E3: formati e fotogrammi dell'esportazione #73
No files matched your search
@@ -123,7 +123,7 @@ Tutto il resto si scrive in casa, dalle specifiche pubbliche dei formati e mai c
|
|||||||
- metadati delle immagini: lettura e scrittura di EXIF (orientamento compreso), profilo ICC e XMP, per copiarli da un formato all'altro (§4.10);
|
- metadati delle immagini: lettura e scrittura di EXIF (orientamento compreso), profilo ICC e XMP, per copiarli da un formato all'altro (§4.10);
|
||||||
- lettori dei contenitori video ISO BMFF (MP4, MOV) e Matroska (MKV, WebM): durata, dimensioni, rotazione, tracce, codec e metadati del contenitore, al posto di ffprobe;
|
- lettori dei contenitori video ISO BMFF (MP4, MOV) e Matroska (MKV, WebM): durata, dimensioni, rotazione, tracce, codec e metadati del contenitore, al posto di ffprobe;
|
||||||
- lettori dei contenitori ASF (WMV, WMA), FLV e MPEG-PS (flusso di programma di ISO/IEC 13818-1, `.mpg`, `.vob`): durata, dimensioni, codec e data dove il contenitore la porta (risposta di Alberto del 18 novembre 2026, tappa C5). Solo lettura dei metadati: i loro video non si rimuxano. Di un MPEG-PS codec e dimensioni vengono dall'intestazione di sequenza MPEG-1 o MPEG-2, o dall'SPS di una traccia H.264 o H.265 (questa solo con il tipo di flusso 0x24 nella mappa del flusso di programma); i suoi campioni, spezzati nei pacchetti PES, non si elencano, quindi nemmeno una traccia H.264 o H.265 dà un fotogramma e la miniatura è la tessera neutra. Fra questi contenitori la miniatura viene solo da un FLV con H.264;
|
- lettori dei contenitori ASF (WMV, WMA), FLV e MPEG-PS (flusso di programma di ISO/IEC 13818-1, `.mpg`, `.vob`): durata, dimensioni, codec e data dove il contenitore la porta (risposta di Alberto del 18 novembre 2026, tappa C5). Solo lettura dei metadati: i loro video non si rimuxano. Di un MPEG-PS codec e dimensioni vengono dall'intestazione di sequenza MPEG-1 o MPEG-2, o dall'SPS di una traccia H.264 o H.265 (questa solo con il tipo di flusso 0x24 nella mappa del flusso di programma); i suoi campioni, spezzati nei pacchetti PES, non si elencano, quindi nemmeno una traccia H.264 o H.265 dà un fotogramma e la miniatura è la tessera neutra. Fra questi contenitori la miniatura viene solo da un FLV con H.264;
|
||||||
- rimuxaggio in MP4, senza ricodifica;
|
- rimuxaggio in MP4, senza ricodifica (MOV, M4V, 3GP, MKV e WebM con H.264 o HEVC e AAC o MP3, tappa E3, §4.10);
|
||||||
- decodificatore H.264 (ITU-T H.264), per i fotogrammi, le miniature dei video importati e i video fermi (§4.10). **Tutto lo standard** (risposta di Alberto del 18 novembre 2026, «Tutto»): profili Baseline (anche non vincolato), Constrained Baseline, Main, Extended (FMO, ASO, fette ridondanti, partizione dei dati, fette SP e SI), High, High 10, High 4:2:2 e High 4:4:4 (Predictive e Intra, con i piani di colore separati e il modo senza perdita), CAVLC 4:4:4 Intra, monocromatico (4:0:0), con la profondità di bit che ogni profilo prevede (fino a 14 bit); video interlacciati (campi, PAFF, MBAFF); CAVLC e CABAC, trasformata 8×8 e matrici di quantizzazione; SVC (allegato G) e MVC (allegato H), di cui per fotogrammi e miniature si usano lo strato con la risoluzione più alta e la vista di base. Un fotogramma con più di 8 bit si porta a 8 bit solo all'uscita, per JPG, PNG e WEBP. Solo un flusso rovinato dice «Fotogramma non disponibile per questo video»;
|
- decodificatore H.264 (ITU-T H.264), per i fotogrammi, le miniature dei video importati e i video fermi (§4.10). **Tutto lo standard** (risposta di Alberto del 18 novembre 2026, «Tutto»): profili Baseline (anche non vincolato), Constrained Baseline, Main, Extended (FMO, ASO, fette ridondanti, partizione dei dati, fette SP e SI), High, High 10, High 4:2:2 e High 4:4:4 (Predictive e Intra, con i piani di colore separati e il modo senza perdita), CAVLC 4:4:4 Intra, monocromatico (4:0:0), con la profondità di bit che ogni profilo prevede (fino a 14 bit); video interlacciati (campi, PAFF, MBAFF); CAVLC e CABAC, trasformata 8×8 e matrici di quantizzazione; SVC (allegato G) e MVC (allegato H), di cui per fotogrammi e miniature si usano lo strato con la risoluzione più alta e la vista di base. Un fotogramma con più di 8 bit si porta a 8 bit solo all'uscita, per JPG, PNG e WEBP. Solo un flusso rovinato dice «Fotogramma non disponibile per questo video»;
|
||||||
- decodificatore H.265/HEVC (ITU-T H.265; risposta di Alberto del 18 novembre 2026, dentro la 0.3.0, tappa C4), per gli stessi usi: tutti i profili della serie di conformità ITU-T H.265.1 scelta per Febe (cartelle `HEVC_v1` e `RExt`, §16 domanda 18, risposta di Alberto del 25 novembre 2026), cioè Main, Main 10, Main Still Picture e le **estensioni di formato (RExt)** dei flussi della serie, che **restano**: 4:0:0, 4:2:2 e 4:4:4 fino a 12 bit, con i loro strumenti (predizione fra componenti, RDPCM, adattamento di Rice, `chroma_qp_offset_list`). Un fotogramma con più di 8 bit si porta a 8 bit solo all'uscita, come per H.264. Non hanno flussi in quella serie e restano fuori la precisione estesa dei profili a 16 bit, l'allineamento del CABAC, lo scalabile (SHVC), il multivista (MV-HEVC), il 3D e i contenuti dello schermo (SCC): un video così dice «Fotogramma non disponibile per questo video»;
|
- decodificatore H.265/HEVC (ITU-T H.265; risposta di Alberto del 18 novembre 2026, dentro la 0.3.0, tappa C4), per gli stessi usi: tutti i profili della serie di conformità ITU-T H.265.1 scelta per Febe (cartelle `HEVC_v1` e `RExt`, §16 domanda 18, risposta di Alberto del 25 novembre 2026), cioè Main, Main 10, Main Still Picture e le **estensioni di formato (RExt)** dei flussi della serie, che **restano**: 4:0:0, 4:2:2 e 4:4:4 fino a 12 bit, con i loro strumenti (predizione fra componenti, RDPCM, adattamento di Rice, `chroma_qp_offset_list`). Un fotogramma con più di 8 bit si porta a 8 bit solo all'uscita, come per H.264. Non hanno flussi in quella serie e restano fuori la precisione estesa dei profili a 16 bit, l'allineamento del CABAC, lo scalabile (SHVC), il multivista (MV-HEVC), il 3D e i contenuti dello schermo (SCC): un video così dice «Fotogramma non disponibile per questo video»;
|
||||||
- VP9, AV1 e gli altri codec video non si decodificano (non richiesti): miniatura con la tessera neutra e «Fotogramma non disponibile per questo video»;
|
- VP9, AV1 e gli altri codec video non si decodificano (non richiesti): miniatura con la tessera neutra e «Fotogramma non disponibile per questo video»;
|
||||||
@@ -219,8 +219,8 @@ A destra un riquadro «Con queste impostazioni» traduce le scelte in conseguenz
|
|||||||
- Deve restare fluida con 200.000 elementi: caricamento a finestre, miniature generate una volta e conservate.
|
- 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. 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).
|
- **File danneggiato o incompleto** (risposta di Alberto del 25 novembre 2026). Un'immagine troncata o rovinata, scaricata o importata (§3, §8.4), si rifiuta e lo dice: tessera neutra nel mosaico e «File danneggiato o incompleto» nel visualizzatore al posto dell'immagine, con le azioni sul file (mostra nella cartella o scarica, elimina) che restano. Il file **resta in libreria** (regola 12): Febe non lo cancella, non lo sostituisce e non lo riscarica da sé. Un HEIC che non si decodifica ha solo la tessera neutra, senza questa scritta (§3).
|
||||||
- Visualizzatore (mockup 02): elemento a tutta altezza, frecce, file della serie, scheda con dati, file e provenienza. Azioni: mostra nella cartella (Windows) o scarica il file (browser), apri su Instagram, elimina dalla libreria. Con l'esportazione (§4.10, traguardo 0.3.0): «Copia in…», «Fotogramma» per i video, «È un video fermo?» a richiesta, e nel pannello File le righe delle copie esterne («Copiato in … · intero», «· fotogramma»).
|
- Visualizzatore (mockup 02): elemento a tutta altezza, frecce, file della serie, scheda con dati, file e provenienza. Azioni: mostra nella cartella (Windows) o scarica il file (browser), apri su Instagram, elimina dalla libreria. Con l'esportazione (§4.10, traguardo 0.3.0): «Copia in…», «Fotogramma» per i video (tappa E3; per un video senza fotogrammi la riga «Fotogramma non disponibile per questo video»), «È un video fermo?» a richiesta (tappa E4), e nel pannello File le righe delle copie esterne («Copiato in … · intero», «· PNG», «· fotogramma a 0:01 · PNG») e dei file convertiti della libreria («Convertito in PNG · 2,1 MB»).
|
||||||
- Eliminare chiede conferma e, per impostazione predefinita, ricorda la scelta: l'elemento resta nel database senza file, nello stato «eliminato», così non viene riscaricato. La conferma offre anche «Eliminalo e lascia che torni». Le copie esterne di un elemento eliminato restano dove sono (§4.10).
|
- 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.
|
- 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) o eliminare. Dal traguardo 0.3.0 un filtro «Copie» (Tutti, Non ancora copiati, Copiati, Tolti o superati) in Libreria e nella scheda dell'account.
|
||||||
|
|
||||||
@@ -259,7 +259,7 @@ Hashtag e luoghi, commenti, elenchi di follower di altri, messaggi diretti, più
|
|||||||
|
|
||||||
### 4.10 Esportazione
|
### 4.10 Esportazione
|
||||||
|
|
||||||
Decisioni di Alberto del 18 novembre 2026 (issue #58, traguardo «0.3.0 — Esportazione», tappe in §15). Dalla tappa E2 (27 novembre 2026) le copie degli originali, accanto all'elenco CSV di §4.8; formati e fotogrammi con E3, video fermi con E4, l'automatica con E5. Fino a E3 ed E4 i loro comandi («Fotogrammi…», «Fotogramma», «È un video fermo?», i formati e la conversione della libreria) mancano dall'interfaccia, non sono spenti; fino a E5 una destinazione in pausa si riprova con «Riprova» o «Riprendi», non con il giro orario.
|
Decisioni di Alberto del 18 novembre 2026 (issue #58, traguardo «0.3.0 — Esportazione», tappe in §15). Dalla tappa E2 (27 novembre 2026) le copie degli originali, accanto all'elenco CSV di §4.8; dalla tappa E3 (28 novembre 2026) i formati delle copie, la conversione della libreria e i fotogrammi («Fotogrammi…», «Fotogramma», i menu dei formati, «Conversione della libreria»); video fermi con E4, l'automatica con E5. Fino a E4 i suoi comandi («È un video fermo?», «Salva il fotogramma») mancano dall'interfaccia, non sono spenti; fino a E5 una destinazione in pausa si riprova con «Riprova» o «Riprendi», non con il giro orario.
|
||||||
|
|
||||||
**Principio.** Un'esportazione copia in una cartella esterna (una **destinazione**) file che sono già in libreria: così come sono, convertiti in un altro formato o come fotogramma di un video. È solo lavoro sul disco: niente Instagram, niente CDN, niente Governatore, niente `action_log`. Un file che manca in libreria non si riscarica: la copia dice «File non presente in libreria».
|
**Principio.** Un'esportazione copia in una cartella esterna (una **destinazione**) file che sono già in libreria: così come sono, convertiti in un altro formato o come fotogramma di un video. È solo lavoro sul disco: niente Instagram, niente CDN, niente Governatore, niente `action_log`. Un file che manca in libreria non si riscarica: la copia dice «File non presente in libreria».
|
||||||
|
|
||||||
@@ -276,7 +276,7 @@ Decisioni di Alberto del 18 novembre 2026 (issue #58, traguardo «0.3.0 — Espo
|
|||||||
**Conversione del formato.** Due impostazioni distinte, **entrambe spente** per impostazione predefinita:
|
**Conversione del formato.** Due impostazioni distinte, **entrambe spente** per impostazione predefinita:
|
||||||
|
|
||||||
- **per le copie**: il formato in cui arrivano i file nella destinazione. Valori predefiniti in Impostazioni → Esportazione, che ogni destinazione e ogni singola «Copia in…» possono cambiare;
|
- **per le copie**: il formato in cui arrivano i file nella destinazione. Valori predefiniti in Impostazioni → Esportazione, che ogni destinazione e ogni singola «Copia in…» possono cambiare;
|
||||||
- **per la libreria**: Febe **aggiunge** all'elemento il file convertito, e l'originale **resta** accanto (regola 12). Il convertito è legato al suo originale: SHA-256, impronta visiva, miniatura, controllo dei doppioni e `_febe.jsonl` restano quelli dell'originale, e il convertito non si riscarica né conta come doppione. Si registra in `media_conversion` (migrazione `0003`, tappa E1; decisione di Alberto del 26 novembre 2026): una riga per file convertito, legata alla riga `media` dell'originale, con formato, percorso, byte, SHA-256 del convertito, data e stato; la tabella `media` non cambia. La conversione la fa la tappa E3.
|
- **per la libreria**: Febe **aggiunge** all'elemento il file convertito, e l'originale **resta** accanto (regola 12). Il convertito è legato al suo originale: SHA-256, impronta visiva, miniatura, controllo dei doppioni e `_febe.jsonl` restano quelli dell'originale, e il convertito non si riscarica né conta come doppione. Si registra in `media_conversion` (migrazione `0003`, tappa E1; decisione di Alberto del 26 novembre 2026): una riga per file convertito, legata alla riga `media` dell'originale, con formato, percorso, byte, SHA-256 del convertito, data e stato; la tabella `media` non cambia. La conversione la fa la tappa E3 (qui sotto, «Conversione della libreria»).
|
||||||
|
|
||||||
| | Scelte | Come |
|
| | Scelte | Come |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
@@ -285,13 +285,21 @@ Decisioni di Alberto del 18 novembre 2026 (issue #58, traguardo «0.3.0 — Espo
|
|||||||
|
|
||||||
- **Con perdita solo se scelto**: l'unica conversione con perdita è JPG, a qualità 92, e la finestra lo dice («con perdita»). PNG, WEBP senza perdita e il rimuxaggio non perdono nulla; un'immagine animata non si converte mai, perché perderebbe i fotogrammi dopo il primo. La trasparenza in JPG diventa bianco.
|
- **Con perdita solo se scelto**: l'unica conversione con perdita è JPG, a qualità 92, e la finestra lo dice («con perdita»). PNG, WEBP senza perdita e il rimuxaggio non perdono nulla; un'immagine animata non si converte mai, perché perderebbe i fotogrammi dopo il primo. La trasparenza in JPG diventa bianco.
|
||||||
- **Metadati: tutti quelli possibili.** Il convertito è la stessa immagine con un'altra estensione: EXIF con l'orientamento (che resta un dato, i pixel non si ruotano), profilo ICC, XMP, nei posti che il formato di arrivo prevede (APP1 e APP2 in JPG, `eXIf`, `iCCP` e `iTXt` in PNG, `EXIF`, `ICCP` e `XMP ` in WEBP); per i video i metadati del contenitore (date, rotazione, lingua delle tracce). La data del file segue `libreria.data-file-pubblicazione`, fotogrammi compresi. Ciò che il formato di arrivo non può tenere lo dice il resoconto.
|
- **Metadati: tutti quelli possibili.** Il convertito è la stessa immagine con un'altra estensione: EXIF con l'orientamento (che resta un dato, i pixel non si ruotano), profilo ICC, XMP, nei posti che il formato di arrivo prevede (APP1 e APP2 in JPG, `eXIf`, `iCCP` e `iTXt` in PNG, `EXIF`, `ICCP` e `XMP ` in WEBP); per i video i metadati del contenitore (date, rotazione, lingua delle tracce). La data del file segue `libreria.data-file-pubblicazione`, fotogrammi compresi. Ciò che il formato di arrivo non può tenere lo dice il resoconto.
|
||||||
|
- **Quale formato** (tappa E3). Per ogni file vale la scelta della singola «Copia in…» («Formato: come la destinazione · Cambia»), poi quella della destinazione («Come le impostazioni generali», il predefinito), poi Impostazioni → Esportazione. Un formato nuovo vale per i file non ancora copiati («Già copiato», qui sotto). Lo stesso formato si riconosce dai byte, non dall'estensione: un `.jpg` che è un PNG si converte in JPG; un WEBP con perdita con «WEBP senza perdita» si copia byte per byte, perché ricodificarlo lo farebbe solo più grande (proposta, §16 domanda 36); un video è già MP4 quando è ISO BMFF con un marchio diverso da quello di QuickTime (`qt `) e con l'estensione `.mp4`.
|
||||||
|
- **Copiati come sono anche** (tappa E3, oltre la tabella; proposta, §16 domande 31 e 38): le immagini CMYK o YCCK e quelle con più di 8 bit per colore verso PNG e WEBP senza perdita, perché i codificatori di Febe sono RGB a 8 bit (verso JPG si convertono: un profilo ICC non RGB è detto «non tenuto», come un profilo grigio verso ogni formato); le immagini oltre 40 megapixel per WEBP e oltre 100 per PNG e JPG, con un lato oltre 16.384 pixel per WEBP, o più grandi di 512 MB. Ognuna con la sua nota («Copiato com'è: immagine CMYK», «Copiato com'è: troppo grande per il formato scelto»). Un EXIF rovinato non ferma la conversione: si lascia fuori, con la nota.
|
||||||
|
- **Rimuxaggio** (tappa E3). MOV, M4V, 3GP e Matroska (MKV, WebM) con una traccia video H.264 o HEVC e al più una traccia audio AAC o MP3 diventano MP4 copiando i campioni uno per uno, senza tenerli tutti in memoria: restano fotogrammi chiave, ordine di presentazione, l'inizio ritardato e il priming dell'AAC (l'elenco di modifiche), la rotazione, la lingua delle tracce e le date. Le tracce in più (codice di tempo, sottotitoli, una seconda traccia audio) si tolgono, e la nota lo dice («Tracce tolte: 1»). Si copia com'è, con il motivo, un video con un altro codec (VP9, AV1, Opus…), senza la configurazione del codec, con tracce Matroska codificate, con più di un taglio nell'elenco di modifiche, o in un contenitore che MP4 non prende così com'è (AVI, ASF, FLV, MPEG-PS).
|
||||||
|
- **Note e spazio** (tappa E3). Le note sono nel resoconto del lavoro (colonne «Come sono» e «Note»), nelle righe del visualizzatore e, previste dall'estensione, nel riepilogo di «Copia in…» («circa 3 HEIC copiati come sono»; «con perdita» quando almeno un file si converte in JPG). I byte del riepilogo sono quelli degli originali, «circa»; il controllo dello spazio della destinazione usa la dimensione del convertito, perché Febe converte prima di controllare.
|
||||||
|
- **Conversione della libreria** (tappa E3). Due impostazioni, Foto e Video, in Impostazioni → Esportazione, «Originale» (cioè spente) per impostazione predefinita. Il convertito si scrive accanto all'originale, nella stessa cartella, con lo stesso nome e l'estensione del formato (`nome.png`; `nome (2).png` se il nome è occupato: mai una sovrascrittura), con le regole di scrittura, i metadati e le note delle copie, e la data del file secondo `libreria.data-file-pubblicazione`. Un file già nel formato scelto, HEIC, AVIF, raw, GIF e WebM non entrano in coda; un'immagine animata o un video che non si rimuxa «non si convertono», e non si riprovano finché il file non cambia. Lavora in sottofondo, un file per volta, mai durante una sessione del motore; lascia il passo a importazione, copie e ricostruzione, che partono subito, e riprende dopo; si mette in pausa quando lo spazio libero della libreria scenderebbe sotto la soglia del disco (10 GB / 5 %) con il file da scrivere. Accenderla chiede «Convertire anche i N file già in libreria?», con lo spazio che occupano gli originali, e la risposta proposta è **«Solo i nuovi»**: un file nuovo (salvato in libreria da quando il formato è quello scelto) entra in coda dopo la sua riga di `_febe.jsonl`, anche se arriva tardi in un elemento vecchio, senza i file che l'elemento aveva già; spegnerla svuota la coda e lascia i convertiti dove sono (proposta, §16 domanda 29). Il convertito **non è mai la fonte di un'esportazione**: «Copia in…», «Fotogrammi…» e il CSV partono sempre dall'originale, che resta il file della libreria. Il visualizzatore mostra i convertiti nel pannello File, con «Scarica» o «Mostra nella cartella» e ciò che non si è tenuto (proposta, §16 domanda 30); Impostazioni → Esportazione e la scheda Esportazione della Dashboard dicono a che punto è («In coda 12 · convertiti 340 · non riusciti 2 · non si convertono 3»), con «Interrompi», «Riprendi» e «Riprova i non riusciti». Solo una scelta esplicita toglie un convertito, sempre insieme al suo originale: «Elimina dalla libreria» (la conferma li conta: «elimino gli elementi interi, 9 file e 2 file convertiti»), la rimozione di un account con i suoi file, «Tieni il più grande» per il file che si scarta; un convertito cambiato fuori da Febe dopo la conversione resta dov'è, e lo si dice. Se l'originale cambia (§4.10, «Superato»), il convertito di prima resta e si rifà quello nuovo. La ricostruzione non converte: riconosce i convertiti accanto agli originali e non li conta fra i file sconosciuti. L'importazione riconosce un convertito della libreria, o una copia convertita o un fotogramma trovati in una destinazione, come «già in libreria» («È una copia convertita (o un fotogramma) di un file già in libreria.»), mai come doppione probabile dell'originale (proposta, §16 domanda 37).
|
||||||
|
|
||||||
**Fotogrammi e video fermi.**
|
**Fotogrammi e video fermi.**
|
||||||
|
|
||||||
- **Fotogrammi a richiesta**, dal visualizzatore (questo istante, uno ogni k secondi, N in tutto, con anteprima) o con «Fotogrammi…» dalla selezione (le foto si saltano, e la finestra lo dice): JPG, PNG o WEBP senza perdita, a piena risoluzione, con i decodificatori H.264 e H.265 (HEVC) di Febe (§3; H.265 dalla tappa C4). Un video in un altro codec (VP9, AV1 e gli altri, non richiesti) dice «Fotogramma non disponibile per questo video». Uscita: «Scarica» (un file, o uno zip per più file) oppure una destinazione.
|
- **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».
|
- **Solo il fotogramma**: l'audio si perde, e la finestra lo dice: «Il fotogramma non ha l'audio».
|
||||||
|
- **Quali fotogrammi** (tappa E3). Gli istanti sono quelli che il lettore del visualizzatore mostra (il tempo di presentazione, con il ritardo iniziale dell'elenco di modifiche). «Questo istante» dà il fotogramma mostrato in quel momento (prima dell'inizio il primo, oltre la fine l'ultimo); dal visualizzatore la finestra si apre all'istante del lettore, con l'anteprima. «Uno ogni k secondi» parte da 0:00 (0, k, 2k… prima della fine), con k di almeno 0,1 secondi; «N in tutto» divide il video in N parti uguali e prende il centro di ognuna, (i + ½) · durata / N (proposta, §16 domanda 33). Limiti (proposta, §16 domanda 38): N da 1 a 1.000, al più 1.000 fotogrammi per video («Più di 1.000 fotogrammi per un video: scegli un intervallo più lungo») e 20.000 per richiesta; le anteprime sono di al più 480 pixel e si fanno in 30 secondi («Il fotogramma richiede troppo tempo: scegli la cartella delle copie»). Il fotogramma è a piena risoluzione, mai ridimensionato, ruotato come il video si vede, e **senza metadati**: non ha EXIF né data del video (proposta, §16 domanda 32). Il formato proposto è **PNG** (proposta, §16 domanda 35); JPG dice «con perdita».
|
||||||
|
- **Nomi e uscite dei fotogrammi** (tappa E3). Il nome è quello del video con un suffisso prima dell'estensione: `_t0m12s340` (minuti, secondi e millesimi dell'istante del fotogramma davvero mostrato) per «Questo istante» e «Uno ogni k secondi», `_f001` (la posizione, con almeno tre cifre) per «N in tutto»; `_fotogramma` resta a «Salva il fotogramma» (E4). «Scarica»: un fotogramma è l'immagine stessa; da 2 a 20 uno zip in qualunque momento; da 21 a 500 uno zip solo fuori dalle sessioni del motore e quando non lavorano importazione, copie o ricostruzione; oltre 500 solo «Nella cartella delle copie» (proposta, §16 domanda 34). Lo zip si scrive mentre si scarica, senza compressione (le immagini sono già compresse), con una cartella per account e i nomi resi unici («nome (2).png»), e si chiama `febe-fotogrammi-AAAA-MM-GG.zip`; la data delle voci segue `libreria.data-file-pubblicazione`. «Nella cartella delle copie» è un lavoro di copia verso la destinazione di ogni account, con gli stessi file dovuti di «Copia in…» (un account che non si esporta si salta e si conta); «Scarica» non guarda le destinazioni. Un video che non dà fotogrammi si salta con la nota «Fotogramma non disponibile per questo video».
|
||||||
|
- **Un fotogramma non fa «Copiato».** La copia di un fotogramma ha la sua identità, con l'istante del fotogramma mostrato in millisecondi (arrotondato in su): lo stesso fotogramma chiesto di nuovo è «già copiato», un altro istante è un'altra copia. Il video resta «Non ancora copiato» finché non c'è una sua copia intera o convertita; un elemento che ha soltanto fotogrammi copiati ha sulla tessera il segno «Solo fotogrammi», e il visualizzatore dice «· fotogramma a 0:01,125 · PNG». Un fotogramma «Tolto» o «Superato» si riscrive a una nuova richiesta esplicita (proposta, §16 domanda 32). «Una copia sola» non vale per i fotogrammi.
|
||||||
- **Video fermo** (mostra sempre la stessa immagine): l'analisi si fa **solo a richiesta**, dal visualizzatore («È un video fermo?») o dalla selezione, mai in sottofondo. Esiti: «Fermo», «In movimento», «Non analizzabile», salvati per SHA-256 (`video_analysis`, con il numero dell'algoritmo per poter rianalizzare). Per un video fermo il visualizzatore mostra «Un'immagine sola per tutto il video: basta un fotogramma» con «Salva il fotogramma»; nelle destinazioni si copia comunque **il video intero**, che tiene l'audio.
|
- **Video fermo** (mostra sempre la stessa immagine): l'analisi si fa **solo a richiesta**, dal visualizzatore («È un video fermo?») o dalla selezione, mai in sottofondo. Esiti: «Fermo», «In movimento», «Non analizzabile», salvati per SHA-256 (`video_analysis`, con il numero dell'algoritmo per poter rianalizzare). Per un video fermo il visualizzatore mostra «Un'immagine sola per tutto il video: basta un fotogramma» con «Salva il fotogramma»; nelle destinazioni si copia comunque **il video intero**, che tiene l'audio.
|
||||||
- Copie, conversioni e analisi lunghe partono fuori dalle sessioni del motore; esportazione, importazione e ricostruzione non girano insieme.
|
- Copie, conversioni e analisi lunghe partono fuori dalle sessioni del motore; esportazione, importazione e ricostruzione non girano insieme. La conversione della libreria gira in sottofondo e cede il passo a tutte e tre (tappa E3); uno zip di più di 20 fotogrammi conta come un lavoro lungo.
|
||||||
|
|
||||||
**Manuale e automatica.**
|
**Manuale e automatica.**
|
||||||
|
|
||||||
@@ -301,11 +309,12 @@ Decisioni di Alberto del 18 novembre 2026 (issue #58, traguardo «0.3.0 — Espo
|
|||||||
**«Già copiato».**
|
**«Già copiato».**
|
||||||
|
|
||||||
- Una riga per copia (`export_copy`). Una copia è identificata da SHA-256 dell'originale, destinazione, **account effettivo** (quello del segmento con il nome dell'account nella cartella generale, o l'account della cartella propria), variante (intero, convertito, fotogramma), formato e istante del fotogramma; la riga tiene anche percorso relativo, byte e SHA-256 della copia, data, stato. Si cerca per SHA-256, non per l'identificativo di Instagram, che gli importati possono non avere: un elemento eliminato con «Eliminalo e lascia che torni» ritrova le sue copie quando torna.
|
- Una riga per copia (`export_copy`). Una copia è identificata da SHA-256 dell'originale, destinazione, **account effettivo** (quello del segmento con il nome dell'account nella cartella generale, o l'account della cartella propria), variante (intero, convertito, fotogramma), formato e istante del fotogramma; la riga tiene anche percorso relativo, byte e SHA-256 della copia, data, stato. Si cerca per SHA-256, non per l'identificativo di Instagram, che gli importati possono non avere: un elemento eliminato con «Eliminalo e lascia che torni» ritrova le sue copie quando torna.
|
||||||
|
- **«Già copiato» guarda il file, non il formato** (tappa E3; proposta, §16 domanda 28, che cambia ciò che seguirebbe dall'identità qui sopra). Un file dovuto è «Copiato» in una destinazione quando ha lì una copia corrente intera o convertita, **in qualunque formato**, ed è «Tolto» o «Superato» quando lo è la sua ultima copia intera o convertita; i fotogrammi non contano. Piano, filtro «Copie», segno sulla tessera, conteggio della scheda dell'account, «Una copia sola» e copia usano questa sola regola, mentre l'identità registrata resta quella completa. Così un formato nuovo vale per i file non ancora copiati, e un file già copiato in un'altra forma si salta con «Già copiato in un altro formato». Per averlo nel formato nuovo: togliere il file vecchio dalla destinazione, «Controlla le copie» lo segna «Tolto», poi «Copia di nuovo». «Copia di nuovo» dal visualizzatore rifà **proprio quella copia** (stessa variante, formato e istante del fotogramma); la casella «Copia di nuovo anche i N tolti o superati» di «Copia in…» usa i formati di adesso.
|
||||||
- Stati di un file: **«Copiato»**, **«Tolto»** (il file non c'è più nella destinazione), **«Superato»** (il file della libreria è cambiato, per esempio dopo «Tieni il più grande» o una ricostruzione), «Non riuscito». Tolto e Superato **non si ricopiano mai da soli**: «Copia di nuovo» a richiesta scrive un file nuovo, e la copia vecchia resta: dal visualizzatore, un file alla volta, o per tutti quelli scelti con la casella «Copia di nuovo anche i N tolti o superati» della finestra «Copia in…», spenta all'apertura (proposta, §16 domanda 25). «Tolto» lo trova «Controlla le copie» (Impostazioni → Esportazione), che guarda soltanto: con la radice della destinazione irraggiungibile non segna nulla come tolto e mette la destinazione in pausa. Neppure dopo la rimozione di un account: le sue copie restano registrate, senza account ma con il suo identificativo di Instagram e il suo nome, e se l'account torna quelle della cartella generale tornano sue, in ogni stato (per identificativo; per nome solo se l'identificativo non era noto); quelle della sua cartella propria tornano quando Alberto gliela ridà.
|
- Stati di un file: **«Copiato»**, **«Tolto»** (il file non c'è più nella destinazione), **«Superato»** (il file della libreria è cambiato, per esempio dopo «Tieni il più grande» o una ricostruzione), «Non riuscito». Tolto e Superato **non si ricopiano mai da soli**: «Copia di nuovo» a richiesta scrive un file nuovo, e la copia vecchia resta: dal visualizzatore, un file alla volta, o per tutti quelli scelti con la casella «Copia di nuovo anche i N tolti o superati» della finestra «Copia in…», spenta all'apertura (proposta, §16 domanda 25). «Tolto» lo trova «Controlla le copie» (Impostazioni → Esportazione), che guarda soltanto: con la radice della destinazione irraggiungibile non segna nulla come tolto e mette la destinazione in pausa. Neppure dopo la rimozione di un account: le sue copie restano registrate, senza account ma con il suo identificativo di Instagram e il suo nome, e se l'account torna quelle della cartella generale tornano sue, in ogni stato (per identificativo; per nome solo se l'identificativo non era noto); quelle della sua cartella propria tornano quando Alberto gliela ridà.
|
||||||
- **Adozione per percorso**: se nel percorso di arrivo c'è già un file, Febe lo adotta come copia invece di scriverne un secondo solo se è proprio quella copia. Per le copie byte per byte vuole lo stesso SHA-256 dell'originale; per i convertiti e i fotogrammi Febe rifà la conversione con le impostazioni di quella copia (i suoi codificatori sono fissi, §3) e vuole lo stesso SHA-256 del file trovato. La sola dimensione non basta mai. Se non coincide, il nome è occupato: Febe scrive su un nome libero e il file trovato resta com'è. Copre un database perso, un backup vecchio, due istanze sulla stessa cartella; «Riconosci le copie già presenti» lo fa per tutta la destinazione.
|
- **Adozione per percorso**: se nel percorso di arrivo c'è già un file, Febe lo adotta come copia invece di scriverne un secondo solo se è proprio quella copia. Per le copie byte per byte vuole lo stesso SHA-256 dell'originale; per i convertiti e i fotogrammi Febe rifà la conversione con le impostazioni di quella copia (i suoi codificatori sono fissi, §3) e vuole lo stesso SHA-256 del file trovato (dalla tappa E3: prima la lunghezza, poi lo SHA-256; per un rimuxaggio la lunghezza si sa prima di scrivere; una riga orfana si ricollega solo se ha la stessa forma e lo stesso SHA-256 della copia). La sola dimensione non basta mai. Se non coincide, il nome è occupato: Febe scrive su un nome libero e il file trovato resta com'è. Copre un database perso, un backup vecchio, due istanze sulla stessa cartella; «Riconosci le copie già presenti» lo fa per tutta la destinazione.
|
||||||
- Per elemento, calcolato al momento (nessuna tabella derivata): «Copiato», «Copiato in parte», «Non ancora copiato»; un video copiato solo come fotogramma lo dice («fotogramma», non «intero»).
|
- Per elemento, calcolato al momento (nessuna tabella derivata): «Copiato», «Copiato in parte», «Non ancora copiato»; un video copiato solo come fotogramma lo dice («fotogramma», non «intero»). Contano solo le copie intere o convertite dei file dovuti; un elemento senza nessuna di queste ma con almeno un fotogramma copiato ha il segno «Solo fotogrammi» (tappa E3).
|
||||||
- **File dovuti** (tappa E2): un file è dovuto quando è presente in libreria (scaricato o importato, con il suo SHA-256), il suo account ha «Esporta questo account» acceso e una destinazione effettiva, e il suo tipo di contenuto è fra quelli della destinazione (post foto, post video, storie, evidenza, taggati, profilo; una storia in una raccolta in evidenza è anche evidenza). Il segno sulla tessera, il filtro «Copie», il conteggio della scheda dell'account e «Copia in…» considerano solo i file dovuti (proposta, §16 domanda 26), così «312 su 1.204 non ancora copiati» è proprio ciò che «Copia in…» copierebbe. Le tre scelte del filtro dividono i file dovuti senza sovrapporsi: «Copiati» (copia corrente «Copiato»), «Tolti o superati» (l'ultima copia è «Tolto» o «Superato»), «Non ancora copiati» (tutti gli altri, «Non riuscito» compreso, che la copia successiva riprova). Un account spento non ha file dovuti.
|
- **File dovuti** (tappa E2): un file è dovuto quando è presente in libreria (scaricato o importato, con il suo SHA-256), il suo account ha «Esporta questo account» acceso e una destinazione effettiva, e il suo tipo di contenuto è fra quelli della destinazione (post foto, post video, storie, evidenza, taggati, profilo; una storia in una raccolta in evidenza è anche evidenza). Il segno sulla tessera, il filtro «Copie», il conteggio della scheda dell'account e «Copia in…» considerano solo i file dovuti (proposta, §16 domanda 26), così «312 su 1.204 non ancora copiati» è proprio ciò che «Copia in…» copierebbe. Le tre scelte del filtro dividono i file dovuti senza sovrapporsi: «Copiati» (copia corrente «Copiato»), «Tolti o superati» (l'ultima copia è «Tolto» o «Superato»), «Non ancora copiati» (tutti gli altri, «Non riuscito» compreso, che la copia successiva riprova). Un account spento non ha file dovuti.
|
||||||
- Dove si vede: un piccolo segno sulla tessera (solo se esiste almeno una destinazione; differenza voluta rispetto al mockup 01), le righe del pannello File del visualizzatore («Copiato in Disco USB il 3 novembre · intero», «· fotogramma a 0:01 · JPG», «Tolto» con «Copia di nuovo»), il conteggio nella scheda dell'account («312 su 1.204 non ancora copiati»), il filtro «Copie».
|
- Dove si vede: un piccolo segno sulla tessera (solo se esiste almeno una destinazione; differenza voluta rispetto al mockup 01), le righe del pannello File del visualizzatore («Copiato in Disco USB il 3 novembre · intero», «· PNG», «· fotogramma a 0:01 · JPG», «Tolto» con «Copia di nuovo», con le note su una seconda riga; il segno «Solo fotogrammi» sulla tessera), il conteggio nella scheda dell'account («312 su 1.204 non ancora copiati»), il filtro «Copie».
|
||||||
|
|
||||||
**Casi particolari.**
|
**Casi particolari.**
|
||||||
|
|
||||||
@@ -783,7 +792,7 @@ Tabelle principali. Completa colonne e indici dove serve, ma non cambiare i conc
|
|||||||
| `event` | Cronologia leggibile per l'interfaccia |
|
| `event` | Cronologia leggibile per l'interfaccia |
|
||||||
| `following` | Copia locale dell'elenco dei profili seguiti, con data di lettura |
|
| `following` | Copia locale dell'elenco dei profili seguiti, con data di lettura |
|
||||||
| `import_run`, `import_file` | Importazioni e loro file, con esito e decisione |
|
| `import_run`, `import_file` | Importazioni e loro file, con esito e decisione |
|
||||||
| `export_destination`, `export_account`, `export_copy`, `export_run`, `export_item`, `video_analysis`, `media_conversion` | Migrazione `0003` (tappa E1 del traguardo 0.3.0, §4.10; la `0002` è della tappa D1), usate dalla tappa E2 (copie degli originali; `video_analysis` e `media_conversion` aspettano E4 ed E3): destinazioni di esportazione (generale o di un account, con una colonna esplicita per l'ambito, `General` o `Account`; una riga è una cartella per sempre: togliere una destinazione o cambiarne la cartella la ritira, e le copie registrate restano; rimuovere un account la lascia senza account, inattiva («Automatica» spenta, «Solo i nuovi» dimenticato, anche quando l'account torna), e ne tiene il nome: non la cancella); l'interruttore «Esporta questo account» in `export_account`, che se ne va con l'account (nessuna riga vuol dire acceso, §4.10); copie fatte, per SHA-256 dell'originale, destinazione, account effettivo, variante e formato effettivi e istante del fotogramma, con il loro stato (§4.10), che restano anche se l'elemento si elimina e tengono lo SHA-256 del file che ha preso il posto dell'originale per «Superato»; rimuovere un account toglie l'account alle sue copie e ne tiene identificativo di Instagram e nome, così quelle della cartella generale, anche «Tolto» e «Superato», tornano all'account aggiunto di nuovo; lavori di esportazione e loro file (sul modello di `import_run` e `import_file`, per interrompere e riprendere); esito dell'analisi dei video fermi per SHA-256 e numero dell'algoritmo; file convertiti per la libreria in `media_conversion`, una riga per file legata alla riga `media` dell'originale (decisione di Alberto del 26 novembre 2026): la tabella `media` non cambia. Impostazioni in `setting` con chiavi `esportazione.*` (`esportazione.formato-foto`, `esportazione.formato-video`, `esportazione.libreria-formato-foto`, `esportazione.libreria-formato-video`, `esportazione.stesso-post`); nessuna colonna nuova in `account` |
|
| `export_destination`, `export_account`, `export_copy`, `export_run`, `export_item`, `video_analysis`, `media_conversion` | Migrazione `0003` (tappa E1 del traguardo 0.3.0, §4.10; la `0002` è della tappa D1), usate dalla tappa E2 (copie degli originali) e dalla tappa E3 (copie convertite e fotogrammi in `export_copy` ed `export_item`, conversione della libreria in `media_conversion`, senza una migrazione nuova; `video_analysis` aspetta E4): destinazioni di esportazione (generale o di un account, con una colonna esplicita per l'ambito, `General` o `Account`; una riga è una cartella per sempre: togliere una destinazione o cambiarne la cartella la ritira, e le copie registrate restano; rimuovere un account la lascia senza account, inattiva («Automatica» spenta, «Solo i nuovi» dimenticato, anche quando l'account torna), e ne tiene il nome: non la cancella); l'interruttore «Esporta questo account» in `export_account`, che se ne va con l'account (nessuna riga vuol dire acceso, §4.10); copie fatte, per SHA-256 dell'originale, destinazione, account effettivo, variante e formato effettivi e istante del fotogramma, con il loro stato (§4.10), che restano anche se l'elemento si elimina e tengono lo SHA-256 del file che ha preso il posto dell'originale per «Superato»; rimuovere un account toglie l'account alle sue copie e ne tiene identificativo di Instagram e nome, così quelle della cartella generale, anche «Tolto» e «Superato», tornano all'account aggiunto di nuovo; lavori di esportazione e loro file (sul modello di `import_run` e `import_file`, per interrompere e riprendere); esito dell'analisi dei video fermi per SHA-256 e numero dell'algoritmo; file convertiti per la libreria in `media_conversion`, una riga per file legata alla riga `media` dell'originale (decisione di Alberto del 26 novembre 2026): la tabella `media` non cambia. Le note di un file di un lavoro (`export_item.note`) e l'ultimo errore di una conversione (`media_conversion.last_error`) sono elenchi di codici separati da spazi; per una conversione riuscita `last_error` dice ciò che non si è tenuto (tappa E3, `docs/decisioni.md`). Impostazioni in `setting` con chiavi `esportazione.*` (`esportazione.formato-foto`, `esportazione.formato-video`, `esportazione.libreria-formato-foto`, `esportazione.libreria-formato-video`, `esportazione.stesso-post`); nessuna colonna nuova in `account` |
|
||||||
|
|
||||||
Vincoli che contano:
|
Vincoli che contano:
|
||||||
|
|
||||||
@@ -907,7 +916,7 @@ Ogni riga è un file in `docs/mockup/`. I dati sono inventati: gli account che f
|
|||||||
|
|
||||||
Schermate senza mockup, da comporre con gli elementi del foglio di stile: Scheda account → Cronologia (elenco dei controlli con esito); Impostazioni → Notifiche, Dati e copie di sicurezza, Informazioni; revisione dei doppioni dopo uno scaricamento (lo stesso confronto del mockup 09); primo avvio (la schermata vuota del mockup 13 con i due pulsanti, nella Libreria vuota; nella Dashboard, che `/` apre per prima, lo stesso benvenuto in un riquadro compatto sopra il cruscotto finché non c'è nessun account, §7.9); pagina di errore di configurazione (§8.2, §11).
|
Schermate senza mockup, da comporre con gli elementi del foglio di stile: Scheda account → Cronologia (elenco dei controlli con esito); Impostazioni → Notifiche, Dati e copie di sicurezza, Informazioni; revisione dei doppioni dopo uno scaricamento (lo stesso confronto del mockup 09); primo avvio (la schermata vuota del mockup 13 con i due pulsanti, nella Libreria vuota; nella Dashboard, che `/` apre per prima, lo stesso benvenuto in un riquadro compatto sopra il cruscotto finché non c'è nessun account, §7.9); pagina di errore di configurazione (§8.2, §11).
|
||||||
|
|
||||||
Schermate dell'esportazione (§4.10, traguardo 0.3.0), anche queste senza mockup, composte dai mockup esistenti (decisione di Alberto del 18 novembre 2026): Impostazioni → Esportazione (cartella generale, formati predefiniti delle copie, conversione della libreria, «Una copia per account» o «Una copia sola», nota su `/esporta` in Docker; dai mockup 08 e 07); finestra della destinazione (cartella, tipi, formati, schema con anteprima, «Automatica» con la domanda «Solo i nuovi»; dal mockup 08 e dai dialoghi del 13); blocco «Copie esterne» nella scheda account → Impostazioni, sotto «Cartella» (mockup 05); finestra «Copia in…» con il riepilogo («312 file · 41 già copiati, saltati · 3 HEIC copiati come sono · circa 4,2 GB», con «con perdita» quando serve) e finestra «Fotogrammi…» (dialoghi del 13 e mockup 09); in Libreria e nella scheda account il menu dell'icona CSV («Esporta l'elenco (CSV)», «Copia i file in…»), «Copia in…» e «Fotogrammi…» nella barra della selezione, il filtro «Copie» e il segno sulla tessera (mockup 01 e 12); nel visualizzatore «Copia in…», «Fotogramma», «È un video fermo?» e le righe delle copie nel pannello File (mockup 02); scheda «Esportazione» nella Dashboard con avanzamento, Interrompi, Riprendi e resoconto (mockup 06 e passo 2 del 09). Le differenze rispetto ai mockup da cui nascono vanno in `docs/schermate/differenze.md`.
|
Schermate dell'esportazione (§4.10, traguardo 0.3.0), anche queste senza mockup, composte dai mockup esistenti (decisione di Alberto del 18 novembre 2026): Impostazioni → Esportazione (cartella generale, «Formati delle copie», «Conversione della libreria» con la domanda «Convertire anche i N file già in libreria?» e la riga di stato con «Interrompi», «Riprendi» e «Riprova i non riusciti», «Una copia per account» o «Una copia sola», nota su `/esporta` in Docker; dai mockup 08 e 07); finestra della destinazione (cartella, tipi, formati con «Come le impostazioni generali», schema con anteprima, e dalla tappa E5 «Automatica» con la domanda «Solo i nuovi»; dal mockup 08 e dai dialoghi del 13); blocco «Copie esterne» nella scheda account → Impostazioni, sotto «Cartella» (mockup 05); finestra «Copia in…» con il riepilogo («312 file · 41 già copiati, saltati · circa 3 HEIC copiati come sono · circa 4,2 GB», con «con perdita» quando serve) e la riga «Formato: come la destinazione · Cambia», e finestra «Fotogrammi…» (dialoghi del 13 e mockup 09: «Questo istante», «Uno ogni k secondi», «N in tutto», le anteprime, il formato, «Scarica» o «Nella cartella delle copie»); in Libreria e nella scheda account il menu dell'icona CSV («Esporta l'elenco (CSV)», «Copia i file in…»), «Copia in…» e «Fotogrammi…» nella barra della selezione, il filtro «Copie» e il segno sulla tessera, anche «Solo fotogrammi» (mockup 01 e 12); nel visualizzatore «Copia in…», «Fotogramma», dalla tappa E4 «È un video fermo?», e nel pannello File le righe delle copie con la loro forma e le righe dei file convertiti (mockup 02); scheda «Esportazione» nella Dashboard con avanzamento, Interrompi, Riprendi, il riquadro «Conversione della libreria» e il resoconto con «Come sono» e «Note» (mockup 06 e passo 2 del 09). Le differenze rispetto ai mockup da cui nascono vanno in `docs/schermate/differenze.md`.
|
||||||
|
|
||||||
Schermate della tappa D1 (issue #59, traguardo 0.3.0), anche queste senza mockup, composte dai mockup esistenti (decisione di Alberto del 25 novembre 2026):
|
Schermate della tappa D1 (issue #59, traguardo 0.3.0), anche queste senza mockup, composte dai mockup esistenti (decisione di Alberto del 25 novembre 2026):
|
||||||
|
|
||||||
@@ -1175,6 +1184,17 @@ Falle quando arrivi al punto indicato, una per volta, proponendo la risposta del
|
|||||||
| 25 | Nella finestra «Copia in…» (§4.10) si offre «Copia di nuovo anche i N tolti o superati», o «Copia di nuovo» resta solo nel visualizzatore, un file alla volta? | E2, prima di unire | Si offre nella finestra, spenta all'apertura: senza la casella i tolti e i superati si saltano e si contano. Così fa la tappa E2 |
|
| 25 | Nella finestra «Copia in…» (§4.10) si offre «Copia di nuovo anche i N tolti o superati», o «Copia di nuovo» resta solo nel visualizzatore, un file alla volta? | E2, prima di unire | Si offre nella finestra, spenta all'apertura: senza la casella i tolti e i superati si saltano e si contano. Così fa la tappa E2 |
|
||||||
| 26 | Il conteggio della scheda dell'account, il filtro «Copie» e il segno sulla tessera (§4.10) considerano solo i file dei tipi scelti per la destinazione (con il solo «post foto», le storie non sono dovute)? | E2, prima di unire | Sì, solo i file dovuti (§4.10, «File dovuti»), così «312 su 1.204 non ancora copiati» è ciò che «Copia in…» copierebbe. Così fa la tappa E2 |
|
| 26 | Il conteggio della scheda dell'account, il filtro «Copie» e il segno sulla tessera (§4.10) considerano solo i file dei tipi scelti per la destinazione (con il solo «post foto», le storie non sono dovute)? | E2, prima di unire | Sì, solo i file dovuti (§4.10, «File dovuti»), così «312 su 1.204 non ancora copiati» è ciò che «Copia in…» copierebbe. Così fa la tappa E2 |
|
||||||
| 27 | Il margine di spazio libero delle destinazioni (§4.10, «più un margine»): quanto? | E2, prima di unire | 64 MB oltre al prossimo file. Così fa la tappa E2 |
|
| 27 | Il margine di spazio libero delle destinazioni (§4.10, «più un margine»): quanto? | E2, prima di unire | 64 MB oltre al prossimo file. Così fa la tappa E2 |
|
||||||
|
| 28 | Formati delle copie (§4.10, «Già copiato»): se il formato cambia (per esempio da Originale a JPG), i file già copiati nella forma di prima si copiano di nuovo? L'identità di una copia comprende il formato, quindi la risposta cambia che cosa vuol dire «già copiato» | E3, prima di unire | No: «già copiato» guarda il file, non il formato, e il formato nuovo vale per i file non ancora copiati; un file già copiato in un'altra forma si salta con «Già copiato in un altro formato». Per averlo nella forma nuova si toglie il file vecchio dalla destinazione, «Controlla le copie» lo segna «Tolto», poi «Copia di nuovo». L'alternativa è «già copiato» per formato: un cambio ricopierebbe ogni file nella forma nuova accanto a quella vecchia. Così fa la tappa E3 |
|
||||||
|
| 29 | Conversione della libreria accesa (§4.10): si convertono solo i file nuovi o anche quelli già in libreria? Quando entra in coda un file nuovo? Che cosa succede quando si spegne? | E3, prima di unire | Si chiede, con «Solo i nuovi» come risposta proposta e «Anche i N già in libreria» (con lo spazio degli originali) come l'altra; un file nuovo entra in coda dopo la sua riga di `_febe.jsonl`; spenta, la coda si svuota e i convertiti restano dove sono. Così fa la tappa E3 |
|
||||||
|
| 30 | Il visualizzatore mostra i file convertiti della libreria accanto all'originale, con ciò che non si è tenuto? | E3, prima di unire | Sì, nel pannello File: «Convertito in PNG · 2,1 MB», con «Scarica» o «Mostra nella cartella» e le perdite su una seconda riga. Così fa la tappa E3 |
|
||||||
|
| 31 | Immagini con più di 8 bit per colore o CMYK verso PNG o WEBP senza perdita: i codificatori di Febe sono RGB a 8 bit. Si copia l'originale con una nota o si converte lo stesso? E un profilo ICC grigio, che l'uscita RGB non tiene? | E3, prima di unire | Si copia l'originale con una nota; verso JPG si convertono (JPG perde comunque, e il profilo CMYK si dice «non tenuto»); un profilo ICC grigio si dice «non tenuto». Così fa la tappa E3 |
|
||||||
|
| 32 | Fotogrammi (§4.10): nomi `_t0m12s340` per un istante e per «uno ogni k secondi», `_f001` per «N in tutto», `_fotogramma` tenuto per E4; l'istante del nome e di «già copiato» è quello del fotogramma davvero mostrato, in millesimi arrotondati in su. I fotogrammi si ruotano come il video si vede e non hanno metadati. Un fotogramma «Tolto» o «Superato» si riscrive a una nuova richiesta. Va bene? | E3, prima di unire | Sì. Così fa la tappa E3 |
|
||||||
|
| 33 | «N in tutto»: fotogrammi al centro di N parti uguali ((i + ½) · durata / N)? «Uno ogni k secondi» da 0:00? | E3, prima di unire | Sì a tutti e due. Così fa la tappa E3 |
|
||||||
|
| 34 | «Scarica» di più fotogrammi: uno zip; fino a 20 in qualunque momento; da 21 a 500 solo fuori dalle sessioni del motore e quando non lavorano importazione, copie o ricostruzione; oltre 500 solo «Nella cartella delle copie». Va bene? | E3, prima di unire | Sì. Così fa la tappa E3 |
|
||||||
|
| 35 | Formato proposto per i fotogrammi? | E3, prima di unire | PNG: nessuna perdita, piena risoluzione. Così fa la tappa E3 |
|
||||||
|
| 36 | Un WEBP con perdita con «WEBP senza perdita»: si copia byte per byte o si ricodifica senza perdita? | E3, prima di unire | Byte per byte: è lo stesso formato, e ricodificarlo lo farebbe solo più grande. Così fa la tappa E3 |
|
||||||
|
| 37 | Importare una copia convertita o un fotogramma trovati in una destinazione (o un convertito della libreria): si riconosce («È una copia convertita (o un fotogramma) di un file già in libreria.») invece di proporlo come doppione probabile dell'originale? | E3, prima di unire | Sì, «già in libreria», mai una coppia di doppioni. Così fa la tappa E3 |
|
||||||
|
| 38 | Limiti: al più 1.000 fotogrammi per video e 20.000 per richiesta, «uno ogni k secondi» con k di almeno 0,1 s, N al più 1.000; foto copiate come sono oltre 40 megapixel (WEBP) o 100 (JPG e PNG), con un lato oltre 16.384 pixel per WEBP, oltre 512 MB; anteprime di al più 480 pixel entro 30 secondi; zip di al più 500 fotogrammi. Vanno bene? Alberto non ha dato numeri | E3, prima di unire | Sì: sono i limiti di memoria e di tempo di un server di casa. Così fa la tappa E3 |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -1556,6 +1576,14 @@ Icone: fino alla tappa C6 della 0.3.0 erano quelle di Lucide (licenza ISC), con
|
|||||||
| Fotogramma | `Frame` | Un'immagine presa da un video |
|
| 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: basta un fotogramma |
|
||||||
| Rimuxaggio | `Remux` | Passaggio di un video in un altro contenitore senza ricodifica |
|
| Rimuxaggio | `Remux` | Passaggio di un video in un altro contenitore senza ricodifica |
|
||||||
|
| Formato delle copie | `ExportFormat` | Originale, JPG, PNG, WEBP senza perdita, MP4: generale, della destinazione o della singola «Copia in…» (§4.10) |
|
||||||
|
| Copia convertita | `ExportVariant.Converted` | Una copia esterna in un altro formato; con l'intera e il fotogramma, una delle tre varianti di una copia (§4.10) |
|
||||||
|
| Copiato com'è | `AsIs` (codici `AsIs…`) | Un file che non si converte (HEIC, raw, animato, CMYK…) e si copia byte per byte, con una nota (§4.10) |
|
||||||
|
| Con perdita | `Lossy` | Una conversione che non tiene tutti i pixel: solo JPG, a qualità 92 (§4.10) |
|
||||||
|
| Conversione della libreria | `LibraryConversion` | Il lavoro in sottofondo che aggiunge accanto all'originale il file convertito nel formato scelto per la libreria (§4.10) |
|
||||||
|
| File convertito | `MediaConversion` | Un file aggiunto dalla conversione della libreria, legato al suo originale (`media_conversion`, §8.3) |
|
||||||
|
| Solo fotogrammi | `ExportMark.FrameOnly` | Il segno di un elemento che di copiato ha soltanto fotogrammi: non conta come «Copiato» (§4.10) |
|
||||||
|
| Note | `ExportText.Notes`, codici | Ciò che una copia o una conversione dice di sé: copiata com'è, che cosa non ha tenuto, perché si è saltata (§4.10) |
|
||||||
| Dashboard | `Dashboard` | La pagina iniziale e cruscotto del motore, prima voce della barra laterale; prima si chiamava Attività (§7.9) |
|
| Dashboard | `Dashboard` | La pagina iniziale e cruscotto del motore, prima voce della barra laterale; prima si chiamava Attività (§7.9) |
|
||||||
| Cosa scaricare prima | `DownloadOrder` | L'ordine dei tipi (storie, evidenza, post, reel, taggati) che pesa sulle visite dopo il Giro dei seguiti e sulla coda dei file, generale o di un account (§7.2) |
|
| Cosa scaricare prima | `DownloadOrder` | L'ordine dei tipi (storie, evidenza, post, reel, taggati) che pesa sulle visite dopo il Giro dei seguiti e sulla coda dei file, generale o di un account (§7.2) |
|
||||||
| Raggruppa i post | `MosaicMode.Grouped` | Il mosaico con una tessera per elemento, il predefinito (§4.6) |
|
| Raggruppa i post | `MosaicMode.Grouped` | Il mosaico con una tessera per elemento, il predefinito (§4.6) |
|
||||||
|
|||||||
@@ -629,3 +629,31 @@ Ogni scelta tecnica presa strada facendo, con data e motivo (specifica §15).
|
|||||||
| 2026-11-27 | Tappa E2, revisione: **«Una copia sola»** ha una regola sola in piano, filtro «Copie», visualizzatore e copiatore: conta una copia nella destinazione dell'account stesso, o una copia di **un altro account** (mai una riga generale senza account) in una destinazione in uso. `FindCopiedElsewhereAsync` riceve l'account da escludere. «Storia» del filtro comprende ogni riga «Tolto» o «Superato», con o senza data | I quattro punti davano risposte diverse per lo stesso file |
|
| 2026-11-27 | Tappa E2, revisione: **«Una copia sola»** ha una regola sola in piano, filtro «Copie», visualizzatore e copiatore: conta una copia nella destinazione dell'account stesso, o una copia di **un altro account** (mai una riga generale senza account) in una destinazione in uso. `FindCopiedElsewhereAsync` riceve l'account da escludere. «Storia» del filtro comprende ogni riga «Tolto» o «Superato», con o senza data | I quattro punti davano risposte diverse per lo stesso file |
|
||||||
| 2026-11-27 | Tappa E2, revisione: il controllo della cartella confronta anche **dove sta davvero** la cartella (`FolderIdentity`): su Windows il percorso finale (`GetFinalPathNameByHandle`, che risolve collegamenti, giunzioni, `subst` e unità di rete), su Linux `realpath` più il dispositivo `major:minor` e la cartella del suo file system letti da `/proc/self/mountinfo` (un bind mount di una cartella della libreria è dentro la radice del montaggio della libreria). Su Windows le giunzioni **sotto** la cartella scelta non si cercano | SPECIFICA §4.10, «Cartelle rifiutate»: il confronto per testo e il file di prova non vedevano un collegamento né un bind mount di una sottocartella |
|
| 2026-11-27 | Tappa E2, revisione: il controllo della cartella confronta anche **dove sta davvero** la cartella (`FolderIdentity`): su Windows il percorso finale (`GetFinalPathNameByHandle`, che risolve collegamenti, giunzioni, `subst` e unità di rete), su Linux `realpath` più il dispositivo `major:minor` e la cartella del suo file system letti da `/proc/self/mountinfo` (un bind mount di una cartella della libreria è dentro la radice del montaggio della libreria). Su Windows le giunzioni **sotto** la cartella scelta non si cercano | SPECIFICA §4.10, «Cartelle rifiutate»: il confronto per testo e il file di prova non vedevano un collegamento né un bind mount di una sottocartella |
|
||||||
| 2026-11-27 | Tappa E2, revisione: lo **sfoglia delle cartelle** (`/api/export/folders`) ha un tempo massimo per l'elenco e uno per ogni sottocartella (guardate in parallelo; oltre il tempo «senza sottocartelle»); il piano dice `HasDestination`, e «Copia in…» scrive «Nessuna cartella» solo quando non ce n'è nessuna, altrimenti «file di account che non si esportano». Il visualizzatore tiene «In copia…» dopo «Copia di nuovo» e rilegge le copie alla fine del lavoro; la Dashboard fa una lettura per volta | Una condivisione morta bloccava il dialogo; le altre erano parole sbagliate o letture doppie |
|
| 2026-11-27 | Tappa E2, revisione: lo **sfoglia delle cartelle** (`/api/export/folders`) ha un tempo massimo per l'elenco e uno per ogni sottocartella (guardate in parallelo; oltre il tempo «senza sottocartelle»); il piano dice `HasDestination`, e «Copia in…» scrive «Nessuna cartella» solo quando non ce n'è nessuna, altrimenti «file di account che non si esportano». Il visualizzatore tiene «In copia…» dopo «Copia di nuovo» e rilegge le copie alla fine del lavoro; la Dashboard fa una lettura per volta | Una condivisione morta bloccava il dialogo; le altre erano parole sbagliate o letture doppie |
|
||||||
|
| 2026-11-28 | Tappa E3: lo **zip dei fotogrammi** si scrive con l'API asincrona di `ZipArchive` (`CreateAsync`, `OpenAsync`, `DisposeAsync`) su `Response.Body`, senza abilitare l'I/O sincrono di Kestrel: .NET 10 scrive ancora in modo sincrono il piccolo descrittore di ogni voce, che `FrameService` tiene in memoria (al più 64 KB) e manda con la scrittura asincrona seguente. Il video della dimostrazione è scritto in casa (`H264PcmWriter`: solo macroblocchi I_PCM, 240×432, 8 fotogrammi al secondo, 2 s) | Un `Write` sincrono sul corpo della risposta è rifiutato da Kestrel; abilitarlo terrebbe un thread fermo per ogni lettore lento |
|
||||||
|
| 2026-11-28 | Tappa E3: **«già copiato» per file, in qualunque forma** (proposta, §16 domanda 28). Un file dovuto è «Copiato» quando ha una copia corrente intera o convertita in qualunque formato; «Tolto» o «Superato» quando lo è la sua ultima copia intera o convertita; i fotogrammi non contano mai (`variant <> 'Frame'` in `CopyStatesSql`, `ReplacedCopySql`, `ReplacedStatesSql`, `CopiedElsewhereSql` e nei rami «Non riuscito», «Tolti o superati» e «Storia» del filtro). Piano, filtro, segni, conteggio dell'account, «Una copia sola» e copiatore leggono la stessa regola (`ListCurrentCopiesAnyFormAsync`, `FindLatestCopyAnyFormAsync`, `FindCopiedElsewhereAsync(sha, exceptAccountId)`, tutte su `ix_export_copy_sha256`); l'identità registrata resta quella completa di §4.10 (`ux_export_copy_identity`). Per lo stato di un file vale «Copiato» > «Non riuscito» > l'ultima riga «Tolto»/«Superato», come il filtro di E2, dove «Non ancora copiati» comprende i non riusciti. Dopo una copia riuscita le righe «Non riuscito» delle altre forme dello stesso file si tolgono (`ClearFailedAsync`): non hanno file | Con l'identità completa un cambio di formato ricopierebbe ogni file accanto a quello vecchio; la regola sola evita che piano, filtro e copiatore dicano cose diverse |
|
||||||
|
| 2026-11-28 | Tappa E3: **richiesta ed esito**. `export_item` tiene ciò che si è chiesto (`Converted` + `Jpg`, `Frame` + `Png` + istante chiesto), `export_copy` ciò che è uscito (un HEIC chiesto in JPG è una copia `Whole`/`Original` con la nota). `UpdateItemsAsync` non cambia mai variante, formato e istante di un file. Le scelte di un lavoro di fotogrammi e il «Copia di nuovo» esatto stanno in `setting` (`esportazione.lavoro.{id}.fotogrammi` = `Istante`, `Ogni` o `Numero:N`; `esportazione.lavoro.{id}.esatta`), tolte prima di scrivere quelle di un lavoro nuovo con lo stesso numero. Nessuna migrazione `0005` | Il commento della `0003` su `export_item`; la ripresa di un lavoro deve rifare la stessa richiesta |
|
||||||
|
| 2026-11-28 | Tappa E3: **il formato di una copia** si sceglie così: la scelta della singola «Copia in…», poi quella della destinazione (le colonne `photo_format`/`video_format` di `export_destination` già nella `0003`, `null` = «Come le impostazioni generali»), poi `esportazione.formato-foto`/`-video`. Cambiare il formato di una destinazione non la ritira (lo fa solo la cartella). Sul filo i formati restano quelli di E2 (`original`, `jpg`, `png`, `webplossless`, `mp4`); `PUT /api/export/settings` è parziale e risponde `{ message, overview, queued }`, così il JavaScript che legge `message` continua a funzionare | SPECIFICA §4.10, «per le copie»: valori predefiniti che destinazione e «Copia in…» possono cambiare |
|
||||||
|
| 2026-11-28 | Tappa E3: **quando una foto si converte** (`ImageConverter.Check`): il formato si riconosce dai byte (`ImageFormatSniffer`), non dall'estensione; stesso formato → copia byte per byte (anche un WEBP con perdita verso «WEBP senza perdita», proposta, §16 domanda 36); HEIF/AVIF, TIFF e raw, ciò che non si identifica, le immagini animate (presenza di `acTL`, di `ANIM`/`ANMF`, GIF con più di un fotogramma), CMYK/YCCK e più di 8 bit verso PNG e WEBP, oltre 40 megapixel per WEBP o 100 per PNG e JPG, un lato WEBP oltre 16.384, un file oltre 512 MiB → copiato com'è con il suo codice (`AsIs…`; proposte, §16 domande 31 e 38). JPG a qualità 92, 4:4:4, trasparenza su bianco (`TransparencyWhite`). I metadati si ripuliscono **prima** dei codificatori: ciò che il formato non tiene (EXIF oltre 65.533 byte in JPG, EXIF senza intestazione TIFF, ICC non RGB o in più di 255 pezzi, IPTC, altri blocchi, testi, commento troppo lungo, XMP esteso) diventa un codice `Lost…`, mai un'eccezione; i codificatori tengono i loro controlli per chi li chiama direttamente | La memoria di un server di casa (il WEBP senza perdita vuole circa 24-28 byte per pixel: 40 megapixel sono circa 1,1 GB) e la regola «ciò che non si tiene lo dice il resoconto» |
|
||||||
|
| 2026-11-28 | Tappa E3: **stesse conversioni, stessi byte** (D9 del progetto della tappa), con la stessa versione di Febe **sullo stesso runtime di .NET**: JPEG (DCT in virgola mobile con `MathF.Round`, senza SIMD) è deterministico; in `Vp8LWriter` le stime dei costi non usano più `Math.Log2` ma un logaritmo in base 2 a virgola fissa (Q16, tabella per i valori piccoli e quadrati esatti oltre), così le scelte del codificatore WEBP non dipendono dalla libreria C (UCRT o glibc). **Limite noto:** PNG comprime con `ZLibStream` della BCL a `CompressionLevel.Optimal`, i cui byte possono cambiare con un aggiornamento di servizio di .NET; allora l'adozione per percorso di un PNG convertito prima non riconosce il file e scrive su un nome libero un secondo file uguale nei pixel. Nessun numero di versione delle conversioni è registrato: un codificatore che cambia uscita ha lo stesso effetto. Un deflate scritto in casa non è nella tappa E3; un PNG non compresso è stato scartato (file molte volte più grandi) | SPECIFICA §4.10, adozione: «i suoi codificatori sono fissi». Il danno del limite è al più un file in più, mai una sovrascrittura |
|
||||||
|
| 2026-11-28 | Tappa E3: **rimuxaggio** (`Mp4Remuxer`): ISO BMFF (`qt `, `M4V `, `3gp*`, ogni estensione non `.mp4`) e Matroska/WebM, con una traccia H.264 o HEVC (`avc1`/`avc3`/`hvc1`/`hev1` come nell'origine) e al più una AAC o MP3; un file ISO con un marchio diverso da `qt ` e l'estensione `.mp4` è già MP4 e si copia. L'elenco di modifiche dell'origine si riporta: il tratto vuoto iniziale (un inizio ritardato) e il tempo del primo tratto (il priming dell'AAC resta nascosto); più di un tratto non vuoto → rifiutato (`EditList`). MP3 nell'MP4 con l'OTI 0x6B (letto dall'`esds`, prima si scambiava per AAC), anche dentro `wave` di `mp4a`; per gli ID Matroska vecchi `A_AAC/MPEG4/…` la configurazione AAC si ricava da frequenza e canali; tracce Matroska con `ContentEncodings` rifiutate. Tracce in più tolte (`LostTracks:n`), `udta`/`meta`/tag non riportati (`LostVideoMetadata`); si tengono rotazione, lingua (`mdhd`, prima sempre «und») e date. Il lettore lavora con un «adesso» fisso (`ContainerReader.AnyDate`), così l'uscita non dipende dall'orologio; `Mp4Writer.Prepare` dà la lunghezza esatta prima di scrivere, e `Write` di prima dà gli stessi byte. In memoria solo le tabelle e il `moov`: i campioni si leggono e si scrivono uno per volta | SPECIFICA §4.10: «solo rimuxaggio, mai ricodifica»; un video non rimuxabile si copia com'è con il motivo |
|
||||||
|
| 2026-11-28 | Tappa E3: **fotogrammi** (`VideoFrameReader`). Gli istanti sono tempi di presentazione come li mostra il lettore: i PTS del lettore ISO comprendono già `ctts` e tolgono il primo tratto non vuoto, e vi si aggiunge il tratto vuoto iniziale. «Questo istante» = il campione con il tempo mostrato più grande che non supera l'istante (il primo prima dell'inizio, l'ultimo oltre la fine). La decodifica è esatta: parte da un IDR, da un CRA/BLA di HEVC o da un I di H.264 con un punto di ripresa (`recovery_frame_cnt` 0), altrimenti dal campione 0; i fotogrammi escono nell'ordine di decodifica e i nomi vengono da `Locate`. L'identità di un fotogramma copiato è l'istante del campione mostrato in millisecondi **arrotondato in su** (`frame_at_ms`): richiesto di nuovo a quell'istante trova lo stesso campione (sotto i 1.000 fotogrammi al secondo due campioni non distano meno di 1 ms); in un lavoro i doppioni si tolgono per campione, e il file del lavoro tiene l'istante chiesto. I pixel si ruotano come il video si vede (90 → EXIF 6, 180 → 3, 270 → 8) e **il fotogramma non ha metadati** (manca uno scrittore di EXIF; la data del file segue `libreria.data-file-pubblicazione`; proposta, §16 domanda 32). Oltre 8 bit si porta a 8 all'uscita. Suffissi `_t0m12s340` e `_f001` protetti dall'accorciamento a 240 caratteri (`FitPath(…, keepSuffix)`, il numero libero va dopo: `x_f001 (2).png`) | SPECIFICA §4.10, «Fotogrammi»; con l'arrotondamento in su basta una regola sola per ritrovare il fotogramma |
|
||||||
|
| 2026-11-28 | Tappa E3: **fotogrammi nelle destinazioni**: un lavoro di copia con file `Frame`, creati di seguito per video nell'ordine degli istanti; il copiatore li prende a gruppi per video e formato (anche fra due pagine di 500), apre il video una volta, scrive un fotogramma alla volta e fra l'uno e l'altro guarda sessione, interruzione e cartella: una pausa lascia in attesa il resto. Un video senza durata nota si misura quando si registra il lavoro; uno illeggibile dà un istante 0 e poi «Fotogramma non disponibile per questo video» senza riga di copia. Prima di registrare qualunque cosa il lavoro si rifiuta oltre 1.000 fotogrammi per un video o 20.000 in tutto. Nel piano un fotogramma conta 0 byte; il segno della tessera è `FrameOnly` quando l'elemento non ha copie intere o convertite e ha almeno un fotogramma copiato (proposta, §16 domande 32 e 38) | SPECIFICA §4.10: un fotogramma non fa «Copiato»; un video si legge una volta sola, non mille |
|
||||||
|
| 2026-11-28 | Tappa E3: **adozione e spazio con le conversioni**. Il file si converte **prima** dei controlli di dimensione (FAT32) e di spazio, che usano la lunghezza del convertito; il riepilogo dice «circa» con i byte degli originali. Adozione: la lunghezza, poi lo SHA-256 del file trovato contro quello della conversione; per un rimuxaggio lo SHA-256 si calcola scrivendo in un pozzo che conta e somma, solo se la lunghezza coincide. Una riga orfana di E2 si ricollega solo con lo stesso SHA-256 della copia, la stessa variante, lo stesso formato e lo stesso istante. Una foto si legge tutta in memoria e il suo SHA-256 si confronta prima di convertire; per video e fotogrammi l'origine si ricontrolla prima del cambio di nome (`SourceChanged`). Una foto oltre 512 MiB, copiata com'è, si copia in flusso | SPECIFICA §4.10, «Adozione per percorso», e lo spazio di §4.10 |
|
||||||
|
| 2026-11-28 | Tappa E3: **le note sono un elenco di codici** separati da spazi (`Codice` o `Codice:argomento`, argomento senza spazi) in `export_item.note` e in `media_conversion.last_error`; `ExportText.Note` li traduce uno per uno e li unisce con « · », e un codice sconosciuto si mostra com'è. In una riga di `media_conversion` **«Convertito»** `last_error` dice ciò che non si è tenuto (codici `Lost…`); in una «Non riuscito» il perché (`SourceMissing`, `SourceChanged`, `AccountFolderMissing`, `Error:<Tipo>`, oppure `AsIs…`, che non si converte). Il resoconto tiene al più 200 file con una nota e conta per account i «come sono» per etichetta | Nessuna colonna nuova: `note` e `last_error` sono `TEXT` senza vincoli. Una copia può perdere più cose insieme |
|
||||||
|
| 2026-11-28 | Tappa E3: **permesso di sottofondo** (`LongWorkGate.TryEnterBackground`, solo per `LongWorkKind.LibraryConversion`). Si prende solo se nessun lavoro lungo lo tiene; `Busy` non lo vede, così `EnsureIdle` delle copie e dell'importazione non rifiuta. `TryEnter` (sincrono, firma invariata) di un lavoro in primo piano lo toglie: sotto il lucchetto lo segna, fuori dal lucchetto annulla `Preempted` e, se il lavoro sta registrando un file (`TryBeginCommit`: un cambio di nome e una transazione, con `CancellationToken.None`), aspetta al più 10 secondi; oltre restituisce `false` con «La conversione della libreria sta salvando un file: riprova fra un attimo.». Fuori dalla registrazione il lavoro legge l'originale e scrive solo il suo `.part`, che la ricostruzione salta; quando vede la richiesta toglie il `.part` e lascia la riga «In coda». `FrameDownload` è un tipo nuovo con i suoi messaggi («scarica i fotogrammi») | SPECIFICA §4.10: la conversione cede il passo. Chi avvia copie e importazioni chiama `TryEnter` sotto i suoi lucchetti: una sospensione asincrona cambierebbe quei chiamanti, una registrazione dura millisecondi |
|
||||||
|
| 2026-11-28 | Tappa E3: **lavoro della conversione della libreria** (`LibraryConversionWorker`): un ciclo avviato con `InBackground` in `FebeApp` (non un `BackgroundService`, che con un'eccezione fermerebbe l'ospite), mai nella dimostrazione. Si sveglia con `LibraryConversionQueue.Signal()` o ogni 30 secondi, aspetta fuori dalle sessioni (ogni 5 secondi), prende 50 righe per volta; in pausa con `esportazione.libreria-sospesa` = `1`. Per ogni riga: elemento sparito → riga tolta; cartella dell'account assente → «Non riuscito» (`AccountFolderMissing`), mai creata (`RequireExistingRoot`); originale mancante → `SourceMissing`; SHA-256 cambiato → la riga prende quello nuovo; un video si somma prima del rimuxaggio; stesso formato riconosciuto dai byte → riga tolta (il vincolo `sha256 <> source_sha256` non lascia registrarla); copiato com'è → «Non riuscito» con il codice `AsIs…`, definitivo («Riprova i non riusciti» lo salta); spazio sotto `DiskThresholds.Default` con il file da scrivere → pausa con il motivo. Scrittura con `SafeFileWriter` nella cartella dell'originale, stesso nome, estensione del formato, nome libero, rilettura dal disco; adozione di un file con lo stesso SHA-256 solo se nessun file presente e nessuna conversione viva dell'account registrano quel percorso. Se alla registrazione l'elemento non c'è più (o il posto è preso), Febe toglie il file **appena scritto da lei**, dopo averne riletto lo SHA-256, mai un file adottato. Ogni errore di un file finisce in `last_error` come `Error:<Tipo>`; il registro ha solo il nome del tipo | Regola 11: la conversione aggiunge e non toglie; un disco staccato non deve diventare una cartella locale; nel registro mai percorsi |
|
||||||
|
| 2026-11-28 | Tappa E3: **righe della conversione sempre vere**. Un file nuovo entra in coda in `LibraryIngest.AppendJournalAsync`, dopo la sua riga di `_febe.jsonl` (scaricamento e importazione; nessun costruttore cambia). Spegnere o cambiare un formato toglie le righe «In coda» di quello di prima; i convertiti e le loro righe restano. Un originale cambiato (`ExportSupersession.FileChangedAsync`): le righe «Convertito» diventano «Superato» (il file resta), quelle «In coda» o «Non riuscito», **anche le `AsIs…`** (il verdetto era sui byte di prima), tornano «In coda» con lo SHA-256 nuovo. «Elimina dalla libreria» che ricorda la scelta segna «Tolto» i convertiti e toglie le righe senza file; «Eliminalo e lascia che torni» toglie le righe (`RemoveWithConversionsAsync`); poi il file convertito si cancella solo se il suo SHA-256 è ancora quello registrato e nessuna riga viva tiene quel percorso, altrimenti resta ed è detto. `EntryStore.RemoveAsync` resta severo: una riga «Convertito» o «Superato» lo fa fallire (`ON DELETE RESTRICT`) con un errore in italiano. Il file scartato da «Tieni il più grande» porta via i suoi convertiti in una transazione (`ForgetDeletedMediaAsync`). La ricostruzione non converte: salta i percorsi registrati, conta i convertiti accanto agli originali (`RebuildReport.ConversionsFound`) e, con la conversione accesa per quel formato, ne rimette la riga «In coda» (il lavoro poi la adotta per SHA-256); per gli elementi eliminati passa solo le conversioni il cui file manca e conta le altre (`ConversionsOfDeletedEntries`) | SPECIFICA §4.10: il convertito è legato al suo originale; regola 11 |
|
||||||
|
| 2026-11-28 | Tappa E3: **l'importazione riconosce i convertiti** (proposta, §16 domanda 37): uno SHA-256 di una conversione della libreria o di una copia convertita o di un fotogramma (`export_copy.copy_sha256` delle righe `Converted`/`Frame`) è «già in libreria», con la nota «È una copia convertita (o un fotogramma) di un file già in libreria.», mai una coppia di doppioni. Le copie si leggono una volta per importazione in un insieme in memoria (`LoadConvertedCopyShasAsync`), perché `copy_sha256` non ha un indice e la tappa non aggiunge migrazioni | Una copia convertita somiglia all'originale per impronta: senza la regola l'importazione di una destinazione proporrebbe centinaia di doppioni |
|
||||||
|
| 2026-11-28 | Tappa E3: **risorse delle conversioni**. Ogni conversione di una foto (copiatore, lavoro della libreria e fotogrammi delle destinazioni) passa da un solo `ConversionThrottle` del processo (`SemaphoreSlim(1)`) e gira con `Task.Run`; un video si legge a pezzi; un fotogramma è un'immagine RGBA alla volta. I file della libreria si aprono anche con `FileShare.Delete`, così una lettura lunga non blocca «Elimina dalla libreria» su Windows | Un server di casa con poca memoria; due conversioni di foto grandi insieme raddoppierebbero il picco |
|
||||||
|
| 2026-11-28 | Tappa E3: **fotogrammi dall'interfaccia** (`FrameService`). Anteprime e fotogrammi singoli uno alla volta, entro 30 secondi (oltre, 503 «Il fotogramma richiede troppo tempo: scegli la cartella delle copie»), con le informazioni dei video in memoria per SHA-256 (le ultime 64); anteprima JPG di al più 480 pixel, scaricamento in PNG di serie con il nome del fotogramma. «Scarica» passa da un gettone in memoria (5 minuti, un uso solo): 1 fotogramma → l'immagine, da 2 a 500 → uno zip `febe-fotogrammi-AAAA-MM-GG.zip`, non compresso, con voci `<account>/<nome>` rese uniche come i nomi liberi e la data delle voci secondo `libreria.data-file-pubblicazione` tenuta fra il 1980 e il 2107 (i limiti dello zip). Oltre 20 fotogrammi lo zip vuole il permesso `FrameDownload` (409 altrimenti) e niente sessione del motore, lascia il permesso anche se il browser chiude, e si interrompe dopo 60 secondi senza che una scrittura vada avanti. Oltre 500 → «Per più di 500 fotogrammi scegli la cartella delle copie» (proposta, §16 domanda 34). Gli errori con un codice (409, 503) passano da `ApiStatusException` | Un browser lento non deve tenere il permesso dei lavori lunghi per sempre; uno zip grande non deve fermare il motore |
|
||||||
|
| 2026-11-28 | Tappa E3, interfaccia: un dialogo aperto dal visualizzatore resta sopra di lui (velo dei dialoghi da `z-index` 40 a 55, il visualizzatore è a 50, i menu a 60); il segno «Solo fotogrammi» è disegnato in CSS, senza un file d'icona; «Fotogrammi…» dalla selezione ha solo il campo dell'istante, senza anteprime (non c'è un video solo); il riquadro «Conversione della libreria» della Dashboard compare solo quando la conversione è accesa o ha righe; la domanda «Convertire anche i N file già in libreria?» si fa a ogni cambio verso un formato che non è «Originale», se l'anteprima trova file da convertire. La dimostrazione non avvia mai la conversione: semina una copia PNG fatta dal motore vero, un fotogramma a 1,234 s (il campione mostrato è a 1,125 s) e due righe `media_conversion` («Convertito» in PNG con il suo file e «Non riuscito» `AsIsAnimated`) | Un dialogo sotto il visualizzatore non si vedeva; un riquadro sempre presente per una funzione spenta sarebbe rumore |
|
||||||
|
| 2026-11-28 | Revisione della tappa E3, immagini: il controllo prima della conversione stima anche la memoria di lavoro del decodificatore JPEG (`ImageInfo.DecodeWorkingBytes`: un progressivo tiene i coefficienti), così un JPEG che il decodificatore rifiuterebbe esce «troppo grande» (`AsIsTooLarge`) e non «illeggibile»; un'eccezione di limite durante la conversione della libreria fa lo stesso. Un EXIF che non si tiene (illeggibile o troppo grande per il JPG) lascia comunque un EXIF minimo con il solo orientamento (`ExifOrientation.Minimal`, nell'ordine dei byte della fonte) | Il verdetto deve dire il vero motivo; senza orientamento la foto uscirebbe girata |
|
||||||
|
| 2026-11-28 | Revisione della tappa E3, fotogrammi: gli istanti di «Uno ogni k secondi» e «N in tutto» sono in millisecondi interi (`ExportFrames.WholeMs`) prima di contare i doppioni; la copia ricalcola gli istanti dalla durata (misurata se il database non la sa) e trova l'indice del nome per istante (`ExportFrames.IndexOf`), con il conteggio delle righe solo come riserva. I video di durata sconosciuta si misurano nel pianificatore (`lengthOf`, una volta per video e per richiesta) prima che si registri qualcosa, così contano nei limiti di 500 per richiesta e 5000 per video; un video che non si misura dà il solo fotogramma a 0 | Nomi e conteggi non devono dipendere dall'ordine delle righe né scoprire il troppo dopo averlo scritto |
|
||||||
|
| 2026-11-28 | Revisione della tappa E3, video: il rimuxaggio porta in MP4 la durata del segmento di `elst` (`MediaTrack.EditSegmentDuration`) e la scrive quando taglia la fine; i fotogrammi non cadono oltre la fine mostrata. Il punto di recupero H.264 vale come IDR solo con `exact_match_flag` = 1. MP3 in MP4: `objectTypeIndication` 0x69 (MPEG-2, fino a 24 kHz) o 0x6B (MPEG-1) secondo la frequenza | Un AAC con la fine tagliata è comune; un recovery point inesatto dà fotogrammi sporchi; 0x6B con 22,05 kHz è un'etichetta falsa (ISO/IEC 14496-1, tabella 5) |
|
||||||
|
| 2026-11-28 | Revisione della tappa E3, conversione della libreria: il lavoro ricontrolla il formato della riga con le impostazioni di adesso e toglie quella di un formato spento o cambiato; spegnere o cambiare un formato toglie anche i suoi «Non riuscito» (non `AsIs…`, `DeleteQueueAsync`); «Riprova» rimette solo i formati di adesso. Prima di rileggere l'originale il lavoro guarda lo spazio libero e si mette in pausa se è già sotto la soglia. «Anche i N» conta e mette in coda solo il tipo che si sta cambiando (`?photo=`/`?video=`, e nel PUT i tipi il cui formato cambia), mai l'altro che aveva già avuto «Solo i nuovi». Il PUT delle impostazioni dell'esportazione passa da un cancello (uno per volta): due clic veloci non partono dallo stesso «prima» | Una riga di un formato spento non deve scrivere file; rileggere un originale grande con il disco pieno è lavoro buttato; due cambi insieme perdevano l'uno o l'altro |
|
||||||
|
| 2026-11-28 | Revisione della tappa E3: «file nuovo» per «Solo i nuovi» vuol dire salvato in libreria (`media.downloaded_at`) da quando il formato di quel tipo è quello di adesso (`esportazione.libreria-formato-foto-dal` / `-video-dal`, in millisecondi, scritti da `OnSettingsChangedAsync`; senza la chiave ogni file è nuovo). Un file arrivato tardi in un elemento vecchio mette in coda sé, non i fratelli | Come per «Automatica» (`automatic_since` contro `media.downloaded_at`); passare gli id dai chiamanti non reggeva alle righe del giornale rimandate |
|
||||||
|
| 2026-11-28 | Revisione della tappa E3: «Elimina dalla libreria» (con memoria) e «Tieni il più grande» scelgono le righe dei convertiti nella stessa transazione che elimina (`MarkDeletedWithConversionsAsync`, `ForgetDeletedMediaAsync` che segna anche il file «Eliminato»), così un convertito registrato dal lavoro un attimo prima se ne va con il suo originale. Lo zip dei fotogrammi si scrive a pezzi di 64 KB, ognuno con i suoi 60 secondi: un browser lento che legge non si interrompe, uno fermo sì | Un convertito orfano resterebbe sul disco con la riga «Convertito»; un fotogramma grande su una linea lenta superava i 60 secondi in una scrittura sola |
|
||||||
|
| 2026-11-28 | Seconda revisione della tappa E3, video: `Mp4Writer` misura la fine della presentazione in tempo di composizione (il massimo di decodifica + scarto di composizione + durata di ogni campione), non la somma delle durate di decodifica. Con i fotogrammi B l'edit comincia al primo scarto di composizione e con la somma l'MP4 nascondeva gli ultimi fotogrammi mostrati (2 in un iPhone), e durava altrettanto meno in `mvhd`, `tkhd` ed `elst`; il segmento della sorgente resta il limite. Vale per ogni scrittura, non solo per le sorgenti con un segmento: per una traccia senza scarti la fine è la stessa di prima e i byte non cambiano, con gli scarti il risultato di prima era sbagliato anche senza segmento (Matroska, ISO senza `elst`). | Una MOV con fotogrammi B rimuxata in MP4 (conversione della libreria o copia) deve mostrare quello che mostrava la sorgente; i fotogrammi presi dal convertito ora leggono il segmento giusto. |
|
||||||
|
| 2026-11-28 | Seconda revisione della tappa E3, conversione della libreria: il lavoro ricorda il file che l'ha messo in pausa per spazio e quanto serve al suo convertito (riga, SHA-256 dell'originale, byte), e finché il disco non ha posto anche per quello la pausa vale prima di rileggere l'originale (hash, decodifica, rimuxaggio). Non si sottraggono i byte dell'originale in anticipo: un PNG grande che diventa un JPG piccolo resterebbe fermo senza motivo. Il ricordo è del processo: dopo un riavvio l'originale si rilegge una volta. | La pausa per spazio (D17) non deve rileggere lo stesso video di 2 GB a ogni risveglio quando lo spazio libero sta fra la soglia e la soglia più il file. |
|
||||||
|
| 2026-11-28 | Seconda revisione della tappa E3: un cambio dei formati della libreria si salva in una transazione sola con le chiavi «dal» e la coda svuotata del formato sostituito (`LibraryConversionQueue.SaveSettingsAsync`, `IMediaConversionStore.SaveSettingsAndDeleteQueuesAsync`); «Anche i N» dopo il salvataggio non dipende più dalla richiesta (`CancellationToken.None`). Il gancio della libreria legge formati e chiavi «dal» con una lettura sola. | Una scheda chiusa, un arresto o un file salvato in quel momento non devono vedere il formato nuovo senza la sua chiave «dal» (che metterebbe in coda tutto l'elemento) né lasciare «Non riuscito» del formato vecchio che «Riprova» non tocca più. |
|
||||||
|
| 2026-11-28 | Seconda revisione della tappa E3, fotogrammi: i tempi di `WriteStall` dello zip passano da un `TimeProvider` della BCL (`FrameService.StallTime`, di serie quello di sistema); la prova del lettore lento usa un `TimeProvider` scritto nella prova che avanza solo quando il collegamento finto manda un pezzo. | La prova dipendeva da orologi veri con 250 ms di margine e poteva cadere su un esecutore carico della CI; ora non dipende dal carico. Nessun pacchetto esterno. |
|
||||||
@@ -54,6 +54,9 @@ Che cosa fa:
|
|||||||
disco, e rispetta le eliminazioni (un elemento eliminato «ricordando la scelta» resta eliminato);
|
disco, e rispetta le eliminazioni (un elemento eliminato «ricordando la scelta» resta eliminato);
|
||||||
- **non riscarica nulla** e **non sposta, non rinomina e non cancella nessun file**;
|
- **non riscarica nulla** e **non sposta, non rinomina e non cancella nessun file**;
|
||||||
- gli elementi già presenti nel database restano come sono: si può lanciare anche su un database esistente;
|
- gli elementi già presenti nel database restano come sono: si può lanciare anche su un database esistente;
|
||||||
|
- non converte nulla: i file della conversione della libreria accanto ai loro originali (`foto.png` accanto a
|
||||||
|
`foto.jpg`) si riconoscono e non contano fra i file sconosciuti; se la conversione è accesa per quel formato, il file
|
||||||
|
torna nell'elenco dei convertiti dopo la ricostruzione;
|
||||||
- mostra l'avanzamento (cartelle e file controllati) e alla fine un resoconto.
|
- mostra l'avanzamento (cartelle e file controllati) e alla fine un resoconto.
|
||||||
|
|
||||||
Che cosa non torna:
|
Che cosa non torna:
|
||||||
|
|||||||
@@ -2,11 +2,12 @@
|
|||||||
|
|
||||||
Le **copie esterne** sono copie dei file della libreria in cartelle fuori da Febe: un disco USB, una chiavetta, una
|
Le **copie esterne** sono copie dei file della libreria in cartelle fuori da Febe: un disco USB, una chiavetta, una
|
||||||
cartella di rete, un'altra cartella del server. La libreria non cambia: Febe legge i suoi file e li copia così come
|
cartella di rete, un'altra cartella del server. La libreria non cambia: Febe legge i suoi file e li copia così come
|
||||||
sono, byte per byte. Non riscarica nulla e non apre Instagram: è solo lavoro sul disco.
|
sono, byte per byte, oppure convertiti in un altro formato (vedi «Formati»), oppure ne prende dei fotogrammi (vedi
|
||||||
|
«Fotogrammi»). Non riscarica nulla e non apre Instagram: è solo lavoro sul disco.
|
||||||
|
|
||||||
In questa versione (tappa E2) si copiano gli **originali**. Le copie in un altro formato e i fotogrammi dei video
|
In questa versione (tappa E3) ci sono le copie degli originali, i formati delle copie, la conversione della libreria e
|
||||||
arrivano con la tappa E3, l'analisi dei video fermi con la E4, le copie automatiche con la E5: fino ad allora quei
|
i fotogrammi dei video. L'analisi dei video fermi arriva con la tappa E4 e le copie automatiche con la E5: fino ad
|
||||||
comandi non ci sono.
|
allora quei comandi («È un video fermo?», «Automatica») non ci sono.
|
||||||
|
|
||||||
> **Le copie esterne escono dal controllo di Febe.** Chi ha la cartella di una copia, o il disco su cui sta, ha quei
|
> **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
|
> file, comprese le foto e i video di altre persone. Febe non le cifra, non le cancella e, dopo averle scritte, ne sa
|
||||||
@@ -78,13 +79,54 @@ quando quell'account ne ha una).
|
|||||||
La finestra conta prima di copiare: quanti file, quanti già copiati (saltati), quanti tolti o superati (saltati), quanti
|
La finestra conta prima di copiare: quanti file, quanti già copiati (saltati), quanti tolti o superati (saltati), quanti
|
||||||
di account che non si esportano, quanti non presenti in libreria, circa quanto spazio, e lo spazio libero di ogni
|
di account che non si esportano, quanti non presenti in libreria, circa quanto spazio, e lo spazio libero di ogni
|
||||||
cartella. **«Copia di nuovo anche i N tolti o superati»** è spenta: accendila se vuoi riscriverli (vedi «Stati»).
|
cartella. **«Copia di nuovo anche i N tolti o superati»** è spenta: accendila se vuoi riscriverli (vedi «Stati»).
|
||||||
«Copia N file» fa partire il lavoro e la finestra si chiude: le copie vanno avanti da sole e si seguono nella Dashboard.
|
La riga **«Formato: come la destinazione · Cambia»** dice in che formato arrivano i file; «Cambia» lo sceglie solo per
|
||||||
|
questa copia (vedi «Formati»), e il riepilogo dice allora anche quanti file si copiano come sono («circa 3 HEIC copiati
|
||||||
|
come sono») e «con perdita» se qualche file diventa JPG. «Copia N file» fa partire il lavoro e la finestra si chiude:
|
||||||
|
le copie vanno avanti da sole e si seguono nella Dashboard.
|
||||||
|
|
||||||
Si copiano solo i **file dovuti**: i file presenti in libreria di un account che si esporta e ha una cartella delle
|
Si copiano solo i **file dovuti**: i file presenti in libreria di un account che si esporta e ha una cartella delle
|
||||||
copie, del tipo che quella cartella copia. Il segno sulle tessere, il filtro «Copie», il conteggio della scheda
|
copie, del tipo che quella cartella copia. Il segno sulle tessere, il filtro «Copie», il conteggio della scheda
|
||||||
dell'account e «Copia in…» contano tutti e soli questi file, così «312 su 1.204 non ancora copiati» è proprio ciò che
|
dell'account e «Copia in…» contano tutti e soli questi file, così «312 su 1.204 non ancora copiati» è proprio ciò che
|
||||||
«Copia in…» copierebbe.
|
«Copia in…» copierebbe.
|
||||||
|
|
||||||
|
## Formati
|
||||||
|
|
||||||
|
Di solito le copie sono gli **originali**, byte per byte. Puoi chiedere invece che arrivino in un altro formato:
|
||||||
|
|
||||||
|
| | Scelte |
|
||||||
|
|---|---|
|
||||||
|
| Foto | **Originale** (di solito), JPG, PNG, WEBP senza perdita |
|
||||||
|
| Video | **Originale** (di solito), MP4 |
|
||||||
|
|
||||||
|
Il formato si sceglie in tre posti, e vale il più vicino alla copia: **«Cambia»** nella finestra «Copia in…» (solo per
|
||||||
|
quella copia), la parte **«Formati»** della finestra di una cartella («Come le impostazioni generali», di solito),
|
||||||
|
**Impostazioni ▸ Esportazione ▸ «Formati delle copie»**.
|
||||||
|
|
||||||
|
- **Con perdita solo se lo scegli.** JPG è l'unico formato con perdita: Febe lo scrive a **qualità 92**, e la finestra lo
|
||||||
|
dice («con perdita: qualità 92», «con perdita» nel riepilogo). La trasparenza in JPG diventa bianco. PNG e WEBP senza
|
||||||
|
perdita tengono tutti i pixel.
|
||||||
|
- **Video in MP4: solo rimuxaggio, mai ricodifica.** Febe porta in MP4 un MOV, un M4V, un 3GP o un MKV/WebM con video
|
||||||
|
H.264 o HEVC e audio AAC o MP3, copiando i fotogrammi così come sono: tengono qualità, rotazione, lingua delle tracce
|
||||||
|
e date. Tracce in più (codice di tempo, sottotitoli, una seconda traccia audio) si tolgono, e la nota lo dice. Un
|
||||||
|
video con un altro codec (VP9, AV1, Opus…) si copia com'è.
|
||||||
|
- **Un file già in quel formato si copia byte per byte**, mai ricodificato. Febe lo riconosce dal contenuto, non dal
|
||||||
|
nome: un `.jpg` che in realtà è un PNG si converte. Un WEBP con perdita resta com'è anche con «WEBP senza perdita».
|
||||||
|
- **Si copiano come sono, con una nota:** HEIC, AVIF, raw (`.dng`, `.cr2`, `.nef`…), le immagini animate (GIF, WEBP e
|
||||||
|
PNG animati: convertite perderebbero i fotogrammi dopo il primo), ciò che Febe non riesce a leggere, le immagini CMYK
|
||||||
|
o con più di 8 bit per colore verso PNG e WEBP, le immagini troppo grandi per il formato (oltre 40 megapixel per WEBP,
|
||||||
|
oltre 100 per JPG e PNG, oltre 512 MB), i video che non si portano in MP4 senza ricodificarli.
|
||||||
|
- **I metadati vengono con il file:** EXIF (l'orientamento resta un dato, i pixel non si ruotano), profilo ICC, XMP; per
|
||||||
|
i video date, rotazione e lingua. Ciò che il formato non può tenere (un EXIF troppo grande per JPG, un profilo ICC non
|
||||||
|
RGB…) lo dicono le note («Non tenuto: profilo ICC»).
|
||||||
|
- **Un formato nuovo vale per i file non ancora copiati.** Un file già copiato in un'altra forma resta «Copiato» e si
|
||||||
|
salta («Già copiato in un altro formato»). Se lo vuoi anche nel formato nuovo: togli il file vecchio dalla cartella,
|
||||||
|
«Controlla le copie» lo segna «Tolto», poi «Copia di nuovo».
|
||||||
|
- Il riepilogo prevede le note dal nome dei file e dice lo spazio degli originali, «circa»: un convertito può occupare
|
||||||
|
di più. Lo spazio della cartella Febe lo controlla sul file convertito, prima di scriverlo.
|
||||||
|
|
||||||
|
Le note di ogni file stanno nel **resoconto** del lavoro (Dashboard ▸ Esportazione ▸ «Resoconto», colonne «Come sono» e
|
||||||
|
«Note») e nelle righe del visualizzatore.
|
||||||
|
|
||||||
## Come Febe scrive una copia
|
## Come Febe scrive una copia
|
||||||
|
|
||||||
- Prima di ogni gruppo di copie (al più 100 file o 1 GB) Febe scrive e toglie un file di prova nella cartella. Se non
|
- Prima di ogni gruppo di copie (al più 100 file o 1 GB) Febe scrive e toglie un file di prova nella cartella. Se non
|
||||||
@@ -97,7 +139,8 @@ dell'account e «Copia in…» contano tutti e soli questi file, così «312 su
|
|||||||
della libreria, poi prende il nome definitivo. **Febe non sovrascrive mai un file**: se il nome è occupato da un altro
|
della libreria, poi prende il nome definitivo. **Febe non sovrascrive mai un file**: se il nome è occupato da un altro
|
||||||
file, scrive `nome (2).jpg` e lascia l'altro com'è. Non cancella e non sposta nulla nelle cartelle delle copie; i
|
file, scrive `nome (2).jpg` e lascia l'altro com'è. Non cancella e non sposta nulla nelle cartelle delle copie; i
|
||||||
`.part` rimasti da una copia interrotta li toglie solo nelle cartelle di quel lavoro, mai frugando nel resto.
|
`.part` rimasti da una copia interrotta li toglie solo nelle cartelle di quel lavoro, mai frugando nel resto.
|
||||||
- La data del file segue l'impostazione della libreria «Imposta la data del file a quella di pubblicazione».
|
- La data del file segue l'impostazione della libreria «Imposta la data del file a quella di pubblicazione», anche
|
||||||
|
per i file convertiti e i fotogrammi.
|
||||||
- Non si copia durante una sessione del motore: la copia aspetta che la sessione finisca («Aspetto la fine della
|
- Non si copia durante una sessione del motore: la copia aspetta che la sessione finisca («Aspetto la fine della
|
||||||
sessione del motore»). Copie, importazione e ricostruzione del database non girano insieme: mentre una lavora, le
|
sessione del motore»). Copie, importazione e ricostruzione del database non girano insieme: mentre una lavora, le
|
||||||
altre due aspettano che finisca o che la interrompi.
|
altre due aspettano che finisca o che la interrompi.
|
||||||
@@ -106,28 +149,31 @@ dell'account e «Copia in…» contano tutti e soli questi file, così «312 su
|
|||||||
|
|
||||||
Se nel posto dove andrebbe la copia c'è già un file **identico** (stesso SHA-256 dell'originale), Febe lo adotta come
|
Se nel posto dove andrebbe la copia c'è già un file **identico** (stesso SHA-256 dell'originale), Febe lo adotta come
|
||||||
copia invece di scriverne un secondo: succede dopo un database perso o ricostruito, con un backup vecchio della
|
copia invece di scriverne un secondo: succede dopo un database perso o ricostruito, con un backup vecchio della
|
||||||
cartella, con due Febe sulla stessa cartella. La sola dimensione non basta mai: un file diverso con la stessa
|
cartella, con due Febe sulla stessa cartella. Per un file convertito o un fotogramma Febe rifà la conversione e vuole
|
||||||
dimensione resta com'è, e la copia va su un nome libero.
|
lo stesso SHA-256 del file che trova. La sola dimensione non basta mai: un file diverso con la stessa dimensione resta
|
||||||
|
com'è, e la copia va su un nome libero.
|
||||||
|
|
||||||
## Stati di una copia
|
## Stati di una copia
|
||||||
|
|
||||||
| Stato | Che cosa vuol dire |
|
| Stato | Che cosa vuol dire |
|
||||||
|---|---|
|
|---|---|
|
||||||
| **Copiato** | Il file è nella cartella, uguale all'originale |
|
| **Copiato** | Il file è nella cartella, uguale all'originale o convertito nel formato chiesto |
|
||||||
| **Tolto** | Il file non c'è più nella cartella (l'hai spostato o cancellato tu, o il disco è un altro). Lo trova «Controlla le copie» in Impostazioni ▸ Esportazione, che guarda soltanto e non tocca nessun file. Con il disco staccato non segna nulla come tolto: mette la cartella in pausa |
|
| **Tolto** | Il file non c'è più nella cartella (l'hai spostato o cancellato tu, o il disco è un altro). Lo trova «Controlla le copie» in Impostazioni ▸ Esportazione, che guarda soltanto e non tocca nessun file. Con il disco staccato non segna nulla come tolto: mette la cartella in pausa |
|
||||||
| **Superato** | Il file della libreria è cambiato dopo la copia: «Tieni il più grande» fra due doppioni, un'importazione che sostituisce, una ricostruzione che trova un altro file. La copia vecchia resta |
|
| **Superato** | Il file della libreria è cambiato dopo la copia: «Tieni il più grande» fra due doppioni, un'importazione che sostituisce, una ricostruzione che trova un altro file. La copia vecchia resta |
|
||||||
| **Non riuscito** | La copia non si è potuta fare (per esempio il limite di FAT32): la prossima «Copia in…» ci riprova |
|
| **Non riuscito** | La copia non si è potuta fare (per esempio il limite di FAT32): la prossima «Copia in…» ci riprova |
|
||||||
|
|
||||||
**Tolto e Superato non si ricopiano mai da soli.** «Copia di nuovo», nel pannello File del visualizzatore accanto alla
|
**Tolto e Superato non si ricopiano mai da soli.** «Copia di nuovo», nel pannello File del visualizzatore accanto alla
|
||||||
riga della copia, oppure la casella «Copia di nuovo anche i N tolti o superati» di «Copia in…», scrive un file nuovo, e
|
riga della copia, oppure la casella «Copia di nuovo anche i N tolti o superati» di «Copia in…», scrive un file nuovo, e
|
||||||
la copia vecchia resta dov'è. Eliminare un elemento dalla libreria non tocca le sue copie.
|
la copia vecchia resta dov'è. Dal visualizzatore rifà proprio quella copia, nella sua forma (intero, PNG, il fotogramma
|
||||||
|
a quell'istante…); la casella di «Copia in…» usa i formati di adesso. Eliminare un elemento dalla libreria non tocca le
|
||||||
|
sue copie.
|
||||||
|
|
||||||
Dove si vede:
|
Dove si vede:
|
||||||
|
|
||||||
- un piccolo **segno sulla tessera** (solo se c'è almeno una cartella delle copie), con «2/3» per un post copiato in
|
- un piccolo **segno sulla tessera** (solo se c'è almeno una cartella delle copie), con «2/3» per un post copiato in
|
||||||
parte;
|
parte e un piccolo riquadro, **«Solo fotogrammi»**, per un elemento di cui sono stati copiati solo dei fotogrammi;
|
||||||
- le righe del **pannello File** del visualizzatore: «Copiato in Disco USB il 3 novembre · intero», «Tolto da…»,
|
- le righe del **pannello File** del visualizzatore: «Copiato in Disco USB il 3 novembre · intero», «… · PNG»,
|
||||||
«Superato in…», con «Copia di nuovo»;
|
«… · fotogramma a 0:01,125 · PNG», «Tolto da…», «Superato in…», con «Copia di nuovo» e, sotto, le note;
|
||||||
- il conteggio nella **scheda dell'account** («312 su 1.204 non ancora copiati», i tolti o superati, i non riusciti);
|
- il conteggio nella **scheda dell'account** («312 su 1.204 non ancora copiati», i tolti o superati, i non riusciti);
|
||||||
- il filtro **«Copie»** in Libreria e nella scheda dell'account: Tutti, Non ancora copiati, Copiati, Tolti o superati.
|
- il filtro **«Copie»** in Libreria e nella scheda dell'account: Tutti, Non ancora copiati, Copiati, Tolti o superati.
|
||||||
Resta nell'indirizzo della pagina (`?copie=non-copiati`).
|
Resta nell'indirizzo della pagina (`?copie=non-copiati`).
|
||||||
@@ -141,6 +187,79 @@ Quando lo stesso file è il post di un account e il taggato di un altro, Imposta
|
|||||||
- **«Una copia sola»**: si copia una volta, nel primo account che lo copia; l'altro lo mostra «Copiato» con la cartella
|
- **«Una copia sola»**: si copia una volta, nel primo account che lo copia; l'altro lo mostra «Copiato» con la cartella
|
||||||
dove sta.
|
dove sta.
|
||||||
|
|
||||||
|
## Fotogrammi
|
||||||
|
|
||||||
|
Un **fotogramma** è un'immagine presa da un video, a piena risoluzione e girata come il video si vede. Si chiede:
|
||||||
|
|
||||||
|
- dal **visualizzatore**, con **«Fotogramma»** sotto un video: il video si ferma e la finestra si apre all'istante in
|
||||||
|
cui era, con l'anteprima e il cursore per spostarsi;
|
||||||
|
- dalla **selezione**, in Libreria e nella scheda di un account: «Seleziona», scegli le tessere, **«Fotogrammi…»** nella
|
||||||
|
barra in basso. Lo stesso istante (o la stessa regola) vale per ogni video scelto; **le foto si saltano**, e la
|
||||||
|
finestra lo dice.
|
||||||
|
|
||||||
|
Quali fotogrammi:
|
||||||
|
|
||||||
|
- **Questo istante**: il fotogramma che il video mostra in quel momento (scrivi l'istante come `0:12` o `0:12,5`); oltre
|
||||||
|
la fine, l'ultimo;
|
||||||
|
- **Uno ogni k secondi**: da 0:00, poi ogni k secondi fino alla fine (k almeno 0,1 secondi);
|
||||||
|
- **N in tutto**: il video diviso in N parti uguali, un fotogramma al centro di ognuna (da 1 a 1.000).
|
||||||
|
|
||||||
|
Dal visualizzatore la finestra mostra le anteprime dei primi sei («e altri N»). Formato: **PNG** (di solito, nessuna
|
||||||
|
perdita), JPG (con perdita) o WEBP senza perdita. **Il fotogramma non ha l'audio**, e la finestra lo ricorda; non ha
|
||||||
|
nemmeno i metadati del video. Un video in un codec che Febe non decodifica (VP9, AV1…) o rovinato dice **«Fotogramma
|
||||||
|
non disponibile per questo video»**.
|
||||||
|
|
||||||
|
Dove vanno:
|
||||||
|
|
||||||
|
- **«Scarica»**: un fotogramma si scarica com'è; più fotogrammi in uno **zip** (`febe-fotogrammi-AAAA-MM-GG.zip`, una
|
||||||
|
cartella per account). Fino a 20 fotogrammi lo zip si fa in qualunque momento; da 21 a 500 solo fuori dalle sessioni
|
||||||
|
del motore e quando non lavorano importazione, copie o ricostruzione; per più di 500 scegli la cartella delle copie.
|
||||||
|
«Scarica» non guarda le cartelle delle copie né «Esporta questo account».
|
||||||
|
- **«Nella cartella delle copie»**: un lavoro di copia, come «Copia in…», nella cartella di ogni account, accanto alle
|
||||||
|
copie, con gli stessi file dovuti (gli account che non si esportano si saltano e si contano). Si segue nella
|
||||||
|
Dashboard.
|
||||||
|
|
||||||
|
I nomi sono quelli del video con l'istante: `video_t0m12s340.png` (0 minuti, 12 secondi e 340 millesimi: l'istante del
|
||||||
|
fotogramma davvero mostrato) per «Questo istante» e «Uno ogni k secondi», `video_f001.png`, `video_f002.png`… per «N in
|
||||||
|
tutto». Al più 1.000 fotogrammi per video («Più di 1.000 fotogrammi per un video: scegli un intervallo più lungo») e
|
||||||
|
20.000 per volta.
|
||||||
|
|
||||||
|
**Un fotogramma non fa «copiato» il video:** il video resta «Non ancora copiato» finché non ne copi il file intero, e
|
||||||
|
un elemento con soli fotogrammi ha il segno «Solo fotogrammi». Lo stesso fotogramma chiesto di nuovo nella stessa
|
||||||
|
cartella è «già copiato»; un fotogramma «Tolto» si riscrive quando lo chiedi di nuovo.
|
||||||
|
|
||||||
|
## Conversione della libreria
|
||||||
|
|
||||||
|
Oltre alle copie, Febe può tenere **nella libreria** un file convertito accanto a ogni foto o video: Impostazioni ▸
|
||||||
|
Esportazione ▸ **«Conversione della libreria»**, Foto (JPG, PNG, WEBP senza perdita) e Video (MP4). Di solito è spenta
|
||||||
|
(«Originale»).
|
||||||
|
|
||||||
|
- **Il file convertito si aggiunge: l'originale resta**, con il suo nome. Il convertito va nella stessa cartella, con lo
|
||||||
|
stesso nome e l'estensione nuova (`foto.png` accanto a `foto.jpg`; `foto (2).png` se il nome è già preso: mai una
|
||||||
|
sovrascrittura), con le stesse regole e le stesse note delle copie.
|
||||||
|
- Resta l'originale il file della libreria: SHA-256, miniatura, doppioni, `_febe.jsonl`, «Copia in…», «Fotogrammi…» e
|
||||||
|
l'elenco CSV usano sempre l'originale. Il convertito non si riscarica e non è un doppione.
|
||||||
|
- Quando la accendi Febe chiede **«Convertire anche i N file già in libreria?»**, con lo spazio che occupano gli
|
||||||
|
originali (i convertiti possono occupare di più): **«Solo i nuovi»** converte da adesso in poi, ogni file dopo il
|
||||||
|
suo scaricamento o la sua importazione; «Anche i N già in libreria» li mette tutti in coda. Spegnerla svuota la coda;
|
||||||
|
i file già convertiti restano dove sono.
|
||||||
|
- Lavora **in sottofondo**, un file alla volta, mai durante una sessione del motore; quando parte un'importazione, una
|
||||||
|
copia o una ricostruzione si fa da parte e riprende dopo. Con il disco della libreria quasi pieno (sotto 10 GB o il 5 %
|
||||||
|
liberi, contando il file da scrivere) si mette in pausa e lo dice.
|
||||||
|
- **A che punto è**: in Impostazioni ▸ Esportazione e nella Dashboard, scheda Esportazione («In coda 12 · convertiti 340
|
||||||
|
· non riusciti 2 · non si convertono 3»), con **«Interrompi»**, **«Riprendi»** e **«Riprova i non riusciti»**. «Non si
|
||||||
|
converte» vuol dire che il file resta solo originale (HEIC, raw, un'immagine animata, un video che non va in MP4
|
||||||
|
senza ricodifica): non si riprova finché il file non cambia.
|
||||||
|
- Nel **visualizzatore**, pannello File: «Convertito in PNG · 2,1 MB» con «Mostra nella cartella» (Windows) o «Scarica»,
|
||||||
|
e sotto ciò che non si è tenuto.
|
||||||
|
- Solo tu togli un convertito, sempre con il suo originale: «Elimina dalla libreria» (la conferma li conta: «… 9 file e
|
||||||
|
2 file convertiti»), la rimozione di un account con i suoi file, «Tieni il più grande» per il file che scarti. Un
|
||||||
|
convertito che hai cambiato tu dopo la conversione resta dov'è, e Febe lo dice. Se l'originale cambia, il convertito
|
||||||
|
di prima resta e se ne fa uno nuovo.
|
||||||
|
- La ricostruzione del database non converte e riconosce i convertiti accanto agli originali; l'importazione riconosce
|
||||||
|
un convertito, o una copia convertita o un fotogramma di una cartella delle copie, come già in libreria («È una copia
|
||||||
|
convertita (o un fotogramma) di un file già in libreria.»).
|
||||||
|
|
||||||
## La Dashboard, scheda Esportazione
|
## La Dashboard, scheda Esportazione
|
||||||
|
|
||||||
La Dashboard ha due schede, **Motore** ed **Esportazione** (`/dashboard/esportazione`).
|
La Dashboard ha due schede, **Motore** ed **Esportazione** (`/dashboard/esportazione`).
|
||||||
@@ -150,8 +269,11 @@ La Dashboard ha due schede, **Motore** ed **Esportazione** (`/dashboard/esportaz
|
|||||||
- **Da riprendere:** le cartelle in pausa con il motivo e **«Riprova»**; le copie interrotte o in pausa con
|
- **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»** (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.
|
**«Riprendi tutte»**. Una copia interrotta da un arresto di Febe si ritrova qui al riavvio: non riparte da sola.
|
||||||
|
- **Conversione della libreria** (quando è accesa o ha già lavorato): a che punto è, con «Interrompi», «Riprendi» e
|
||||||
|
«Riprova i non riusciti».
|
||||||
- **Ultimi lavori**, ognuno con il suo **«Resoconto»**: copiati, già presenti e riconosciuti, già copiati, saltati, non
|
- **Ultimi lavori**, ognuno con il suo **«Resoconto»**: copiati, già presenti e riconosciuti, già copiati, saltati, non
|
||||||
presenti in libreria, non riusciti, per account, e i file da guardare con il motivo.
|
presenti in libreria, non riusciti, per account (con i file copiati come sono), i file da guardare con il motivo e le
|
||||||
|
note dei file copiati (che cosa non si è tenuto, che cosa si è copiato com'è).
|
||||||
|
|
||||||
Quando ci sono copie da riprendere o cartelle in pausa, la scheda Motore lo dice con un avviso.
|
Quando ci sono copie da riprendere o cartelle in pausa, la scheda Motore lo dice con un avviso.
|
||||||
|
|
||||||
|
|||||||
@@ -49,6 +49,8 @@ fare solo con Instagram o su Windows:
|
|||||||
Unraid.
|
Unraid.
|
||||||
- **Copie esterne degli originali (tappa E2, 27 novembre 2026):** pronte, da provare dal vivo su Unraid con
|
- **Copie esterne degli originali (tappa E2, 27 novembre 2026):** pronte, da provare dal vivo su Unraid con
|
||||||
`/esporta` montata e su Windows con una cartella di rete. Vedi [Copie esterne](Esportazione).
|
`/esporta` montata e su Windows con una cartella di rete. Vedi [Copie esterne](Esportazione).
|
||||||
|
- **Formati, fotogrammi e conversione della libreria (tappa E3, 28 novembre 2026):** pronti, da provare dal vivo con
|
||||||
|
foto e video veri della tua libreria (HEIC e MOV del telefono compresi). Vedi [Copie esterne](Esportazione).
|
||||||
|
|
||||||
## Pagine della guida
|
## Pagine della guida
|
||||||
|
|
||||||
@@ -60,7 +62,7 @@ fare solo con Instagram o su Windows:
|
|||||||
| [Account e impostazioni](Account-e-impostazioni) | Aggiungere account, punti di partenza, impostazioni per account |
|
| [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 |
|
| [Libreria](Libreria) | Mosaico, filtri, visualizzatore, eliminazione, esportazione CSV, nomi dei file |
|
||||||
| [Importazione](Importazione) | Portare in libreria foto e video che hai già, senza doppioni |
|
| [Importazione](Importazione) | Portare in libreria foto e video che hai già, senza doppioni |
|
||||||
| [Copie esterne](Esportazione) | Copiare i file della libreria su un disco esterno o una cartella di rete: cartelle, «Copia in…», stati delle copie, `/esporta` in Docker |
|
| [Copie esterne](Esportazione) | Copiare i file della libreria su un disco esterno o una cartella di rete: cartelle, «Copia in…», formati, fotogrammi, conversione della libreria, stati delle copie, `/esporta` in Docker |
|
||||||
| [Limiti e comportamento](Limiti-e-comportamento) | Profili di prudenza, tetti, fascia oraria, ritmo delle sessioni |
|
| [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 |
|
| [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 |
|
| [Avvisi e Telegram](Avvisi-e-Telegram) | Striscia, notifiche di Windows, messaggi Telegram con un bot tuo |
|
||||||
|
|||||||
@@ -43,7 +43,9 @@ Quattro contatori:
|
|||||||
|
|
||||||
I doppioni si cercano anche dentro la sorgente stessa (una copia identica nella sorgente si copia una volta sola). Per
|
I doppioni si cercano anche dentro la sorgente stessa (una copia identica nella sorgente si copia una volta sola). Per
|
||||||
i video vale solo lo SHA-256 (e il codice). Un file che hai eliminato «ricordando la scelta» conta come già in
|
i video vale solo lo SHA-256 (e il codice). Un file che hai eliminato «ricordando la scelta» conta come già in
|
||||||
libreria: un'importazione non annulla un'eliminazione.
|
libreria: un'importazione non annulla un'eliminazione. Anche un file convertito della libreria, o una copia convertita
|
||||||
|
o un fotogramma presi da una cartella delle copie ([Copie esterne](Esportazione)), conta come già in libreria («È una
|
||||||
|
copia convertita (o un fotogramma) di un file già in libreria.»), mai come doppione probabile dell'originale.
|
||||||
|
|
||||||
**Cartelle e account.** Una tabella lega ogni cartella della sorgente a un account: uno esistente (riconosciuto per
|
**Cartelle e account.** Una tabella lega ogni cartella della sorgente a un account: uno esistente (riconosciuto per
|
||||||
identificativo o per nome), oppure un nuovo account «Solo archivio» con il nome della cartella. Una cartella senza
|
identificativo o per nome), oppure un nuovo account «Solo archivio» con il nome della cartella. Una cartella senza
|
||||||
|
|||||||
@@ -43,7 +43,9 @@ si legge «Libreria, file 12 di 61.034». A lato: la serie dei file, didascalia,
|
|||||||
|
|
||||||
- **Mostra nella cartella** (Windows) oppure **Scarica** il file (dal browser, in Docker);
|
- **Mostra nella cartella** (Windows) oppure **Scarica** il file (dal browser, in Docker);
|
||||||
- **Apri su Instagram**, nel tuo browser;
|
- **Apri su Instagram**, nel tuo browser;
|
||||||
- **Elimina dalla libreria**.
|
- **Elimina dalla libreria**;
|
||||||
|
- con le copie esterne, **«Copia in…»** e, per i video, **«Fotogramma»** (vedi [Copie esterne](Esportazione)); nel
|
||||||
|
pannello File le righe delle copie e, con la conversione della libreria accesa, dei file convertiti.
|
||||||
|
|
||||||
## Eliminare
|
## Eliminare
|
||||||
|
|
||||||
@@ -55,7 +57,9 @@ Eliminare chiede conferma. I file vengono cancellati dal disco e non si recupera
|
|||||||
scarica di nuovo.
|
scarica di nuovo.
|
||||||
|
|
||||||
L'eliminazione si scrive prima nel file `_febe.jsonl` dell'account, poi nel database, poi sul disco: anche una
|
L'eliminazione si scrive prima nel file `_febe.jsonl` dell'account, poi nel database, poi sul disco: anche una
|
||||||
ricostruzione del database la rispetta.
|
ricostruzione del database la rispetta. Se la conversione della libreria ha aggiunto dei file convertiti, se ne vanno
|
||||||
|
con i loro originali e la conferma li conta («… 9 file e 2 file convertiti»); un convertito che hai cambiato tu resta.
|
||||||
|
Le copie esterne invece restano dove sono.
|
||||||
|
|
||||||
**La libreria non cancella e non sostituisce mai un file da sola.** Se un contenuto sparisce da Instagram, il file
|
**La libreria non cancella e non sostituisce mai un file da sola.** Se un contenuto sparisce da Instagram, il file
|
||||||
resta. Un file si elimina o si sostituisce solo per una scelta tua.
|
resta. Un file si elimina o si sostituisce solo per una scelta tua.
|
||||||
@@ -63,7 +67,8 @@ resta. Un file si elimina o si sostituisce solo per una scelta tua.
|
|||||||
## Selezione multipla
|
## Selezione multipla
|
||||||
|
|
||||||
«Seleziona» attiva la scelta delle tessere; nella barra in basso: **Esporta l'elenco** degli elementi scelti oppure
|
«Seleziona» attiva la scelta delle tessere; nella barra in basso: **Esporta l'elenco** degli elementi scelti oppure
|
||||||
**Elimina** (con la stessa conferma di sopra). «Fine» chiude la selezione.
|
**Elimina** (con la stessa conferma di sopra); **Fotogrammi…** per i video scelti; con una cartella delle copie anche
|
||||||
|
«Copia in…» ([Copie esterne](Esportazione)). «Fine» chiude la selezione.
|
||||||
|
|
||||||
Con «Tutte le foto» si scelgono i file, ma l'elenco CSV ed «Elimina» lavorano sugli **elementi interi** a cui
|
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
|
appartengono: la barra lo dice («3 file scelti, di 2 elementi», «Elimina 2 elementi») e anche la conferma («3 file
|
||||||
|
|||||||
@@ -152,6 +152,16 @@ Vedi anche [Copie esterne](Esportazione).
|
|||||||
| «C'è un lavoro di copia non finito verso questa cartella…» | Prima di cambiare la cartella, riprendi o annulla quel lavoro nella Dashboard, scheda Esportazione |
|
| «C'è un lavoro di copia non finito verso questa cartella…» | Prima di cambiare la cartella, riprendi o annulla quel lavoro nella Dashboard, scheda Esportazione |
|
||||||
| «Copia in…» dice «N di account che non si esportano» | Quegli account hanno «Esporta questo account» spento (scheda dell'account ▸ Impostazioni ▸ «Copie esterne») |
|
| «Copia in…» dice «N di account che non si esportano» | Quegli account hanno «Esporta questo account» spento (scheda dell'account ▸ Impostazioni ▸ «Copie esterne») |
|
||||||
| «Copia in…» o il filtro «Copie» non ci sono | Manca una cartella delle copie: scegline una in Impostazioni ▸ Esportazione (o nella scheda dell'account) |
|
| «Copia in…» o il filtro «Copie» non ci sono | Manca una cartella delle copie: scegline una in Impostazioni ▸ Esportazione (o nella scheda dell'account) |
|
||||||
|
| Ho scelto JPG ma un file è arrivato com'è («HEIC copiato com'è», «Immagine animata copiata com'è…», «Copiato com'è: …») | È voluto: HEIC, AVIF, raw, immagini animate, immagini CMYK o con più di 8 bit verso PNG e WEBP e quelle troppo grandi non si convertono. Le note sono nel resoconto e nel visualizzatore |
|
||||||
|
| «Video copiato com'è: non si porta in MP4 senza ricodificarlo (codec video)» | Il video non è H.264 o HEVC (o l'audio non è AAC o MP3, o il contenitore non si rimuxa): Febe non ricodifica mai, quindi lo copia com'è |
|
||||||
|
| «Già copiato in un altro formato» | Il file è già nella cartella in un'altra forma. Per averlo nel formato nuovo: togli il file vecchio dalla cartella, «Controlla le copie», poi «Copia di nuovo» |
|
||||||
|
| «Fotogramma non disponibile per questo video» | Il video è in un codec che Febe non decodifica (VP9, AV1…) o è rovinato. Il video intero si copia lo stesso |
|
||||||
|
| «Il fotogramma richiede troppo tempo: scegli la cartella delle copie» | Un video lungo o grande non dà l'anteprima in 30 secondi: scegli «Nella cartella delle copie», che lavora senza fretta |
|
||||||
|
| «Il motore è in sessione: per più di 20 fotogrammi riprova fra poco» | Uno zip di più di 20 fotogrammi si prepara solo fuori dalle sessioni del motore e quando non lavorano importazione, copie o ricostruzione: riprova dopo, o scegli meno fotogrammi |
|
||||||
|
| «Per più di 500 fotogrammi scegli la cartella delle copie» o «Più di 1.000 fotogrammi per un video…» | Sono i limiti di «Scarica» e di un video: scegli «Nella cartella delle copie», o un intervallo più lungo |
|
||||||
|
| La conversione della libreria non va avanti: «Il motore è in sessione…», «Un'importazione, una copia o una ricostruzione è al lavoro…» | È voluto: la conversione lavora in sottofondo e cede il passo. Riprende da sola |
|
||||||
|
| «Spazio libero sotto la soglia: la conversione della libreria è in pausa» | Il disco della libreria è quasi pieno: libera spazio (o spegni la conversione); riprende da sola |
|
||||||
|
| Un file convertito «non si converte» o «Conversione … non riuscita» | «Non si converte» è definitivo (HEIC, raw, animata…); per gli altri, se la cartella dell'account era staccata o il file mancava, sistema e premi «Riprova i non riusciti» in Impostazioni ▸ Esportazione |
|
||||||
|
|
||||||
## Database
|
## Database
|
||||||
|
|
||||||
|
|||||||
@@ -119,4 +119,5 @@ trattale come i dati che descrivono.
|
|||||||
Le [copie esterne](Esportazione) escono dal controllo di Febe: chi ha la cartella delle copie, o il disco su cui sta,
|
Le [copie esterne](Esportazione) escono dal controllo di Febe: chi ha la cartella delle copie, o il disco su cui sta,
|
||||||
ha quei file, foto e video di altre persone compresi. Febe non le cifra e non le cancella; nelle cartelle delle copie
|
ha quei file, foto e video di altre persone compresi. Febe non le cifra e non le cancella; nelle cartelle delle copie
|
||||||
non scrive diari, identificativi o didascalie, solo i file. Una chiavetta o un disco con le copie va trattato come la
|
non scrive diari, identificativi o didascalie, solo i file. Una chiavetta o un disco con le copie va trattato come la
|
||||||
libreria.
|
libreria. Lo stesso vale per i fotogrammi scaricati e per i loro zip, che finiscono nei download del browser. Una
|
||||||
|
conversione con perdita (JPG) è una scelta tua: Febe non la fa mai da sola.
|
||||||
@@ -549,7 +549,7 @@ cambiano». Se i nomi sono diversi, il catalogo va corretto prima di configurare
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## F. Copie esterne (tappa E2): Docker con `/esporta`, FAT32, cartella di rete su Windows
|
## F. Copie esterne (tappe E2 ed E3): Docker con `/esporta`, FAT32, cartella di rete su Windows, formati, fotogrammi
|
||||||
|
|
||||||
Scopo: vedere sul tuo impianto ciò che le prove automatiche non possono fare (specifica §4.10, §11, §12): un montaggio
|
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
|
vero su Unraid, un disco FAT32 vero, una condivisione che si stacca. **Non serve Instagram**: le copie leggono solo
|
||||||
@@ -618,10 +618,67 @@ in quelle cartelle, né crearne la cartella scelta.
|
|||||||
5. Facoltativo: esci da Febe durante una copia e riaprilo. Atteso: la copia è «Interrotta» nella scheda Esportazione e
|
5. Facoltativo: esci da Febe durante una copia e riaprilo. Atteso: la copia è «Interrotta» nella scheda Esportazione e
|
||||||
non riparte da sola; nel registro «N copie interrotte dall'arresto precedente…».
|
non riparte da sola; nel registro «N copie interrotte dall'arresto precedente…».
|
||||||
|
|
||||||
### F5. Che cosa riferire
|
### F5. Formati delle copie con i tuoi file (tappa E3)
|
||||||
|
|
||||||
|
Le prove automatiche convertono immagini e video costruiti da loro; qui servono file veri del tuo telefono e della
|
||||||
|
libreria: qualche JPG con la posizione nell'EXIF, una foto HEIC, un PNG con la trasparenza, una GIF animata, un MOV
|
||||||
|
dell'iPhone (meglio se girato in verticale) e un video con VP9 o AV1, se ne hai uno (per esempio un WebM).
|
||||||
|
|
||||||
|
1. Impostazioni ▸ Esportazione ▸ «Formati delle copie»: Foto **JPG**, Video **MP4**. Atteso: «con perdita: qualità 92»
|
||||||
|
sotto JPG, «solo rimuxaggio, mai ricodifica» sotto MP4.
|
||||||
|
2. «Copia in…» su quei file. Atteso nel riepilogo: «circa 1 HEIC copiato com'è», «con perdita». Copia, poi
|
||||||
|
«Resoconto»: l'HEIC, la GIF e il video VP9/AV1 «come sono», con la nota; il PNG con «La trasparenza è diventata
|
||||||
|
bianco».
|
||||||
|
3. Nella cartella delle copie: il JPG di partenza è **identico** all'originale (confronta lo SHA-256, per esempio con
|
||||||
|
`Get-FileHash` su Windows o `sha256sum` su Unraid); il PNG è diventato `.jpg`, con lo sfondo bianco dove era
|
||||||
|
trasparente; il MOV è diventato `.mp4`, si apre nel browser e nel lettore di sistema, è **diritto** come l'originale,
|
||||||
|
ha l'audio e la stessa durata, e le proprietà del file (Windows: Proprietà ▸ Dettagli) hanno la stessa data di
|
||||||
|
ripresa; la foto convertita ha ancora l'EXIF (data, fotocamera, posizione) e l'orientamento giusto.
|
||||||
|
4. Cambia Foto in **PNG** e rifai «Copia in…» sugli stessi file. Atteso: «già copiati, saltati» e nel resoconto «Già
|
||||||
|
copiato in un altro formato»; nessun file nuovo. Togli a mano un JPG convertito dalla cartella, «Controlla le copie»,
|
||||||
|
poi «Copia di nuovo» dal visualizzatore: atteso di nuovo il JPG (la forma di quella copia), non un PNG.
|
||||||
|
5. Rimetti i formati su «Originale».
|
||||||
|
|
||||||
|
### F6. Fotogrammi (tappa E3)
|
||||||
|
|
||||||
|
1. Apri nel visualizzatore un video vero H.264 (un reel scaricato) e uno HEVC (un MOV dell'iPhone recente). Ferma il
|
||||||
|
lettore su un'immagine riconoscibile e premi «Fotogramma». Atteso: la finestra si apre a quell'istante e
|
||||||
|
l'anteprima è **la stessa immagine** che vedevi; «Il fotogramma non ha l'audio.».
|
||||||
|
2. «Scarica» in PNG. Atteso: un file `…_t0m…s….png` della piena risoluzione del video, diritto come il video si vede.
|
||||||
|
3. «N in tutto» = 5, «Scarica». Atteso: uno zip `febe-fotogrammi-AAAA-MM-GG.zip` con una cartella dell'account e
|
||||||
|
cinque file `…_f001.png` … `…_f005.png`, distribuiti lungo il video.
|
||||||
|
4. Su un video VP9 o AV1 (o una tessera neutra): atteso «Fotogramma non disponibile per questo video».
|
||||||
|
5. Dalla Libreria: «Seleziona», scegli alcuni video e qualche foto, «Fotogrammi…», «Uno ogni 10 secondi», «Nella
|
||||||
|
cartella delle copie». Atteso: «le N foto si saltano»; il lavoro nella Dashboard; nella cartella i fotogrammi accanto
|
||||||
|
alle copie, con l'istante nel nome. Le tessere dei video copiati solo come fotogrammi hanno il segno «Solo
|
||||||
|
fotogrammi» e il filtro «Copie» li mette fra i «Non ancora copiati».
|
||||||
|
6. Facoltativo: durante una sessione del motore chiedi lo zip di 30 fotogrammi. Atteso: «Il motore è in sessione: per
|
||||||
|
più di 20 fotogrammi riprova fra poco»; fuori dalla sessione lo zip parte.
|
||||||
|
|
||||||
|
### F7. Conversione della libreria (tappa E3)
|
||||||
|
|
||||||
|
Prima: annota il numero dei file di una cartella di account e lo SHA-256 di due o tre originali (`Get-FileHash` o
|
||||||
|
`sha256sum`). Alla fine gli originali devono essere **identici** e i file solo in più.
|
||||||
|
|
||||||
|
1. Impostazioni ▸ Esportazione ▸ «Conversione della libreria»: Foto **PNG**. Atteso il dialogo «Convertire anche i N
|
||||||
|
file già in libreria?» con lo spazio degli originali; scegli **«Solo i nuovi»**. Atteso: niente in coda.
|
||||||
|
2. Importa (o lascia scaricare) due o tre foto JPG nuove. Atteso, fuori dalle sessioni del motore e entro un minuto o
|
||||||
|
due: «convertiti 3» nella riga di stato; accanto a ogni `foto.jpg` della libreria un `foto.png`; il visualizzatore
|
||||||
|
mostra «Convertito in PNG · …» con «Mostra nella cartella» (Windows) o «Scarica».
|
||||||
|
3. Avvia un'importazione grande mentre la conversione lavora (con «Anche i N già in libreria» su un account piccolo).
|
||||||
|
Atteso: l'importazione parte subito; la conversione dice «Un'importazione, una copia o una ricostruzione è al
|
||||||
|
lavoro…» e riprende dopo.
|
||||||
|
4. «Interrompi», poi «Riprendi». Atteso: si ferma e riparte; i file già convertiti restano.
|
||||||
|
5. Elimina dalla libreria un elemento con un convertito. Atteso: la conferma dice «… e 1 file convertito»; dopo,
|
||||||
|
originale e convertito non ci sono più, le copie esterne restano.
|
||||||
|
6. Rimetti Foto su «Originale». Atteso: la coda si svuota, i file convertiti restano dove sono.
|
||||||
|
|
||||||
|
### F8. Che cosa riferire
|
||||||
|
|
||||||
- Per ogni passo «come atteso» oppure il testo esatto di ciò che hai visto, con l'ora.
|
- Per ogni passo «come atteso» oppure il testo esatto di ciò che hai visto, con l'ora.
|
||||||
- Il conteggio dei file della cartella delle copie prima e dopo (F2, F4): solo file in più, mai meno o cambiati.
|
- Il conteggio dei file della cartella delle copie prima e dopo (F2, F4): solo file in più, mai meno o cambiati.
|
||||||
|
- In F5 e F7 gli SHA-256 degli originali prima e dopo (devono coincidere) e, per F5 passo 3, se data, posizione e
|
||||||
|
rotazione sono rimaste; in F6 se l'anteprima era davvero l'immagine che il lettore mostrava.
|
||||||
- Le righe del registro dell'avvio che parlano di copie esterne (F1, F2) e quelle della pausa (F2 passo 8, F4).
|
- Le righe del registro dell'avvio che parlano di copie esterne (F1, F2) e quelle della pausa (F2 passo 8, F4).
|
||||||
- In F2 passo 1 l'esito di `stat -c '%u:%g' /mnt/user/Febe-copie /mnt/user/Febe-copie/disco` dal terminale di Unraid.
|
- In F2 passo 1 l'esito di `stat -c '%u:%g' /mnt/user/Febe-copie /mnt/user/Febe-copie/disco` dal terminale di Unraid.
|
||||||
- Se un file è finito nel posto sbagliato (per esempio nella cartella vuota del server con il disco smontato): il
|
- Se un file è finito nel posto sbagliato (per esempio nella cartella vuota del server con il disco smontato): il
|
||||||
|
|||||||
|
Before Width: | Height: | Size: 101 KiB After Width: | Height: | Size: 112 KiB |
|
Before Width: | Height: | Size: 97 KiB After Width: | Height: | Size: 141 KiB |
|
Before Width: | Height: | Size: 148 KiB After Width: | Height: | Size: 163 KiB |
|
Before Width: | Height: | Size: 143 KiB After Width: | Height: | Size: 144 KiB |
|
Before Width: | Height: | Size: 515 KiB After Width: | Height: | Size: 482 KiB |
|
Before Width: | Height: | Size: 238 KiB After Width: | Height: | Size: 233 KiB |
|
Before Width: | Height: | Size: 447 KiB After Width: | Height: | Size: 257 KiB |
|
Before Width: | Height: | Size: 64 KiB After Width: | Height: | Size: 76 KiB |
|
After Width: | Height: | Size: 160 KiB |
|
After Width: | Height: | Size: 174 KiB |
|
After Width: | Height: | Size: 187 KiB |
|
After Width: | Height: | Size: 128 KiB |
|
After Width: | Height: | Size: 546 KiB |
|
After Width: | Height: | Size: 129 KiB |
@@ -41,14 +41,20 @@ solo per l'interfaccia di Febe (§10.7).
|
|||||||
| `doppioni-download.png` | `/doppioni` | confronto di `miniature/09-importa-revisione.png` (§9.5) |
|
| `doppioni-download.png` | `/doppioni` | confronto di `miniature/09-importa-revisione.png` (§9.5) |
|
||||||
| `primo-avvio.png` | `/libreria?scena=scollegato`, libreria vuota disegnata dal passo `benvenuto.js` | (nessuno: §10.3) |
|
| `primo-avvio.png` | `/libreria?scena=scollegato`, libreria vuota disegnata dal passo `benvenuto.js` | (nessuno: §10.3) |
|
||||||
| `errore-configurazione.png` | `/libreria?scena=errore` | (nessuno) |
|
| `errore-configurazione.png` | `/libreria?scena=errore` | (nessuno) |
|
||||||
| `15-impostazioni-esportazione.png` | `/impostazioni/esportazione` (presa il 27/11 da Windows, come le righe seguenti) | composta da `docs/mockup/08-impostazioni-generali.png` e `miniature/07-limiti-e-comportamento.png` |
|
| `15-impostazioni-esportazione.png` | `/impostazioni/esportazione`, 1440 × 1470 (presa il 27/11 da Windows, come le righe seguenti fino alla 21; tutte rifatte il 28/11 con i formati della tappa E3) | composta da `docs/mockup/08-impostazioni-generali.png` e `miniature/07-limiti-e-comportamento.png` |
|
||||||
| `15-impostazioni-esportazione-docker.png` | `/impostazioni/esportazione?veste=docker`, con la nota su `/esporta` | come sopra |
|
| `15-impostazioni-esportazione-docker.png` | `/impostazioni/esportazione?veste=docker`, con la nota su `/esporta` | come sopra |
|
||||||
| `16-destinazione.png` | `/impostazioni/esportazione`, «Modifica…» della cartella generale, «Uno schema suo» con il primo schema cambiato (passo `destinazione.js`), 1440 × 1000 | composta dal mockup 08 («Nomi dei file», «Risultato») e dai dialoghi di `miniature/13-foglio-di-stile.png` |
|
| `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` |
|
| `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` |
|
| `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`) | 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` |
|
| `20-visualizzatore-copie.png` | `/libreria?copie=tolti`, la prima foto con «Copia di nuovo» (passo `visualizzatore-copie.js`) | composta da `miniature/02-visualizzatore.png` |
|
||||||
| `21-dashboard-esportazione.png` | `/dashboard/esportazione` | composta da `miniature/06-attivita.png` e dal passo 2 dell'importazione (mockup 09) |
|
| `21-dashboard-esportazione.png` | `/dashboard/esportazione`, con il riquadro «Conversione della libreria» | composta da `miniature/06-attivita.png` e dal passo 2 dell'importazione (mockup 09) |
|
||||||
|
| `22-fotogrammi-visualizzatore.png` | `/libreria`, il video di @marta.demo con un fotogramma copiato, il lettore a 1,25 s, «Fotogramma»: «Questo istante» con l'anteprima (passo `fotogrammi-visualizzatore.js`), 1440 × 1000 (presa il 28/11 da Windows, come le righe seguenti) | composta dai dialoghi di `miniature/13-foglio-di-stile.png` sopra `miniature/02-visualizzatore.png` |
|
||||||
|
| `22-fotogrammi-striscia.png` | come sopra, «N in tutto» 8, JPG, «Nella cartella delle copie» (passo `fotogrammi-striscia.js`), 1440 × 1000 | come sopra, con la riga delle cartelle di `miniature/09-importa-revisione.png` |
|
||||||
|
| `23-fotogrammi-selezione.png` | `/libreria?account=2` (@marta.demo), «Seleziona», quattro video e quattro foto, «Fotogrammi…» (passo `fotogrammi-selezione.js`), 1440 × 1000 | composta dai dialoghi del 13 sopra `docs/mockup/01-libreria.png` |
|
||||||
|
| `24-visualizzatore-fotogramma.png` | `/libreria`, lo stesso video, righe «Copia» con «· intero» e «· fotogramma a 0:01,125 · PNG» (passo `visualizzatore-fotogramma.js`) | composta da `miniature/02-visualizzatore.png` |
|
||||||
|
| `25-copia-in-formati.png` | come la 18, con «Cambia» aperto e PNG per le foto (passo `copia-in-formati.js`), 1440 × 1000 | composta dai dialoghi del 13 e dai controlli segmentati di `miniature/07-limiti-e-comportamento.png` |
|
||||||
|
| `26-conversione-libreria.png` | `/impostazioni/esportazione`, «Conversione della libreria» → PNG: la domanda «Convertire anche i N file già in libreria?» (passo `conversione-libreria.js`; nessuna risposta, l'impostazione resta «Originale») | composta da `docs/mockup/08-impostazioni-generali.png` e dai dialoghi del 13 |
|
||||||
|
|
||||||
## Differenze che restano
|
## Differenze che restano
|
||||||
|
|
||||||
@@ -228,14 +234,15 @@ da cui nascono. Le prove dell'interfaccia (`ExportInterfaceTests`: impostazioni
|
|||||||
destinazione, blocco dell'account, «Copia in…» dalla selezione, filtro «Copie» e segno sulle tessere, righe del
|
destinazione, blocco dell'account, «Copia in…» dalla selezione, filtro «Copie» e segno sulle tessere, righe del
|
||||||
visualizzatore, scheda della Dashboard) girano solo nella CI, con Chromium: qui non sono state eseguite. Differenze:
|
visualizzatore, scheda della Dashboard) girano solo nella CI, con Chromium: qui non sono state eseguite. Differenze:
|
||||||
|
|
||||||
- **Formati e conversione non ci sono (E3).** La tappa E2 copia solo gli originali: la finestra della destinazione non
|
- **Formati e conversione non c'erano (E3).** Nelle schermate del 27/11 la finestra della destinazione non aveva la
|
||||||
ha la parte dei formati, Impostazioni → Esportazione non ha «Formati predefiniti delle copie» né «Conversione della
|
parte dei formati, Impostazioni → Esportazione non aveva «Formati delle copie» né «Conversione della libreria», e
|
||||||
libreria», e il riepilogo di «Copia in…» non ha mai «3 HEIC copiati come sono» né «con perdita». I controlli mancano,
|
«Copia in…» non aveva la riga del formato: sono arrivati con la tappa E3, e le schermate 15–21 sono state rifatte il
|
||||||
non sono spenti: un controllo grigio senza niente dietro non dice che cosa succede (§10.4).
|
28/11 con loro (qui sotto, «Formati e fotogrammi»).
|
||||||
- **«Automatica» non c'è (E5).** La scelta si conserva ma non si mostra, con la domanda «Solo i nuovi»: senza il giro
|
- **«Automatica» non c'è (E5).** La scelta si conserva ma non si mostra, con la domanda «Solo i nuovi»: senza il giro
|
||||||
orario della tappa E5 un interruttore acceso non farebbe nulla.
|
orario della tappa E5 un interruttore acceso non farebbe nulla.
|
||||||
- **«Fotogrammi…» e «Fotogramma» non ci sono (E3)**: né nella barra della selezione della Libreria e della scheda
|
- **«Fotogrammi…» e «Fotogramma» non c'erano (E3)** nelle schermate del 27/11: né nella barra della selezione della
|
||||||
account, né nel visualizzatore. Neppure la finestra «Fotogrammi…».
|
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'è (E4)** nel visualizzatore.
|
||||||
- **Segno sulla tessera** (voluto, §4.10): l'ultimo dei segni in alto a destra, un riquadro scuro con l'icona `copy`
|
- **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'è.
|
quando i file dovuti dell'elemento sono tutti copiati, con «2/3» quando lo sono solo in parte. Nel mockup 01 non c'è.
|
||||||
@@ -287,6 +294,81 @@ visualizzatore, scheda della Dashboard) girano solo nella CI, con Chromium: qui
|
|||||||
visualizzatore, la finestra della destinazione in Docker, il «Resoconto», una copia in corso con Interrompi, una
|
visualizzatore, la finestra della destinazione in Docker, il «Resoconto», una copia in corso con Interrompi, una
|
||||||
cartella in pausa con «Riprova», il tema scuro, la finestra stretta e il telefono.
|
cartella in pausa con «Riprova», il tema scuro, la finestra stretta e il telefono.
|
||||||
|
|
||||||
|
### Formati e fotogrammi (tappa E3, issue #58, dal 28 novembre 2026)
|
||||||
|
|
||||||
|
Anche queste parti non hanno un mockup (§10.3 «Schermate dell'esportazione»): sono composte dai mockup esistenti, come
|
||||||
|
dice la tabella. Il 28/11 le schermate `15-…` – `21-…` sono state rifatte e le sei nuove `22-…` – `26-…` prese con il
|
||||||
|
programma delle schermate da Windows (`tools/Febe.Schermate`, browser senza finestra, scala 1,25), una alla volta con
|
||||||
|
`una`, su una dimostrazione appena avviata (`--demo --porta 8490`), nell'ordine della tabella; nessun passo converte,
|
||||||
|
scarica o copia, e la domanda della conversione resta senza risposta. Misure: 1440 × 900; 1440 × 1000 per le finestre
|
||||||
|
alte (fotogrammi, «Copia in…» con «Cambia» aperto); 1440 × 1470 per Impostazioni → Esportazione intera, che ora arriva
|
||||||
|
fino a «Conversione della libreria». Poi sono state messe accanto ai mockup da cui nascono; le stesse finestre sono state
|
||||||
|
guardate anche in tema scuro e a 390 × 844 (senza schermata nella cartella). Le prove dell'interfaccia girano solo nella
|
||||||
|
CI. Differenze:
|
||||||
|
|
||||||
|
- **Impostazioni → Esportazione** (mockup 08 e 07): due blocchi nuovi, «Formati delle copie» dopo «Cartella generale» e
|
||||||
|
«Conversione della libreria» in fondo, con i controlli segmentati del mockup 07 (Foto: Originale · JPG · PNG · WEBP
|
||||||
|
senza perdita; Video: Originale · MP4) e la nota sotto il controllo («con perdita: qualità 92», «solo rimuxaggio, mai
|
||||||
|
ricodifica»). Il blocco della conversione ha la riga di stato («In coda 12 · convertiti 340 · …») con «Interrompi» o
|
||||||
|
«Riprendi» e «Riprova i non riusciti», e l'avviso del motivo dell'attesa; la domanda «Convertire anche i N file già
|
||||||
|
in libreria?» è un dialogo del mockup 13 con «Solo i nuovi» come pulsante principale.
|
||||||
|
- **Finestra della destinazione**: una parte «Formati» con gli stessi controlli e la prima voce «Come le impostazioni
|
||||||
|
generali».
|
||||||
|
- **«Copia in…»**: una riga «Formato: come la destinazione · Cambia» sopra il riepilogo; «Cambia» apre i due controlli
|
||||||
|
per quella copia sola. Il riepilogo aggiunge «circa 3 HEIC copiati come sono» e «con perdita».
|
||||||
|
- **Finestra «Fotogrammi…»** (dialoghi del mockup 13, elenco delle scelte del passo 3 del mockup 09): dal visualizzatore
|
||||||
|
anteprima grande del fotogramma (al più 480 pixel), cursore e campo dell'istante, la riga «Fotogramma a 0:01,125»,
|
||||||
|
una striscia con le prime sei anteprime e «e altri N»; poi formato (PNG, JPG con la nota «con perdita», WEBP senza
|
||||||
|
perdita), «Il fotogramma non ha l'audio.» e l'uscita, «Scarica» o «Nella cartella delle copie» (spenta senza una
|
||||||
|
cartella). **Dalla selezione** la finestra ha solo il campo dell'istante, senza anteprime né cursore (non c'è un
|
||||||
|
video solo), e il riepilogo dice «4 fotogrammi da 4 video · le 6 foto si saltano» (23).
|
||||||
|
- **Visualizzatore** (mockup 02): «Fotogramma» fra le azioni dei video (ferma il video e apre la finestra al suo
|
||||||
|
istante), o la riga «Fotogramma non disponibile per questo video»; le righe delle copie aggiungono la forma («· intero»,
|
||||||
|
«· PNG», «· fotogramma a 0:01,125 · PNG») e le note su una seconda riga; i file convertiti della libreria hanno una
|
||||||
|
riga loro («Convertito in PNG · 2,1 MB») con «Mostra nella cartella» su Windows o «Scarica».
|
||||||
|
- **Segno «Solo fotogrammi»** sulla tessera (mockup 01): un piccolo riquadro disegnato in CSS, senza un'icona nuova,
|
||||||
|
nello stesso posto del segno delle copie. Nel mockup non c'è (come il segno delle copie, voluto).
|
||||||
|
- **Dashboard → Esportazione**: un riquadro «Conversione della libreria» fra «Da riprendere» e «Ultimi lavori», solo
|
||||||
|
quando la conversione è accesa o ha righe; nel resoconto la colonna «Come sono» e la parte «Note». Aggiunte senza
|
||||||
|
mockup.
|
||||||
|
- **Conferma dell'eliminazione**: aggiunge i file convertiti («… elimino gli elementi interi, 9 file e 2 file
|
||||||
|
convertiti»).
|
||||||
|
- **Dialoghi sopra il visualizzatore**: un dialogo aperto dal visualizzatore (la finestra «Fotogrammi», «Copia in…»)
|
||||||
|
ora sta sopra di lui; prima restava sotto.
|
||||||
|
- **Contenuti dimostrativi.** Ogni video della dimostrazione è lo stesso video di 2 secondi, 240 × 432: le informazioni
|
||||||
|
del file nel visualizzatore (720 × 1280, 0:11 nella 22 e nella 24) non coincidono con quelle della finestra dei
|
||||||
|
fotogrammi («Video di 0:02, 240 × 432 pixel»), e l'anteprima è stretta in mezzo a un riquadro nero largo. «Nella
|
||||||
|
cartella delle copie» dei fotogrammi e una «Copia in…» di un video finiscono in errore nella dimostrazione («non
|
||||||
|
corrisponde»), perché i video dimostrativi hanno lo SHA-256 della loro copertina; le anteprime e «Scarica» funzionano.
|
||||||
|
Le foto della dimostrazione sono tutte JPEG: nella 25 il riepilogo di «Copia in…» con PNG resta uguale a quello della
|
||||||
|
18 (994 file; i 28.865 già copiati restano «già copiati» in qualunque formato, decisione D3) e non può mostrare né
|
||||||
|
«con perdita» né «copiati come sono» («con perdita» si vede nella 22-striscia: «8 fotogrammi da 1 video · con
|
||||||
|
perdita»). Il segno
|
||||||
|
«Solo fotogrammi» non si vede in nessuna tessera: il video del fotogramma dimostrativo ha anche la copia intera (per
|
||||||
|
SHA-256, come sopra), quindi la sua tessera ha il segno delle copie. I numeri delle schermate 15–21 sono quelli della
|
||||||
|
dimostrazione del 28/11 e non coincidono con quelli citati qui sopra per la tappa E2 (per esempio «335 su 657 non ancora
|
||||||
|
copiati» invece di «371 su 648»).
|
||||||
|
- **Confronto con le immagini** (28/11): la finestra «Fotogrammi» ha intestazione, piede con «Annulla» e il pulsante
|
||||||
|
principale, titoli delle parti e righe divisorie dei dialoghi del 13; le scelte «Scarica» / «Nella cartella delle
|
||||||
|
copie» sono le scelte a pallino con la riga d'aiuto del passo 3 del mockup 09; la riga della cartella nella 22-striscia
|
||||||
|
e nella 25 è quella dell'elenco delle cartelle dell'importazione. I controlli dei formati sono i segmentati del mockup
|
||||||
|
07, con l'etichetta a sinistra come le righe del mockup 08. Il visualizzatore (24) è quello del mockup 02 con le righe
|
||||||
|
«Copia» e cinque azioni in fondo invece di due («Copia in…» e «Fotogramma» si aggiungono). Nessuna differenza da
|
||||||
|
segnalare oltre a quelle elencate qui sopra e ai ritocchi seguenti.
|
||||||
|
- **Sistemato il 28/11** dopo il confronto:
|
||||||
|
- nella finestra «Fotogrammi» la riga «Fotogramma a 0:01,25» accanto al campo dell'istante (e «Lo stesso istante in ogni
|
||||||
|
video…» dalla selezione) stava 6 px più in alto del campo, perché la regola dei paragrafi dei dialoghi le dava 12 px
|
||||||
|
sotto: ora è centrata sul campo;
|
||||||
|
- sotto «Formato» la nota «Il fotogramma non ha l'audio.» (e «con perdita: qualità 92») aveva 12 px in più sotto, e la
|
||||||
|
parte «Formato» finiva più larga delle altre: ora le parti hanno lo stesso respiro;
|
||||||
|
- in «Copia in…» con «Cambia» aperto il controllo delle foto (cinque voci) non stava accanto all'etichetta «Foto» e
|
||||||
|
andava a capo, mentre quello dei video restava accanto a «Video»: i due controlli partivano da punti diversi. Ora in
|
||||||
|
«Copia in…» le etichette stanno sopra i controlli, e i due controlli sono allineati.
|
||||||
|
- **Senza schermata:** la veste Docker («Scarica» del convertito), la linguetta della scheda account con «Fotogrammi…»,
|
||||||
|
«Uno ogni k secondi», la riga «Convertito in PNG» del visualizzatore, la conferma dell'eliminazione con i file
|
||||||
|
convertiti, il resoconto con «Come sono» e «Note», il tema scuro, la finestra stretta e il telefono (guardati, senza
|
||||||
|
difetti da correggere), uno zip di più di 20 fotogrammi durante una sessione.
|
||||||
|
|
||||||
### Carattere e icone (dal 18 novembre 2026)
|
### 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
|
Mockup e schermate di questa cartella sono stati presi con il carattere Archivo e le icone Lucide, che dal 18 novembre
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
# Stato
|
# Stato
|
||||||
|
|
||||||
Filo fra le sessioni (specifica §15): che cosa è fatto, che cosa è in corso, che cosa è rimandato e perché.
|
Filo fra le sessioni (specifica §15): che cosa è fatto, che cosa è in corso, che cosa è rimandato e perché.
|
||||||
Aggiornato il 27 novembre 2026 (tappa E2 Copie esterne; prima, E1 Schema unita in `main` con #69 e la catena della
|
Aggiornato il 28 novembre 2026 (tappa E3 Formati e fotogrammi; prima, E2 Copie esterne e E1 Schema unita in `main` con #69 e la catena della
|
||||||
0.3.0, #60 … #66), versione 0.1.2 in
|
0.3.0, #60 … #66), versione 0.1.2 in
|
||||||
`main` (il tag `v0.1.2` non è stato creato). **Le attività stanno
|
`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
|
su Gitea**: issue, etichette e traguardi di https://gitea.encke-hake.ts.net/Alby96/Febe. Questo file resta il resoconto
|
||||||
@@ -9,6 +9,62 @@ fra le sessioni; ciò che è da fare si legge nelle issue aperte.
|
|||||||
|
|
||||||
## In breve
|
## In breve
|
||||||
|
|
||||||
|
**28 novembre 2026: tappa E3 «Formati e fotogrammi» dell'esportazione** (#58, ramo
|
||||||
|
`funzione/esportazione-formati`). Le undici domande nuove della tappa sono in §16 (righe 28–38) con la proposta
|
||||||
|
adottata, da confermare con Alberto.
|
||||||
|
|
||||||
|
- **Foto** (`src/Febe.Core/Codecs/Images/`, `ImageConverter`): copie e libreria in JPG (qualità 92, 4:4:4, trasparenza
|
||||||
|
su bianco, «con perdita»), PNG o WEBP senza perdita; stesso formato = copia byte per byte (anche un WEBP con perdita
|
||||||
|
verso «WEBP senza perdita»). EXIF, ICC e XMP nei loro blocchi; ciò che non si tiene diventa una nota (elenco di
|
||||||
|
codici). Si copiano come sono, con una nota: HEIC, AVIF, raw, animate, illeggibili, CMYK o più di 8 bit verso
|
||||||
|
PNG/WEBP, oltre 40/100 MP o 16.384 px. Stessi byte a ogni conversione sullo stesso runtime (logaritmo a virgola fissa
|
||||||
|
nel WEBP).
|
||||||
|
- **Video**: rimuxaggio in MP4 (MOV, M4V, 3GP, Matroska/WebM con H.264 o HEVC e AAC/MP3) con campioni, tempi, edit
|
||||||
|
list, rotazione e lingua; ciò che non si rimuxa si copia intero con il motivo. **Fotogrammi esatti** (`VideoFrameReader`):
|
||||||
|
un istante, «uno ogni k secondi» da 0:00, «N in tutto» al centro di N parti; PNG di base; nomi `_t0m12s340` e `_f001`;
|
||||||
|
verso le destinazioni (segno «Solo fotogrammi», «Copiato in parte»), «Scarica» di un'immagine o di uno zip (fino a
|
||||||
|
20 sempre, 21–500 fuori dalle sessioni del motore, oltre solo nella cartella delle copie).
|
||||||
|
- **Copie**: formato scelto da «Copia in…», poi dalla destinazione, poi dalle impostazioni; si converte prima dei
|
||||||
|
controlli di spazio e FAT32; adozione per lunghezza e SHA-256 della conversione; «già copiato» in qualunque forma
|
||||||
|
tranne il fotogramma; «Copia di nuovo» con l'identità esatta. Nessuna migrazione: bastano le tabelle di E1.
|
||||||
|
- **Conversione della libreria** (`LibraryConversionWorker`): un file convertito accanto all'originale, mai al suo
|
||||||
|
posto, con la riga di `media_conversion` sempre vera (anche dopo un arresto, un'eliminazione, un doppione, una
|
||||||
|
ricostruzione, un'importazione); permesso di sottofondo di `LongWorkGate` che cede al lavoro in primo piano; una
|
||||||
|
conversione alla volta nel processo; pausa con poco spazio o durante una sessione del motore; «Solo i nuovi» o
|
||||||
|
«Anche i N già in libreria», per tipo; mai nella dimostrazione. Nuove chiavi
|
||||||
|
`esportazione.libreria-formato-foto-dal` e `-video-dal` per sapere che cosa è «nuovo».
|
||||||
|
- **Interfaccia**: menu dei formati con «con perdita» in Impostazioni, destinazioni e «Copia in…» («Cambia»); dialogo
|
||||||
|
«Fotogrammi…» dal visualizzatore (all'istante del lettore, con anteprima) e dalla selezione; righe di copia e di
|
||||||
|
conversione nel visualizzatore; conteggio dei convertiti nella conferma di eliminazione. Nessun controllo di E4.
|
||||||
|
- **Revisione a più lenti**, due giri prima dell'unione: 16 rilievi confermati e corretti (`958cb71`), poi 4 sulle
|
||||||
|
correzioni stesse (`2efb408`). I più seri: un JPEG progressivo fra circa 57 e 100 MP segnato «illeggibile» per sempre
|
||||||
|
invece che «troppo grande»; «N in tutto» con N oltre la durata in ms perdeva istanti e spostava i nomi `_fNNN`; i video
|
||||||
|
di durata ignota sfuggivano ai limiti di 1.000 e 20.000 fotogrammi; il rimuxaggio mostrava la coda nascosta di un
|
||||||
|
video tagliato in fondo; «Riprova» riconvertiva in un formato spento; «Anche i N» di un tipo metteva in coda anche
|
||||||
|
l'altro; uno zip lento si interrompeva dopo 60 s; due cambi rapidi delle impostazioni ne perdevano uno.
|
||||||
|
- Documenti: SPECIFICA §4.10, §16 righe 28–38; righe del 28/11 in `decisioni.md`; guida `Esportazione.md`;
|
||||||
|
schermate 15–21 rifatte e sei nuove (22–26) con il confronto in `docs/schermate/differenze.md`.
|
||||||
|
- Controlli, su Windows: `dotnet build -warnaserror` 0 avvisi, 0 errori; `dotnet test tests/Febe.Tests` 3187
|
||||||
|
superate, 110 ignorate (Chromium e Xvfb: solo nella CI), 0 non superate; `dotnet test tests/Febe.Tests.Windows` 24
|
||||||
|
superate. Nella CI l'esecuzione 502 (prima delle correzioni) si è fermata 42 minuti con tutto il processo delle prove
|
||||||
|
(anche le prove H.265 da 1 s), e due prove d'interfaccia nuove sono scadute in quella pausa; la stessa revisione
|
||||||
|
nell'immagine della CI in locale è verde in 10 m 33 s e nel codice di E3 non c'è nulla che blocchi i thread. Se si
|
||||||
|
ripete, il prossimo passo è limitare i Chromium paralleli nelle prove (`UiBrowser`) e aggiungere `--blame-hang`.
|
||||||
|
- **Non verificato**:
|
||||||
|
- le sette prove d'interfaccia nuove (`ExportInterfaceTests.Formats.cs`) girano solo nella CI di Linux; nessuna
|
||||||
|
clicca «Scarica» o avvia un lavoro di fotogrammi o di video nella dimostrazione;
|
||||||
|
- file veri grandi: foto da 40–100 MP, video oltre 4 GiB (`co64`), HEVC di telefoni veri; le prove usano media
|
||||||
|
costruiti dalle prove;
|
||||||
|
- senza prova loro: più edit di seguito, AAC di Matroska vecchio stile, Opus, tracce Matroska codificate, un flusso
|
||||||
|
che comincia solo con CRA, una pausa in mezzo a un gruppo di fotogrammi, l'eliminazione di un account con file
|
||||||
|
convertiti su un disco vero;
|
||||||
|
- stessi byte fra versioni diverse di .NET (lo zlib del PNG è quello del runtime: scritto in `decisioni.md`);
|
||||||
|
- nessuna schermata di: veste Docker, «Uno ogni k secondi», riga «Convertito in PNG» del visualizzatore, conferma
|
||||||
|
di eliminazione, Resoconto; tema scuro e 390 px visti solo su prove scartate;
|
||||||
|
- nella dimostrazione «con perdita» non compare in «Copia in…» (le foto di esempio sono tutte JPEG) e nessuna
|
||||||
|
tessera ha il segno «Solo fotogrammi».
|
||||||
|
- **Prossima tappa**: E4 «Video fermi» oppure E5 «Esportazione automatica», a scelta di Alberto.
|
||||||
|
|
||||||
**27 novembre 2026: tappa E2 «Copie esterne» dell'esportazione** (#58). Decisione di Alberto di oggi: «Esporta questo
|
**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
|
account» senza una scelta registrata (nessuna riga in `export_account`) è **acceso**. Le altre sei domande della tappa
|
||||||
sono in §16 (righe 22–27) con la proposta adottata, da confermare.
|
sono in §16 (righe 22–27) con la proposta adottata, da confermare.
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ using Febe.Core.Engine;
|
|||||||
using Febe.Core.Export;
|
using Febe.Core.Export;
|
||||||
using Febe.Core.Import;
|
using Febe.Core.Import;
|
||||||
using Febe.Core.Library;
|
using Febe.Core.Library;
|
||||||
|
using Febe.Core.Library.Conversion;
|
||||||
using Febe.Core.Security;
|
using Febe.Core.Security;
|
||||||
using Febe.Core.Storage;
|
using Febe.Core.Storage;
|
||||||
using Febe.Data;
|
using Febe.Data;
|
||||||
@@ -194,9 +195,12 @@ public sealed class FebeApp : IAsyncDisposable
|
|||||||
DataFolder = data.Root,
|
DataFolder = data.Root,
|
||||||
Gate = longWork,
|
Gate = longWork,
|
||||||
});
|
});
|
||||||
|
var idleConversion = new LibraryConversionWorker(new LibraryConversionEnvironment { Storage = Database, Layout = () => library.Layout, Clock = Clock, Gate = longWork });
|
||||||
await StartWebAsync(hooks, services =>
|
await StartWebAsync(hooks, services =>
|
||||||
{
|
{
|
||||||
services.AddSingleton(longWork);
|
services.AddSingleton(longWork);
|
||||||
|
services.AddSingleton(idleConversion);
|
||||||
|
services.AddSingleton(new LibraryConversionQueue(Database, Clock));
|
||||||
services.AddSingleton(ExportRootOptions.Docker(Path.Combine(_temporaryFolder, "esporta"), declared: false));
|
services.AddSingleton(ExportRootOptions.Docker(Path.Combine(_temporaryFolder, "esporta"), declared: false));
|
||||||
services.AddSingleton<IFebeStorage>(Database);
|
services.AddSingleton<IFebeStorage>(Database);
|
||||||
services.AddSingleton(library);
|
services.AddSingleton(library);
|
||||||
@@ -336,12 +340,28 @@ public sealed class FebeApp : IAsyncDisposable
|
|||||||
_telegram = new TelegramClient(hooks.TelegramHandler);
|
_telegram = new TelegramClient(hooks.TelegramHandler);
|
||||||
var telegramChannel = new TelegramAlertChannel(_telegram);
|
var telegramChannel = new TelegramAlertChannel(_telegram);
|
||||||
|
|
||||||
|
// The conversion for the library (tappa E3, spec §4.10): one worker, started below in the background; it yields
|
||||||
|
// to import, copies and rebuild through the gate and never runs during an engine session. Never in the demo.
|
||||||
|
var sessionState = new RuntimeSessionState(services.Runtime);
|
||||||
|
var conversion = new LibraryConversionWorker(new LibraryConversionEnvironment
|
||||||
|
{
|
||||||
|
Storage = Database,
|
||||||
|
Layout = () => library.Layout,
|
||||||
|
Clock = Clock,
|
||||||
|
Gate = longWork,
|
||||||
|
Session = sessionState,
|
||||||
|
FreeSpace = hooks.FreeSpace ?? new DriveFreeSpaceProbe(),
|
||||||
|
Log = message => Log.Write(LogLevel.Warning, "conversione", message),
|
||||||
|
});
|
||||||
|
|
||||||
await StartWebAsync(hooks, s =>
|
await StartWebAsync(hooks, s =>
|
||||||
{
|
{
|
||||||
s.AddSingleton(longWork);
|
s.AddSingleton(longWork);
|
||||||
|
s.AddSingleton(conversion);
|
||||||
|
s.AddSingleton(new LibraryConversionQueue(Database, Clock));
|
||||||
s.AddSingleton(exportRoot);
|
s.AddSingleton(exportRoot);
|
||||||
s.AddSingleton<IExportDisk>(hooks.ExportDisk ?? new SystemExportDisk(exportRoot.Mounts));
|
s.AddSingleton<IExportDisk>(hooks.ExportDisk ?? new SystemExportDisk(exportRoot.Mounts));
|
||||||
s.AddSingleton<IEngineSessionState>(new RuntimeSessionState(services.Runtime));
|
s.AddSingleton<IEngineSessionState>(sessionState);
|
||||||
s.AddSingleton<IFebeStorage>(Database);
|
s.AddSingleton<IFebeStorage>(Database);
|
||||||
s.AddSingleton(library);
|
s.AddSingleton(library);
|
||||||
s.AddSingleton<IClock>(Clock);
|
s.AddSingleton<IClock>(Clock);
|
||||||
@@ -398,6 +418,7 @@ public sealed class FebeApp : IAsyncDisposable
|
|||||||
InBackground(() => BackupLoopAsync(new DailyBackup(Database, Clock, data.Backups), lifetime));
|
InBackground(() => BackupLoopAsync(new DailyBackup(Database, Clock, data.Backups), lifetime));
|
||||||
InBackground(() => BringUpBrowserAsync(ingest, staging, services, engine, runner, search, lifetime));
|
InBackground(() => BringUpBrowserAsync(ingest, staging, services, engine, runner, search, lifetime));
|
||||||
InBackground(() => Alerts.WatchDiskSpaceAsync(lifetime));
|
InBackground(() => Alerts.WatchDiskSpaceAsync(lifetime));
|
||||||
|
InBackground(() => conversion.RunAsync(lifetime));
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>Runs <paramref name="work"/> in the background; the stop waits for it.</summary>
|
/// <summary>Runs <paramref name="work"/> in the background; the stop waits for it.</summary>
|
||||||
|
|||||||
@@ -13,19 +13,38 @@ public enum LongWorkKind
|
|||||||
|
|
||||||
/// <summary>«Ricostruisci il database dalla libreria» (spec §8.5).</summary>
|
/// <summary>«Ricostruisci il database dalla libreria» (spec §8.5).</summary>
|
||||||
Rebuild,
|
Rebuild,
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The conversion for the library (tappa E3, spec §4.10): held only as a <see cref="LongWorkGate.BackgroundLease"/>,
|
||||||
|
/// which any of the others pre-empts.
|
||||||
|
/// </summary>
|
||||||
|
LibraryConversion,
|
||||||
|
|
||||||
|
/// <summary>A zip of 21 to 500 frames being prepared for «Scarica» (tappa E3, D14).</summary>
|
||||||
|
FrameDownload,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Lets only one of import, export and rebuild run at a time, in both directions. One instance is shared by the whole
|
/// Lets only one of import, export, rebuild and frame download run at a time, in both directions. One instance is
|
||||||
/// process (the composition registers it once). A lease is taken when a job starts and disposed when it ends; disposing
|
/// shared by the whole process (the composition registers it once). A lease is taken when a job starts and disposed when
|
||||||
/// it twice releases nothing more.
|
/// it ends; disposing it twice releases nothing more.
|
||||||
|
/// <para>
|
||||||
|
/// The conversion for the library takes a <see cref="BackgroundLease"/> instead (tappa E3, WP2.1): it runs only while
|
||||||
|
/// no foreground lease is held, and a foreground <see cref="TryEnter"/> pre-empts it. Outside a commit the conversion
|
||||||
|
/// only reads an original and writes its own temporary file, so it simply stops; a commit (one rename and one
|
||||||
|
/// transaction) is waited for, at most <see cref="CommitWait"/>.
|
||||||
|
/// </para>
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public sealed class LongWorkGate
|
public sealed class LongWorkGate
|
||||||
{
|
{
|
||||||
private readonly Lock _lock = new();
|
private readonly Lock _lock = new();
|
||||||
private Lease? _holder;
|
private Lease? _holder;
|
||||||
|
private BackgroundLease? _background;
|
||||||
|
|
||||||
/// <summary>Who holds the gate, or null when it is free.</summary>
|
/// <summary>How long a foreground <see cref="TryEnter"/> waits for a commit of the background work to end.</summary>
|
||||||
|
public TimeSpan CommitWait { get; init; } = TimeSpan.FromSeconds(10);
|
||||||
|
|
||||||
|
/// <summary>Who holds the gate in the foreground, or null when it is free. The background lease does not count.</summary>
|
||||||
public LongWorkKind? Busy
|
public LongWorkKind? Busy
|
||||||
{
|
{
|
||||||
get
|
get
|
||||||
@@ -37,12 +56,34 @@ public sealed class LongWorkGate
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>True while the background lease (the conversion for the library) is held and not pre-empted.</summary>
|
||||||
|
public bool BackgroundRunning
|
||||||
|
{
|
||||||
|
get
|
||||||
|
{
|
||||||
|
lock (_lock)
|
||||||
|
{
|
||||||
|
return _background is not null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Takes the gate for <paramref name="kind"/>. False, with <paramref name="busyWith"/> set, when another job (of any
|
/// Takes the gate for <paramref name="kind"/>. False, with <paramref name="busyWith"/> set, when another job (of any
|
||||||
/// kind, the same one included) holds it.
|
/// kind, the same one included) holds it in the foreground. A background lease is pre-empted: its token is
|
||||||
|
/// cancelled and, if it is committing a file, the commit is waited for (at most <see cref="CommitWait"/>; past it,
|
||||||
|
/// false with <see cref="LongWorkKind.LibraryConversion"/>).
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public bool TryEnter(LongWorkKind kind, [NotNullWhen(true)] out IDisposable? lease, out LongWorkKind? busyWith)
|
public bool TryEnter(LongWorkKind kind, [NotNullWhen(true)] out IDisposable? lease, out LongWorkKind? busyWith)
|
||||||
{
|
{
|
||||||
|
if (kind == LongWorkKind.LibraryConversion)
|
||||||
|
{
|
||||||
|
throw new ArgumentException("La conversione della libreria prende il cancello solo in sottofondo.", nameof(kind));
|
||||||
|
}
|
||||||
|
|
||||||
|
Lease taken;
|
||||||
|
BackgroundLease? preempted;
|
||||||
|
bool committing;
|
||||||
lock (_lock)
|
lock (_lock)
|
||||||
{
|
{
|
||||||
if (_holder is { } holder)
|
if (_holder is { } holder)
|
||||||
@@ -52,10 +93,47 @@ public sealed class LongWorkGate
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
var taken = new Lease(this, kind);
|
taken = new Lease(this, kind);
|
||||||
_holder = taken;
|
_holder = taken;
|
||||||
lease = taken;
|
preempted = _background;
|
||||||
busyWith = null;
|
_background = null;
|
||||||
|
committing = preempted?.MarkPreempted() ?? false;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (preempted is not null)
|
||||||
|
{
|
||||||
|
// Outside the lock: the token's callbacks run synchronously and may take the gate's lock.
|
||||||
|
preempted.CancelPreempted();
|
||||||
|
if (committing && !preempted.WaitForCommit(CommitWait))
|
||||||
|
{
|
||||||
|
taken.Dispose();
|
||||||
|
lease = null;
|
||||||
|
busyWith = LongWorkKind.LibraryConversion;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
lease = taken;
|
||||||
|
busyWith = null;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Takes the gate in the background for the conversion for the library. False while any foreground lease, or
|
||||||
|
/// another background lease, is held.
|
||||||
|
/// </summary>
|
||||||
|
public bool TryEnterBackground([NotNullWhen(true)] out BackgroundLease? lease)
|
||||||
|
{
|
||||||
|
lock (_lock)
|
||||||
|
{
|
||||||
|
if (_holder is not null || _background is not null)
|
||||||
|
{
|
||||||
|
lease = null;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
lease = new BackgroundLease(this);
|
||||||
|
_background = lease;
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -68,14 +146,20 @@ public sealed class LongWorkGate
|
|||||||
(LongWorkKind.Rebuild, LongWorkKind.Rebuild) => "La ricostruzione è già in corso.",
|
(LongWorkKind.Rebuild, LongWorkKind.Rebuild) => "La ricostruzione è già in corso.",
|
||||||
(_, LongWorkKind.Import) => $"C'è un'importazione al lavoro: aspetta che finisca o interrompila, poi {Verb(wanted)}.",
|
(_, LongWorkKind.Import) => $"C'è un'importazione al lavoro: aspetta che finisca o interrompila, poi {Verb(wanted)}.",
|
||||||
(_, LongWorkKind.Export) => $"C'è una copia nelle cartelle esterne al lavoro: aspetta che finisca o interrompila, poi {Verb(wanted)}.",
|
(_, LongWorkKind.Export) => $"C'è una copia nelle cartelle esterne al lavoro: aspetta che finisca o interrompila, poi {Verb(wanted)}.",
|
||||||
_ => "La ricostruzione del database è in corso: aspetta che finisca.",
|
(_, LongWorkKind.LibraryConversion) => "La conversione della libreria sta salvando un file: riprova fra un attimo.",
|
||||||
|
(_, LongWorkKind.FrameDownload) => $"Si sta preparando uno zip di fotogrammi: aspetta che finisca, poi {Verb(wanted)}.",
|
||||||
|
(_, LongWorkKind.Rebuild) => "La ricostruzione del database è in corso: aspetta che finisca.",
|
||||||
|
_ => "Un altro lavoro lungo è in corso: aspetta che finisca.",
|
||||||
};
|
};
|
||||||
|
|
||||||
private static string Verb(LongWorkKind kind) => kind switch
|
private static string Verb(LongWorkKind kind) => kind switch
|
||||||
{
|
{
|
||||||
LongWorkKind.Import => "importa",
|
LongWorkKind.Import => "importa",
|
||||||
LongWorkKind.Export => "copia",
|
LongWorkKind.Export => "copia",
|
||||||
_ => "ricostruisci",
|
LongWorkKind.Rebuild => "ricostruisci",
|
||||||
|
LongWorkKind.FrameDownload => "scarica i fotogrammi",
|
||||||
|
LongWorkKind.LibraryConversion => "converti",
|
||||||
|
_ => "riprova",
|
||||||
};
|
};
|
||||||
|
|
||||||
private void Release(Lease lease)
|
private void Release(Lease lease)
|
||||||
@@ -89,6 +173,17 @@ public sealed class LongWorkGate
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private void Release(BackgroundLease lease)
|
||||||
|
{
|
||||||
|
lock (_lock)
|
||||||
|
{
|
||||||
|
if (ReferenceEquals(_background, lease))
|
||||||
|
{
|
||||||
|
_background = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private sealed class Lease(LongWorkGate gate, LongWorkKind kind) : IDisposable
|
private sealed class Lease(LongWorkGate gate, LongWorkKind kind) : IDisposable
|
||||||
{
|
{
|
||||||
private int _disposed;
|
private int _disposed;
|
||||||
@@ -103,4 +198,112 @@ public sealed class LongWorkGate
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The background lease of the conversion for the library. <see cref="Preempted"/> is cancelled when a foreground
|
||||||
|
/// job wants the gate; a commit (<see cref="TryBeginCommit"/>) is waited for by that job, and none begins once
|
||||||
|
/// pre-empted or disposed.
|
||||||
|
/// </summary>
|
||||||
|
public sealed class BackgroundLease : IDisposable
|
||||||
|
{
|
||||||
|
private readonly LongWorkGate _gate;
|
||||||
|
|
||||||
|
// Neither is disposed: a foreground TryEnter may cancel or wait on them after the lease ended, and without a
|
||||||
|
// timer or a wait handle asked for they hold nothing but memory.
|
||||||
|
private readonly CancellationTokenSource _preempted = new();
|
||||||
|
private readonly ManualResetEventSlim _noCommit = new(initialState: true);
|
||||||
|
private bool _isPreempted;
|
||||||
|
private bool _committing;
|
||||||
|
private int _disposed;
|
||||||
|
|
||||||
|
internal BackgroundLease(LongWorkGate gate)
|
||||||
|
{
|
||||||
|
_gate = gate;
|
||||||
|
Preempted = _preempted.Token;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Cancelled when a foreground job takes the gate.</summary>
|
||||||
|
public CancellationToken Preempted { get; }
|
||||||
|
|
||||||
|
/// <summary>True once a foreground job asked for the gate (or the lease ended).</summary>
|
||||||
|
public bool IsPreempted
|
||||||
|
{
|
||||||
|
get
|
||||||
|
{
|
||||||
|
lock (_gate._lock)
|
||||||
|
{
|
||||||
|
return _isPreempted;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Begins a commit (a rename and its record) that a foreground job waits for. False once pre-empted or disposed,
|
||||||
|
/// or while another commit of this lease runs: then nothing may be renamed or recorded.
|
||||||
|
/// </summary>
|
||||||
|
public bool TryBeginCommit([NotNullWhen(true)] out IDisposable? commit)
|
||||||
|
{
|
||||||
|
lock (_gate._lock)
|
||||||
|
{
|
||||||
|
if (_isPreempted || _disposed != 0 || _committing)
|
||||||
|
{
|
||||||
|
commit = null;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
_committing = true;
|
||||||
|
_noCommit.Reset();
|
||||||
|
commit = new Commit(this);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Dispose()
|
||||||
|
{
|
||||||
|
if (Interlocked.Exchange(ref _disposed, 1) != 0)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
EndCommit();
|
||||||
|
_gate.Release(this);
|
||||||
|
lock (_gate._lock)
|
||||||
|
{
|
||||||
|
_isPreempted = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Under the gate's lock: marks the lease pre-empted and tells whether a commit is running.</summary>
|
||||||
|
internal bool MarkPreempted()
|
||||||
|
{
|
||||||
|
_isPreempted = true;
|
||||||
|
return _committing;
|
||||||
|
}
|
||||||
|
|
||||||
|
internal void CancelPreempted() => _preempted.Cancel();
|
||||||
|
|
||||||
|
internal bool WaitForCommit(TimeSpan timeout) => _noCommit.Wait(timeout);
|
||||||
|
|
||||||
|
private void EndCommit()
|
||||||
|
{
|
||||||
|
lock (_gate._lock)
|
||||||
|
{
|
||||||
|
_committing = false;
|
||||||
|
_noCommit.Set();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private sealed class Commit(BackgroundLease lease) : IDisposable
|
||||||
|
{
|
||||||
|
private int _disposed;
|
||||||
|
|
||||||
|
public void Dispose()
|
||||||
|
{
|
||||||
|
if (Interlocked.Exchange(ref _disposed, 1) == 0)
|
||||||
|
{
|
||||||
|
lease.EndCommit();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -6,6 +6,12 @@ namespace Febe.Core.Codecs.Containers;
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public static class ContainerReader
|
public static class ContainerReader
|
||||||
{
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// A «now» far in the future, for readers that must not depend on the clock (frames, remux): every plausible date
|
||||||
|
/// in the file is accepted.
|
||||||
|
/// </summary>
|
||||||
|
internal static readonly DateTimeOffset AnyDate = new(9000, 1, 1, 0, 0, 0, TimeSpan.Zero);
|
||||||
|
|
||||||
/// <summary>The largest sample read into memory: an 8K frame of H.264 at its highest level stays far below.</summary>
|
/// <summary>The largest sample read into memory: an 8K frame of H.264 at its highest level stays far below.</summary>
|
||||||
public const int MaxSampleSize = 64 * 1024 * 1024;
|
public const int MaxSampleSize = 64 * 1024 * 1024;
|
||||||
|
|
||||||
|
|||||||
@@ -39,6 +39,7 @@ public static class IsoBmffReader
|
|||||||
long position = 0;
|
long position = 0;
|
||||||
Span<byte> header = stackalloc byte[16];
|
Span<byte> header = stackalloc byte[16];
|
||||||
Movie? movie = null;
|
Movie? movie = null;
|
||||||
|
string? brand = null;
|
||||||
var pending = new List<(long Start, byte[] Body)>();
|
var pending = new List<(long Start, byte[] Body)>();
|
||||||
for (var i = 0; i < MaxTopLevelBoxes && position + 8 <= length; i++)
|
for (var i = 0; i < MaxTopLevelBoxes && position + 8 <= length; i++)
|
||||||
{
|
{
|
||||||
@@ -75,6 +76,12 @@ public static class IsoBmffReader
|
|||||||
}
|
}
|
||||||
|
|
||||||
var type = header.Slice(4, 4);
|
var type = header.Slice(4, 4);
|
||||||
|
if (type.SequenceEqual("ftyp"u8) && brand is null && size - headerSize >= 4)
|
||||||
|
{
|
||||||
|
stream.ReadExactly(header[..4]); // the size field is read already: its bytes can hold the brand
|
||||||
|
brand = System.Text.Encoding.Latin1.GetString(header[..4]);
|
||||||
|
}
|
||||||
|
|
||||||
if (type.SequenceEqual("moov"u8) && movie is null)
|
if (type.SequenceEqual("moov"u8) && movie is null)
|
||||||
{
|
{
|
||||||
movie = ParseMoov(ReadBody(stream, position + headerSize, size - headerSize), now, samples, length);
|
movie = ParseMoov(ReadBody(stream, position + headerSize, size - headerSize), now, samples, length);
|
||||||
@@ -112,7 +119,7 @@ public static class IsoBmffReader
|
|||||||
throw new ContainerException("Manca il box moov.");
|
throw new ContainerException("Manca il box moov.");
|
||||||
}
|
}
|
||||||
|
|
||||||
return movie.Build();
|
return movie.Build(brand);
|
||||||
}
|
}
|
||||||
|
|
||||||
private static byte[] ReadBody(Stream stream, long offset, long count)
|
private static byte[] ReadBody(Stream stream, long offset, long count)
|
||||||
@@ -141,7 +148,11 @@ public static class IsoBmffReader
|
|||||||
case "mvhd":
|
case "mvhd":
|
||||||
movie.ParseMvhd(body, now);
|
movie.ParseMvhd(body, now);
|
||||||
break;
|
break;
|
||||||
|
case "udta" or "meta":
|
||||||
|
movie.HasUserData = true;
|
||||||
|
break;
|
||||||
case "trak":
|
case "trak":
|
||||||
|
movie.TrackCount++;
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
movie.ParseTrak(moov, start, count);
|
movie.ParseTrak(moov, start, count);
|
||||||
@@ -269,6 +280,12 @@ public static class IsoBmffReader
|
|||||||
internal byte[]? Hvcc;
|
internal byte[]? Hvcc;
|
||||||
internal byte[]? Asc;
|
internal byte[]? Asc;
|
||||||
internal long EditOffset;
|
internal long EditOffset;
|
||||||
|
internal bool HasEdits;
|
||||||
|
internal long EmptyEditMovie;
|
||||||
|
internal long EditSegmentMovie;
|
||||||
|
internal int EditCount;
|
||||||
|
internal string? Language;
|
||||||
|
internal int ObjectType;
|
||||||
internal List<MediaSample> Samples = [];
|
internal List<MediaSample> Samples = [];
|
||||||
internal long FragmentTime = -1;
|
internal long FragmentTime = -1;
|
||||||
}
|
}
|
||||||
@@ -279,6 +296,7 @@ public static class IsoBmffReader
|
|||||||
internal readonly Dictionary<uint, (uint Duration, uint Size, uint Flags)> TrackDefaults = [];
|
internal readonly Dictionary<uint, (uint Duration, uint Size, uint Flags)> TrackDefaults = [];
|
||||||
private readonly List<Track> tracks = [];
|
private readonly List<Track> tracks = [];
|
||||||
private DateTimeOffset? created;
|
private DateTimeOffset? created;
|
||||||
|
private DateTimeOffset? modified;
|
||||||
private long timescale;
|
private long timescale;
|
||||||
private long duration;
|
private long duration;
|
||||||
|
|
||||||
@@ -288,6 +306,12 @@ public static class IsoBmffReader
|
|||||||
/// <summary>fragment_duration of the <c>mehd</c> box, in movie units; 0 when absent.</summary>
|
/// <summary>fragment_duration of the <c>mehd</c> box, in movie units; 0 when absent.</summary>
|
||||||
internal long FragmentDuration;
|
internal long FragmentDuration;
|
||||||
|
|
||||||
|
/// <summary>The <c>trak</c> boxes of the movie, of every kind.</summary>
|
||||||
|
internal int TrackCount;
|
||||||
|
|
||||||
|
/// <summary>True when the movie has a <c>udta</c> or <c>meta</c> box.</summary>
|
||||||
|
internal bool HasUserData;
|
||||||
|
|
||||||
/// <summary>A fragmented movie whose headers give no duration: only its fragments tell it.</summary>
|
/// <summary>A fragmented movie whose headers give no duration: only its fragments tell it.</summary>
|
||||||
internal bool NeedsFragmentsForDuration =>
|
internal bool NeedsFragmentsForDuration =>
|
||||||
Fragmented && duration <= 0 && FragmentDuration <= 0 && !tracks.Exists(t => t.Handler == "vide" && t.Duration > 0);
|
Fragmented && duration <= 0 && FragmentDuration <= 0 && !tracks.Exists(t => t.Handler == "vide" && t.Duration > 0);
|
||||||
@@ -295,15 +319,18 @@ public static class IsoBmffReader
|
|||||||
internal void ParseMvhd(ReadOnlySpan<byte> body, DateTimeOffset now)
|
internal void ParseMvhd(ReadOnlySpan<byte> body, DateTimeOffset now)
|
||||||
{
|
{
|
||||||
ulong creation;
|
ulong creation;
|
||||||
|
ulong modification;
|
||||||
if (body[0] == 1)
|
if (body[0] == 1)
|
||||||
{
|
{
|
||||||
creation = BinaryPrimitives.ReadUInt64BigEndian(body[4..]);
|
creation = BinaryPrimitives.ReadUInt64BigEndian(body[4..]);
|
||||||
|
modification = BinaryPrimitives.ReadUInt64BigEndian(body[12..]);
|
||||||
timescale = BinaryPrimitives.ReadUInt32BigEndian(body[20..]);
|
timescale = BinaryPrimitives.ReadUInt32BigEndian(body[20..]);
|
||||||
duration = (long)Math.Min(BinaryPrimitives.ReadUInt64BigEndian(body[24..]), long.MaxValue);
|
duration = (long)Math.Min(BinaryPrimitives.ReadUInt64BigEndian(body[24..]), long.MaxValue);
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
creation = BinaryPrimitives.ReadUInt32BigEndian(body[4..]);
|
creation = BinaryPrimitives.ReadUInt32BigEndian(body[4..]);
|
||||||
|
modification = BinaryPrimitives.ReadUInt32BigEndian(body[8..]);
|
||||||
timescale = BinaryPrimitives.ReadUInt32BigEndian(body[12..]);
|
timescale = BinaryPrimitives.ReadUInt32BigEndian(body[12..]);
|
||||||
duration = BinaryPrimitives.ReadUInt32BigEndian(body[16..]);
|
duration = BinaryPrimitives.ReadUInt32BigEndian(body[16..]);
|
||||||
if (duration == uint.MaxValue)
|
if (duration == uint.MaxValue)
|
||||||
@@ -312,14 +339,22 @@ public static class IsoBmffReader
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (creation > 0 && creation < 400UL * 366 * 86400)
|
created = Plausible(creation, now);
|
||||||
|
modified = Plausible(modification, now);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static DateTimeOffset? Plausible(ulong seconds, DateTimeOffset now)
|
||||||
|
{
|
||||||
|
if (seconds > 0 && seconds < 400UL * 366 * 86400)
|
||||||
{
|
{
|
||||||
var instant = Epoch1904.AddSeconds(creation);
|
var instant = Epoch1904.AddSeconds(seconds);
|
||||||
if (instant >= Earliest && instant <= now.AddDays(1))
|
if (instant >= Earliest && instant <= now.AddDays(1))
|
||||||
{
|
{
|
||||||
created = instant;
|
return instant;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
internal void ParseTrak(byte[] data, int start, int count)
|
internal void ParseTrak(byte[] data, int start, int count)
|
||||||
@@ -365,15 +400,34 @@ public static class IsoBmffReader
|
|||||||
var v1 = body[0] == 1;
|
var v1 = body[0] == 1;
|
||||||
var entries = BinaryPrimitives.ReadUInt32BigEndian(body[4..]);
|
var entries = BinaryPrimitives.ReadUInt32BigEndian(body[4..]);
|
||||||
var offset = 8;
|
var offset = 8;
|
||||||
|
var leading = true;
|
||||||
for (var i = 0; i < entries && i < 16; i++)
|
for (var i = 0; i < entries && i < 16; i++)
|
||||||
{
|
{
|
||||||
|
var segment = v1 ? (long)Math.Min(BinaryPrimitives.ReadUInt64BigEndian(body[offset..]), long.MaxValue / 4) : BinaryPrimitives.ReadUInt32BigEndian(body[offset..]);
|
||||||
long mediaTime = v1 ? BinaryPrimitives.ReadInt64BigEndian(body[(offset + 8)..]) : BinaryPrimitives.ReadInt32BigEndian(body[(offset + 4)..]);
|
long mediaTime = v1 ? BinaryPrimitives.ReadInt64BigEndian(body[(offset + 8)..]) : BinaryPrimitives.ReadInt32BigEndian(body[(offset + 4)..]);
|
||||||
|
var rate = BinaryPrimitives.ReadInt16BigEndian(body[(offset + (v1 ? 16 : 8))..]);
|
||||||
offset += v1 ? 20 : 12;
|
offset += v1 ? 20 : 12;
|
||||||
if (mediaTime >= 0)
|
if (leading && mediaTime < 0)
|
||||||
{
|
{
|
||||||
track.EditOffset = mediaTime; // the first non-empty edit: media time shown at presentation zero
|
track.EmptyEditMovie += segment; // a delayed start
|
||||||
return;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (leading)
|
||||||
|
{
|
||||||
|
leading = false;
|
||||||
|
track.HasEdits = true;
|
||||||
|
track.EditOffset = mediaTime; // the first non-empty edit: media time shown at presentation zero
|
||||||
|
track.EditSegmentMovie = segment; // and how long it is shown (movie units; 0: to the end)
|
||||||
|
}
|
||||||
|
|
||||||
|
// A rate other than 1 (a slowed or still segment) is not an ordinary edit either.
|
||||||
|
track.EditCount += rate == 1 ? 1 : 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (entries > 16)
|
||||||
|
{
|
||||||
|
track.EditCount += 2;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -397,6 +451,7 @@ public static class IsoBmffReader
|
|||||||
track.Duration = d == uint.MaxValue ? 0 : d;
|
track.Duration = d == uint.MaxValue ? 0 : d;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
track.Language = Language(body[0] == 1 ? body[32..] : body[20..]);
|
||||||
break;
|
break;
|
||||||
case "hdlr":
|
case "hdlr":
|
||||||
track.Handler = System.Text.Encoding.Latin1.GetString(body.Slice(8, 4));
|
track.Handler = System.Text.Encoding.Latin1.GetString(body.Slice(8, 4));
|
||||||
@@ -478,6 +533,39 @@ public static class IsoBmffReader
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The ISO 639-2/T code packed in an <c>mdhd</c> (three letters of five bits each); null for «und», for a
|
||||||
|
/// QuickTime Macintosh language code (below 0x400) or for a damaged value.
|
||||||
|
/// </summary>
|
||||||
|
private static string? Language(ReadOnlySpan<byte> field)
|
||||||
|
{
|
||||||
|
if (field.Length < 2)
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
var packed = BinaryPrimitives.ReadUInt16BigEndian(field) & 0x7FFF;
|
||||||
|
if (packed < 0x400)
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
Span<char> code = stackalloc char[3];
|
||||||
|
for (var i = 0; i < 3; i++)
|
||||||
|
{
|
||||||
|
var letter = (packed >> (10 - (5 * i))) & 0x1F;
|
||||||
|
if (letter is < 1 or > 26)
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
code[i] = (char)('a' + letter - 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
var text = new string(code);
|
||||||
|
return text == "und" ? null : text;
|
||||||
|
}
|
||||||
|
|
||||||
private static void ParseStsd(byte[] data, int start, int count, Track track)
|
private static void ParseStsd(byte[] data, int start, int count, Track track)
|
||||||
{
|
{
|
||||||
if (count < 16)
|
if (count < 16)
|
||||||
@@ -524,16 +612,31 @@ public static class IsoBmffReader
|
|||||||
{
|
{
|
||||||
if (t == "esds")
|
if (t == "esds")
|
||||||
{
|
{
|
||||||
track.Asc = EsdsConfig(data.AsSpan(s, c));
|
(track.ObjectType, track.Asc) = EsdsConfig(data.AsSpan(s, c));
|
||||||
|
}
|
||||||
|
else if (t == "wave" && track.ObjectType == 0)
|
||||||
|
{
|
||||||
|
// QuickTime keeps the esds of an mp4a entry inside a wave box (QTFF, sound sample description).
|
||||||
|
foreach (var (wt, ws, wc) in Children(data, s, c))
|
||||||
|
{
|
||||||
|
if (wt == "esds")
|
||||||
|
{
|
||||||
|
(track.ObjectType, track.Asc) = EsdsConfig(data.AsSpan(ws, wc));
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>The DecoderSpecificInfo of an <c>esds</c> box (ISO/IEC 14496-1 descriptors).</summary>
|
/// <summary>
|
||||||
private static byte[]? EsdsConfig(ReadOnlySpan<byte> body)
|
/// The objectTypeIndication (0 when absent) and the DecoderSpecificInfo of an <c>esds</c> box (ISO/IEC 14496-1
|
||||||
|
/// descriptors).
|
||||||
|
/// </summary>
|
||||||
|
private static (int ObjectType, byte[]? Config) EsdsConfig(ReadOnlySpan<byte> body)
|
||||||
{
|
{
|
||||||
|
var objectType = 0;
|
||||||
var p = 4; // version and flags
|
var p = 4; // version and flags
|
||||||
while (p + 2 <= body.Length)
|
while (p + 2 <= body.Length)
|
||||||
{
|
{
|
||||||
@@ -555,7 +658,7 @@ public static class IsoBmffReader
|
|||||||
{
|
{
|
||||||
if (p + 3 > body.Length)
|
if (p + 3 > body.Length)
|
||||||
{
|
{
|
||||||
return null;
|
return (objectType, null);
|
||||||
}
|
}
|
||||||
|
|
||||||
var flags = body[p + 2];
|
var flags = body[p + 2];
|
||||||
@@ -569,7 +672,7 @@ public static class IsoBmffReader
|
|||||||
{
|
{
|
||||||
if (p >= body.Length)
|
if (p >= body.Length)
|
||||||
{
|
{
|
||||||
return null;
|
return (objectType, null);
|
||||||
}
|
}
|
||||||
|
|
||||||
p += 1 + body[p];
|
p += 1 + body[p];
|
||||||
@@ -583,18 +686,23 @@ public static class IsoBmffReader
|
|||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
case 0x04: // DecoderConfigDescriptor: its fixed fields, then the children
|
case 0x04: // DecoderConfigDescriptor: objectTypeIndication and the other fixed fields, then the children
|
||||||
|
if (p < body.Length)
|
||||||
|
{
|
||||||
|
objectType = body[p];
|
||||||
|
}
|
||||||
|
|
||||||
p += 13;
|
p += 13;
|
||||||
break;
|
break;
|
||||||
case 0x05:
|
case 0x05:
|
||||||
return p + length <= body.Length ? body.Slice(p, length).ToArray() : null;
|
return (objectType, p + length <= body.Length ? body.Slice(p, length).ToArray() : null);
|
||||||
default:
|
default:
|
||||||
p += length;
|
p += length;
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return null;
|
return (objectType, null);
|
||||||
}
|
}
|
||||||
|
|
||||||
private void BuildSamples(Track track, byte[] stts, byte[]? ctts, byte[] stsc, byte[] stsz, bool stz2, byte[] stco, bool co64, byte[]? stss)
|
private void BuildSamples(Track track, byte[] stts, byte[]? ctts, byte[] stsc, byte[] stsz, bool stz2, byte[] stco, bool co64, byte[]? stss)
|
||||||
@@ -903,7 +1011,7 @@ public static class IsoBmffReader
|
|||||||
return total;
|
return total;
|
||||||
}
|
}
|
||||||
|
|
||||||
internal MediaContainer Build()
|
internal MediaContainer Build(string? brand)
|
||||||
{
|
{
|
||||||
var video = tracks.Find(t => t.Handler == "vide");
|
var video = tracks.Find(t => t.Handler == "vide");
|
||||||
var audio = tracks.Find(t => t.Handler == "soun");
|
var audio = tracks.Find(t => t.Handler == "soun");
|
||||||
@@ -932,6 +1040,11 @@ public static class IsoBmffReader
|
|||||||
AvcConfiguration = video.Avcc,
|
AvcConfiguration = video.Avcc,
|
||||||
HevcConfiguration = video.Hvcc,
|
HevcConfiguration = video.Hvcc,
|
||||||
Samples = video.Samples,
|
Samples = video.Samples,
|
||||||
|
EditMediaTime = video.HasEdits ? video.EditOffset : null,
|
||||||
|
EmptyEditDuration = EmptyEdit(video),
|
||||||
|
EditSegmentDuration = EditSegment(video),
|
||||||
|
EditCount = video.EditCount,
|
||||||
|
Language = video.Language,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -942,6 +1055,8 @@ public static class IsoBmffReader
|
|||||||
{
|
{
|
||||||
Codec = audio.Format switch
|
Codec = audio.Format switch
|
||||||
{
|
{
|
||||||
|
// objectTypeIndication 0x69 and 0x6B are MPEG-1/2 audio (MP3) in an mp4a entry (ISO/IEC 14496-1 Table 5).
|
||||||
|
"mp4a" when audio.ObjectType is 0x69 or 0x6B => AudioCodec.Mp3,
|
||||||
"mp4a" => AudioCodec.Aac,
|
"mp4a" => AudioCodec.Aac,
|
||||||
".mp3" => AudioCodec.Mp3,
|
".mp3" => AudioCodec.Mp3,
|
||||||
"Opus" => AudioCodec.Opus,
|
"Opus" => AudioCodec.Opus,
|
||||||
@@ -951,10 +1066,16 @@ public static class IsoBmffReader
|
|||||||
CodecTag = audio.Format,
|
CodecTag = audio.Format,
|
||||||
Channels = audio.Channels,
|
Channels = audio.Channels,
|
||||||
SampleRate = audio.SampleRate,
|
SampleRate = audio.SampleRate,
|
||||||
AacConfiguration = audio.Asc,
|
AacConfiguration = audio.ObjectType is 0x69 or 0x6B ? null : audio.Asc,
|
||||||
|
AudioObjectType = audio.ObjectType is 0x69 or 0x6B ? null : AudioTrack.ObjectTypeOf(audio.Asc),
|
||||||
Timescale = audio.Timescale > 0 ? audio.Timescale : 1,
|
Timescale = audio.Timescale > 0 ? audio.Timescale : 1,
|
||||||
Duration = DurationOf(audio),
|
Duration = DurationOf(audio),
|
||||||
Samples = audio.Samples,
|
Samples = audio.Samples,
|
||||||
|
EditMediaTime = audio.HasEdits ? audio.EditOffset : null,
|
||||||
|
EmptyEditDuration = EmptyEdit(audio),
|
||||||
|
EditSegmentDuration = EditSegment(audio),
|
||||||
|
EditCount = audio.EditCount,
|
||||||
|
Language = audio.Language,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -965,7 +1086,45 @@ public static class IsoBmffReader
|
|||||||
total = Seconds(v.Seconds(v.Duration));
|
total = Seconds(v.Seconds(v.Duration));
|
||||||
}
|
}
|
||||||
|
|
||||||
return new MediaContainer { Format = ContainerFormat.IsoBmff, CreatedAt = created, Duration = total, Video = v, Audio = a };
|
return new MediaContainer
|
||||||
|
{
|
||||||
|
Format = ContainerFormat.IsoBmff,
|
||||||
|
CreatedAt = created,
|
||||||
|
ModifiedAt = modified,
|
||||||
|
MajorBrand = brand,
|
||||||
|
TrackCount = TrackCount,
|
||||||
|
HasUserData = HasUserData,
|
||||||
|
Duration = total,
|
||||||
|
Video = v,
|
||||||
|
Audio = a,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The segment of the first non-empty edit (movie units) in track units, rounded to the nearest; null when the
|
||||||
|
/// edit has none (0, as fragmented files write it) or the track has no edit list.
|
||||||
|
/// </summary>
|
||||||
|
private long? EditSegment(Track track)
|
||||||
|
{
|
||||||
|
if (!track.HasEdits || track.EditSegmentMovie <= 0 || timescale <= 0 || track.Timescale <= 0)
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
var value = (((Int128)track.EditSegmentMovie * track.Timescale) + (timescale / 2)) / timescale;
|
||||||
|
return value > long.MaxValue / 4 ? null : (long)value;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The leading empty edits of a track (movie units) in track units, rounded to the nearest.</summary>
|
||||||
|
private long EmptyEdit(Track track)
|
||||||
|
{
|
||||||
|
if (track.EmptyEditMovie <= 0 || timescale <= 0 || track.Timescale <= 0)
|
||||||
|
{
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
var value = (((Int128)track.EmptyEditMovie * track.Timescale) + (timescale / 2)) / timescale;
|
||||||
|
return value > long.MaxValue / 4 ? 0 : (long)value;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>A duration in seconds; null when it is beyond what a video can last (a damaged header).</summary>
|
/// <summary>A duration in seconds; null when it is beyond what a video can last (a damaged header).</summary>
|
||||||
|
|||||||
@@ -107,6 +107,9 @@ public static class MatroskaReader
|
|||||||
case TracksId:
|
case TracksId:
|
||||||
ParseTracks(reader, bodyEnd, state);
|
ParseTracks(reader, bodyEnd, state);
|
||||||
break;
|
break;
|
||||||
|
case TagsId:
|
||||||
|
state.HasTags = true;
|
||||||
|
break;
|
||||||
case ClusterId:
|
case ClusterId:
|
||||||
if (!samples)
|
if (!samples)
|
||||||
{
|
{
|
||||||
@@ -214,6 +217,13 @@ public static class MatroskaReader
|
|||||||
case 0x23E383:
|
case 0x23E383:
|
||||||
track.DefaultDuration = (long)reader.Unsigned(tsize);
|
track.DefaultDuration = (long)reader.Unsigned(tsize);
|
||||||
break;
|
break;
|
||||||
|
case 0x22B59C:
|
||||||
|
track.Language = reader.String(tsize);
|
||||||
|
break;
|
||||||
|
case 0x6D80: // ContentEncodings: the frames are compressed, stripped or encrypted
|
||||||
|
track.Encoded = true;
|
||||||
|
reader.Skip(tsize);
|
||||||
|
break;
|
||||||
case 0x55EE: // MaxBlockAdditionID, and others: ignored
|
case 0x55EE: // MaxBlockAdditionID, and others: ignored
|
||||||
reader.Skip(tsize);
|
reader.Skip(tsize);
|
||||||
break;
|
break;
|
||||||
@@ -289,6 +299,7 @@ public static class MatroskaReader
|
|||||||
}
|
}
|
||||||
|
|
||||||
stream.Position = Math.Min(entryEnd, stream.Length);
|
stream.Position = Math.Min(entryEnd, stream.Length);
|
||||||
|
state.TrackCount++;
|
||||||
if (track.Type == 1 && state.Video is null)
|
if (track.Type == 1 && state.Video is null)
|
||||||
{
|
{
|
||||||
state.Video = track;
|
state.Video = track;
|
||||||
@@ -498,6 +509,8 @@ public static class MatroskaReader
|
|||||||
internal double Roll;
|
internal double Roll;
|
||||||
internal int SampleRate;
|
internal int SampleRate;
|
||||||
internal int Channels;
|
internal int Channels;
|
||||||
|
internal string? Language;
|
||||||
|
internal bool Encoded;
|
||||||
internal readonly List<MediaSample> Samples = [];
|
internal readonly List<MediaSample> Samples = [];
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -509,6 +522,12 @@ public static class MatroskaReader
|
|||||||
internal TrackEntry? Video;
|
internal TrackEntry? Video;
|
||||||
internal TrackEntry? Audio;
|
internal TrackEntry? Audio;
|
||||||
|
|
||||||
|
/// <summary>Every TrackEntry of the file.</summary>
|
||||||
|
internal int TrackCount;
|
||||||
|
|
||||||
|
/// <summary>True when the segment has a Tags element.</summary>
|
||||||
|
internal bool HasTags;
|
||||||
|
|
||||||
/// <summary>Nanoseconds of one unit of the sample times; fixed by the first block, 0 before.</summary>
|
/// <summary>Nanoseconds of one unit of the sample times; fixed by the first block, 0 before.</summary>
|
||||||
private long unit;
|
private long unit;
|
||||||
|
|
||||||
@@ -599,12 +618,15 @@ public static class MatroskaReader
|
|||||||
Timescale = timescale,
|
Timescale = timescale,
|
||||||
Duration = trackUnits,
|
Duration = trackUnits,
|
||||||
Samples = samples,
|
Samples = samples,
|
||||||
|
Language = Language(v.Language),
|
||||||
|
Encoded = v.Encoded,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
AudioTrack? audio = null;
|
AudioTrack? audio = null;
|
||||||
if (Audio is { } a)
|
if (Audio is { } a)
|
||||||
{
|
{
|
||||||
|
var asc = a.CodecId == "A_AAC" ? a.CodecPrivate : a.CodecId.StartsWith("A_AAC/", StringComparison.Ordinal) ? LegacyAacConfig(a) : null;
|
||||||
audio = new AudioTrack
|
audio = new AudioTrack
|
||||||
{
|
{
|
||||||
Codec = a.CodecId switch
|
Codec = a.CodecId switch
|
||||||
@@ -619,16 +641,91 @@ public static class MatroskaReader
|
|||||||
CodecTag = a.CodecId,
|
CodecTag = a.CodecId,
|
||||||
SampleRate = a.SampleRate,
|
SampleRate = a.SampleRate,
|
||||||
Channels = a.Channels,
|
Channels = a.Channels,
|
||||||
AacConfiguration = a.CodecId == "A_AAC" ? a.CodecPrivate : null,
|
AacConfiguration = asc,
|
||||||
|
AudioObjectType = AudioTrack.ObjectTypeOf(asc),
|
||||||
Timescale = timescale,
|
Timescale = timescale,
|
||||||
Duration = trackUnits,
|
Duration = trackUnits,
|
||||||
Samples = a.Samples,
|
Samples = a.Samples,
|
||||||
|
Language = Language(a.Language),
|
||||||
|
Encoded = a.Encoded,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
var seconds = DurationTicks * TimecodeScale / 1e9;
|
var seconds = DurationTicks * TimecodeScale / 1e9;
|
||||||
TimeSpan? duration = seconds is > 0 and < 1e9 ? TimeSpan.FromSeconds(seconds) : null;
|
TimeSpan? duration = seconds is > 0 and < 1e9 ? TimeSpan.FromSeconds(seconds) : null;
|
||||||
return new MediaContainer { Format = ContainerFormat.Matroska, CreatedAt = Created, Duration = duration, Video = video, Audio = audio };
|
return new MediaContainer
|
||||||
|
{
|
||||||
|
Format = ContainerFormat.Matroska,
|
||||||
|
CreatedAt = Created,
|
||||||
|
Duration = duration,
|
||||||
|
Video = video,
|
||||||
|
Audio = audio,
|
||||||
|
TrackCount = TrackCount,
|
||||||
|
HasUserData = HasTags,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>A three-letter ISO 639-2 language; null for «und», absent or malformed.</summary>
|
||||||
|
private static string? Language(string? code) =>
|
||||||
|
code is { Length: 3 } && code != "und" && code.All(char.IsAsciiLetterLower) ? code : null;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The AudioSpecificConfig (ISO/IEC 14496-3 §1.6.2.1) of a track with an old codec ID that names the profile
|
||||||
|
/// («A_AAC/MPEG4/LC», «A_AAC/MPEG2/MAIN», «…/SBR»...) instead of carrying the configuration in CodecPrivate:
|
||||||
|
/// object type, sampling frequency index (or the explicit frequency), channel configuration, then a
|
||||||
|
/// GASpecificConfig of zeros (1024-sample frames, no core coder, no extension).
|
||||||
|
/// </summary>
|
||||||
|
private static byte[]? LegacyAacConfig(TrackEntry track)
|
||||||
|
{
|
||||||
|
if (track.CodecPrivate is { Length: >= 2 })
|
||||||
|
{
|
||||||
|
return track.CodecPrivate;
|
||||||
|
}
|
||||||
|
|
||||||
|
var profile = track.CodecId[(track.CodecId.LastIndexOf('/') + 1)..];
|
||||||
|
var objectType = profile switch
|
||||||
|
{
|
||||||
|
"MAIN" => 1,
|
||||||
|
"LC" or "SBR" => 2, // SBR is signalled implicitly: the core rate in SamplingFrequency
|
||||||
|
"SSR" => 3,
|
||||||
|
"LTP" => 4,
|
||||||
|
_ => 0,
|
||||||
|
};
|
||||||
|
if (objectType == 0 || track.SampleRate <= 0 || track.Channels is < 1 or > 7)
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
int[] rates = [96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350];
|
||||||
|
var index = Array.IndexOf(rates, track.SampleRate);
|
||||||
|
var bits = new List<(int Value, int Count)> { (objectType, 5) };
|
||||||
|
if (index >= 0)
|
||||||
|
{
|
||||||
|
bits.Add((index, 4));
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
bits.Add((15, 4));
|
||||||
|
bits.Add((track.SampleRate & 0xFFFFFF, 24));
|
||||||
|
}
|
||||||
|
|
||||||
|
bits.Add((track.Channels, 4));
|
||||||
|
bits.Add((0, 3));
|
||||||
|
var total = bits.Sum(b => b.Count);
|
||||||
|
var config = new byte[(total + 7) / 8];
|
||||||
|
var position = 0;
|
||||||
|
foreach (var (value, count) in bits)
|
||||||
|
{
|
||||||
|
for (var i = count - 1; i >= 0; i--, position++)
|
||||||
|
{
|
||||||
|
if (((value >> i) & 1) != 0)
|
||||||
|
{
|
||||||
|
config[position / 8] |= (byte)(0x80 >> (position % 8));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return config;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -94,6 +94,38 @@ public abstract class MediaTrack
|
|||||||
/// <summary>The four-character code or codec identifier of the container, for messages.</summary>
|
/// <summary>The four-character code or codec identifier of the container, for messages.</summary>
|
||||||
public string CodecTag { get; init; } = string.Empty;
|
public string CodecTag { get; init; } = string.Empty;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The media time (track units) shown at the start of the presentation, from the first non-empty edit of an ISO edit
|
||||||
|
/// list; null when the track has no edit list (Matroska never has one). The reader's presentation times already
|
||||||
|
/// have it subtracted.
|
||||||
|
/// </summary>
|
||||||
|
public long? EditMediaTime { get; init; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The empty edits before the first non-empty one (a delayed start), in track units; 0 when none. A sample is shown
|
||||||
|
/// at its <see cref="MediaSample.PresentationTime"/> plus this.
|
||||||
|
/// </summary>
|
||||||
|
public long EmptyEditDuration { get; init; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// How long the first non-empty edit shows the media from <see cref="EditMediaTime"/>, in track units; null when the
|
||||||
|
/// edit runs to the end of the media (no segment written) or there is no edit list. Shorter than the media after
|
||||||
|
/// <see cref="EditMediaTime"/>: the end of the media is hidden (a trim, the padding of AAC).
|
||||||
|
/// </summary>
|
||||||
|
public long? EditSegmentDuration { get; init; }
|
||||||
|
|
||||||
|
/// <summary>The edits of the edit list after the leading empty ones (1 for an ordinary one, 0 without edit list).</summary>
|
||||||
|
public int EditCount { get; init; }
|
||||||
|
|
||||||
|
/// <summary>The language of the track as an ISO 639-2 code («ita», «eng»); null when unknown or undetermined.</summary>
|
||||||
|
public string? Language { get; init; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// True when the frames of the track are stored transformed (Matroska ContentEncodings: compression, header
|
||||||
|
/// stripping, encryption): their bytes are not the codec's.
|
||||||
|
/// </summary>
|
||||||
|
public bool Encoded { get; init; }
|
||||||
|
|
||||||
/// <summary>Time in seconds of a value in track units.</summary>
|
/// <summary>Time in seconds of a value in track units.</summary>
|
||||||
public double Seconds(long ticks) => Timescale > 0 ? (double)ticks / Timescale : 0;
|
public double Seconds(long ticks) => Timescale > 0 ? (double)ticks / Timescale : 0;
|
||||||
}
|
}
|
||||||
@@ -143,6 +175,26 @@ public sealed class AudioTrack : MediaTrack
|
|||||||
|
|
||||||
/// <summary>The AudioSpecificConfig of an AAC track.</summary>
|
/// <summary>The AudioSpecificConfig of an AAC track.</summary>
|
||||||
public byte[]? AacConfiguration { get; init; }
|
public byte[]? AacConfiguration { get; init; }
|
||||||
|
|
||||||
|
/// <summary>The audio object type of an AAC track (ISO/IEC 14496-3: 2 is AAC LC, 5 SBR, 29 PS); null when unknown.</summary>
|
||||||
|
public int? AudioObjectType { get; init; }
|
||||||
|
|
||||||
|
/// <summary>The audio object type of an AudioSpecificConfig (5 bits, 31 escaping to 32 + 6 more).</summary>
|
||||||
|
internal static int? ObjectTypeOf(byte[]? asc)
|
||||||
|
{
|
||||||
|
if (asc is not { Length: > 0 })
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
var type = asc[0] >> 3;
|
||||||
|
if (type == 31)
|
||||||
|
{
|
||||||
|
return asc.Length > 1 ? 32 + (((asc[0] & 7) << 3) | (asc[1] >> 5)) : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return type == 0 ? null : type;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>What a container says: its creation time, duration and first video and audio tracks.</summary>
|
/// <summary>What a container says: its creation time, duration and first video and audio tracks.</summary>
|
||||||
@@ -153,6 +205,21 @@ public sealed class MediaContainer
|
|||||||
/// <summary>Creation time written in the container, when plausible.</summary>
|
/// <summary>Creation time written in the container, when plausible.</summary>
|
||||||
public DateTimeOffset? CreatedAt { get; init; }
|
public DateTimeOffset? CreatedAt { get; init; }
|
||||||
|
|
||||||
|
/// <summary>Modification time written in the container (ISO <c>mvhd</c>), when plausible.</summary>
|
||||||
|
public DateTimeOffset? ModifiedAt { get; init; }
|
||||||
|
|
||||||
|
/// <summary>The major brand of an ISO file («isom», «qt », «M4V », «3gp4»...), null for other containers or without <c>ftyp</c>.</summary>
|
||||||
|
public string? MajorBrand { get; init; }
|
||||||
|
|
||||||
|
/// <summary>Tracks of every kind in the file (video, audio, timecode, subtitles...), of which only the first video and audio are read.</summary>
|
||||||
|
public int TrackCount { get; init; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// True when the file has metadata of its own that the readers do not interpret (ISO <c>udta</c> or <c>meta</c>
|
||||||
|
/// boxes, Matroska tags): a remux does not carry it.
|
||||||
|
/// </summary>
|
||||||
|
public bool HasUserData { get; init; }
|
||||||
|
|
||||||
/// <summary>Duration of the whole presentation.</summary>
|
/// <summary>Duration of the whole presentation.</summary>
|
||||||
public TimeSpan? Duration { get; init; }
|
public TimeSpan? Duration { get; init; }
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,337 @@
|
|||||||
|
namespace Febe.Core.Codecs.Containers;
|
||||||
|
|
||||||
|
/// <summary>Why a video cannot be brought into MP4 without re-encoding it (tappa E3: then it is copied as it is).</summary>
|
||||||
|
public enum RemuxRefusal
|
||||||
|
{
|
||||||
|
/// <summary>It can.</summary>
|
||||||
|
None,
|
||||||
|
|
||||||
|
/// <summary>Not a video Febe recognises, or a file without a video track.</summary>
|
||||||
|
NotAVideo,
|
||||||
|
|
||||||
|
/// <summary>Already an MP4 (an ISO file with an <c>.mp4</c> name and a brand other than QuickTime's): copied byte for byte.</summary>
|
||||||
|
AlreadyMp4,
|
||||||
|
|
||||||
|
/// <summary>A container whose frames MP4 cannot take as they are (AVI, ASF, FLV, MPEG-PS, Annex B streams).</summary>
|
||||||
|
ContainerNotRemuxable,
|
||||||
|
|
||||||
|
/// <summary>A video codec other than H.264 and HEVC.</summary>
|
||||||
|
VideoCodec,
|
||||||
|
|
||||||
|
/// <summary>An audio codec other than AAC and MP3.</summary>
|
||||||
|
AudioCodec,
|
||||||
|
|
||||||
|
/// <summary>A track without the configuration record of its codec.</summary>
|
||||||
|
MissingConfiguration,
|
||||||
|
|
||||||
|
/// <summary>A Matroska track whose frames are stored transformed (ContentEncodings).</summary>
|
||||||
|
EncodedTrack,
|
||||||
|
|
||||||
|
/// <summary>A track with more than one edit (a cut or a still segment), which the writer does not reproduce.</summary>
|
||||||
|
EditList,
|
||||||
|
|
||||||
|
/// <summary>A video track without samples.</summary>
|
||||||
|
NoSamples,
|
||||||
|
|
||||||
|
/// <summary>A damaged or truncated file.</summary>
|
||||||
|
Unreadable,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// A remux planned by <see cref="Mp4Remuxer.Check(Stream, string, out RemuxPlan, CancellationToken)"/>: the source as
|
||||||
|
/// read, the MP4 to write (its exact length is <see cref="OutputLength"/>) and the note codes of what it does not keep.
|
||||||
|
/// </summary>
|
||||||
|
public sealed record RemuxPlan(MediaContainer Source, Mp4Layout Layout, IReadOnlyList<string> Losses)
|
||||||
|
{
|
||||||
|
/// <summary>Bytes of the MP4 that <see cref="Mp4Remuxer.Write"/> writes.</summary>
|
||||||
|
public long OutputLength => Layout.Length;
|
||||||
|
|
||||||
|
/// <summary>The stream the sample writers of <see cref="Layout"/> read from, set by <see cref="Mp4Remuxer.Write"/>.</summary>
|
||||||
|
internal RemuxSource Reading { get; init; } = new();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Where the samples of a planned remux are read from while it is written.</summary>
|
||||||
|
internal sealed class RemuxSource
|
||||||
|
{
|
||||||
|
internal Stream? Stream { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Brings a MOV, M4V, 3GP or Matroska video into MP4 by copying its samples (tappa E3, «MOV → MP4 solo rimuxaggio»):
|
||||||
|
/// one H.264 or HEVC video track and at most one AAC or MP3 audio track, with their configuration records, sync
|
||||||
|
/// samples, composition offsets, edit (the delayed start and the hidden AAC priming), rotation, language and dates.
|
||||||
|
/// Nothing is re-encoded; anything that would need it is refused with its reason. Only the tables and the
|
||||||
|
/// <c>moov</c> are in memory: the samples are read and written one at a time, and the same source always gives the
|
||||||
|
/// same bytes (the reader's «now» is fixed).
|
||||||
|
/// </summary>
|
||||||
|
public static class Mp4Remuxer
|
||||||
|
{
|
||||||
|
/// <summary>Note code (with «:n») of the tracks left behind: timecode, subtitles, a second audio track...</summary>
|
||||||
|
public const string LostTracks = "LostTracks";
|
||||||
|
|
||||||
|
/// <summary>Note code of the metadata of the source the MP4 does not carry (ISO <c>udta</c>/<c>meta</c>, Matroska tags).</summary>
|
||||||
|
public const string LostVideoMetadata = "LostVideoMetadata";
|
||||||
|
|
||||||
|
/// <summary>Plans the remux of a seekable <paramref name="source"/> without knowing its name: never <see cref="RemuxRefusal.AlreadyMp4"/>.</summary>
|
||||||
|
public static RemuxRefusal Check(Stream source, out RemuxPlan? plan, CancellationToken ct) => Check(source, null, out plan, ct);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Plans the remux of a seekable <paramref name="source"/>; <paramref name="fileName"/> (or a path) tells an MP4
|
||||||
|
/// already (<see cref="RemuxRefusal.AlreadyMp4"/>). Never throws for a bad file.
|
||||||
|
/// </summary>
|
||||||
|
public static RemuxRefusal Check(Stream source, string? fileName, out RemuxPlan? plan, CancellationToken ct)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(source);
|
||||||
|
plan = null;
|
||||||
|
MediaContainer? container;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
container = ContainerReader.Read(source, ContainerReader.AnyDate, samples: true, ct);
|
||||||
|
}
|
||||||
|
catch (Exception ex) when (ex is ContainerException or EndOfStreamException or IOException or ArgumentException
|
||||||
|
or IndexOutOfRangeException or OverflowException or InvalidDataException)
|
||||||
|
{
|
||||||
|
return RemuxRefusal.Unreadable;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (container is null)
|
||||||
|
{
|
||||||
|
return RemuxRefusal.NotAVideo;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (container.Format is not (ContainerFormat.IsoBmff or ContainerFormat.Matroska))
|
||||||
|
{
|
||||||
|
return container.Video is null ? RemuxRefusal.NotAVideo : RemuxRefusal.ContainerNotRemuxable;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (container.Format == ContainerFormat.IsoBmff && container.MajorBrand != "qt "
|
||||||
|
&& string.Equals(Path.GetExtension(fileName ?? string.Empty), ".mp4", StringComparison.OrdinalIgnoreCase))
|
||||||
|
{
|
||||||
|
return RemuxRefusal.AlreadyMp4;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (container.Video is not { } video)
|
||||||
|
{
|
||||||
|
return RemuxRefusal.NotAVideo;
|
||||||
|
}
|
||||||
|
|
||||||
|
var audio = container.Audio is { Samples.Count: > 0 } a ? a : null;
|
||||||
|
var refusal = Refusal(video, audio);
|
||||||
|
if (refusal != RemuxRefusal.None)
|
||||||
|
{
|
||||||
|
return refusal;
|
||||||
|
}
|
||||||
|
|
||||||
|
var length = source.Length;
|
||||||
|
if (!InFile(video, length) || (audio is not null && !InFile(audio, length)))
|
||||||
|
{
|
||||||
|
return RemuxRefusal.Unreadable;
|
||||||
|
}
|
||||||
|
|
||||||
|
var reading = new RemuxSource();
|
||||||
|
var tracks = new List<Mp4OutputTrack> { VideoTrackOf(container, video, reading) };
|
||||||
|
if (audio is not null)
|
||||||
|
{
|
||||||
|
tracks.Add(AudioTrackOf(container, audio, reading));
|
||||||
|
}
|
||||||
|
|
||||||
|
Mp4Layout layout;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
layout = Mp4Writer.Prepare(tracks, new Mp4MovieInfo(container.CreatedAt, container.ModifiedAt));
|
||||||
|
}
|
||||||
|
catch (Exception ex) when (ex is ArgumentException or OverflowException)
|
||||||
|
{
|
||||||
|
return RemuxRefusal.Unreadable;
|
||||||
|
}
|
||||||
|
|
||||||
|
var losses = new List<string>();
|
||||||
|
var dropped = container.TrackCount - tracks.Count;
|
||||||
|
if (dropped > 0)
|
||||||
|
{
|
||||||
|
losses.Add(FormattableString.Invariant($"{LostTracks}:{dropped}"));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (container.HasUserData)
|
||||||
|
{
|
||||||
|
losses.Add(LostVideoMetadata);
|
||||||
|
}
|
||||||
|
|
||||||
|
plan = new RemuxPlan(container, layout, losses) { Reading = reading };
|
||||||
|
return RemuxRefusal.None;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Writes the MP4 of <paramref name="plan"/> into <paramref name="output"/>, reading the samples from
|
||||||
|
/// <paramref name="source"/> (the same file the plan was made from, seekable). <paramref name="ct"/> is checked
|
||||||
|
/// between samples.
|
||||||
|
/// </summary>
|
||||||
|
/// <exception cref="ContainerException">A sample lies outside the file (it changed since the plan).</exception>
|
||||||
|
public static void Write(RemuxPlan plan, Stream source, Stream output, CancellationToken ct)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(plan);
|
||||||
|
ArgumentNullException.ThrowIfNull(source);
|
||||||
|
ArgumentNullException.ThrowIfNull(output);
|
||||||
|
lock (plan.Reading)
|
||||||
|
{
|
||||||
|
plan.Reading.Stream = source;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
plan.Layout.WriteTo(output, ct);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
plan.Reading.Stream = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static RemuxRefusal Refusal(VideoTrack video, AudioTrack? audio)
|
||||||
|
{
|
||||||
|
if (video.Encoded || audio?.Encoded == true)
|
||||||
|
{
|
||||||
|
return RemuxRefusal.EncodedTrack;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (video.Codec is not (VideoCodec.H264 or VideoCodec.Hevc))
|
||||||
|
{
|
||||||
|
return RemuxRefusal.VideoCodec;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (video.AnnexB)
|
||||||
|
{
|
||||||
|
return RemuxRefusal.ContainerNotRemuxable;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ((video.Codec == VideoCodec.H264 ? video.AvcConfiguration : video.HevcConfiguration) is not { Length: > 0 })
|
||||||
|
{
|
||||||
|
return RemuxRefusal.MissingConfiguration;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (video.Samples.Count == 0)
|
||||||
|
{
|
||||||
|
return RemuxRefusal.NoSamples;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (video.EditCount > 1)
|
||||||
|
{
|
||||||
|
return RemuxRefusal.EditList;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (audio is null)
|
||||||
|
{
|
||||||
|
return RemuxRefusal.None;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (audio.Codec is not (AudioCodec.Aac or AudioCodec.Mp3))
|
||||||
|
{
|
||||||
|
return RemuxRefusal.AudioCodec;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (audio.Codec == AudioCodec.Aac && audio.AacConfiguration is not { Length: >= 2 })
|
||||||
|
{
|
||||||
|
return RemuxRefusal.MissingConfiguration;
|
||||||
|
}
|
||||||
|
|
||||||
|
return audio.EditCount > 1 ? RemuxRefusal.EditList : RemuxRefusal.None;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool InFile(MediaTrack track, long length)
|
||||||
|
{
|
||||||
|
foreach (var s in track.Samples)
|
||||||
|
{
|
||||||
|
if (s.Offset < 0 || s.Size < 0 || s.Size > ContainerReader.MaxSampleSize || s.Offset + s.Size > length)
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Mp4OutputTrack VideoTrackOf(MediaContainer container, VideoTrack video, RemuxSource reading)
|
||||||
|
{
|
||||||
|
var (samples, edit) = Times(container, video);
|
||||||
|
return new Mp4OutputTrack
|
||||||
|
{
|
||||||
|
IsVideo = true,
|
||||||
|
Timescale = video.Timescale,
|
||||||
|
Samples = samples,
|
||||||
|
WriteSample = Writer(video, reading),
|
||||||
|
Width = video.Width,
|
||||||
|
Height = video.Height,
|
||||||
|
Rotation = video.Rotation,
|
||||||
|
AvcConfiguration = video.Codec == VideoCodec.H264 ? video.AvcConfiguration : null,
|
||||||
|
HevcConfiguration = video.Codec == VideoCodec.Hevc ? video.HevcConfiguration : null,
|
||||||
|
SampleEntryType = container.Format == ContainerFormat.IsoBmff ? video.CodecTag : null,
|
||||||
|
Language = video.Language,
|
||||||
|
EditMediaTime = edit,
|
||||||
|
EmptyEditDuration = video.EmptyEditDuration,
|
||||||
|
EditSegmentDuration = video.EditSegmentDuration,
|
||||||
|
LastSampleDuration = LastDuration(video),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Mp4OutputTrack AudioTrackOf(MediaContainer container, AudioTrack audio, RemuxSource reading)
|
||||||
|
{
|
||||||
|
var (samples, edit) = Times(container, audio);
|
||||||
|
return new Mp4OutputTrack
|
||||||
|
{
|
||||||
|
IsVideo = false,
|
||||||
|
Timescale = audio.Timescale,
|
||||||
|
Samples = samples,
|
||||||
|
WriteSample = Writer(audio, reading),
|
||||||
|
AacConfiguration = audio.Codec == AudioCodec.Aac ? audio.AacConfiguration : null,
|
||||||
|
IsMp3 = audio.Codec == AudioCodec.Mp3,
|
||||||
|
SampleRate = audio.SampleRate,
|
||||||
|
Channels = audio.Channels,
|
||||||
|
Language = audio.Language,
|
||||||
|
EditMediaTime = edit,
|
||||||
|
EmptyEditDuration = audio.EmptyEditDuration,
|
||||||
|
EditSegmentDuration = audio.EditSegmentDuration,
|
||||||
|
LastSampleDuration = LastDuration(audio),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The samples with their composition times and the media time shown first: an ISO reader's presentation times
|
||||||
|
/// have the edit's media time taken off, so it is put back and becomes the edit of the output; without an edit
|
||||||
|
/// list (and in Matroska, whose block times are presentation times) the media time 0 is shown at 0.
|
||||||
|
/// </summary>
|
||||||
|
private static (Mp4OutputSample[] Samples, long Edit) Times(MediaContainer container, MediaTrack track)
|
||||||
|
{
|
||||||
|
var edit = container.Format == ContainerFormat.IsoBmff ? track.EditMediaTime ?? 0 : 0;
|
||||||
|
var samples = new Mp4OutputSample[track.Samples.Count];
|
||||||
|
for (var i = 0; i < samples.Length; i++)
|
||||||
|
{
|
||||||
|
var s = track.Samples[i];
|
||||||
|
samples[i] = new Mp4OutputSample(s.Size, s.DecodeTime, s.PresentationTime + edit, s.Key);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (samples, edit);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The duration of the last sample from the track's duration, when it is plausible (else the writer's default).</summary>
|
||||||
|
private static long LastDuration(MediaTrack track)
|
||||||
|
{
|
||||||
|
var samples = track.Samples;
|
||||||
|
var last = track.Duration - samples[^1].DecodeTime;
|
||||||
|
if (last <= 0)
|
||||||
|
{
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
var before = samples.Count > 1 ? samples[^1].DecodeTime - samples[^2].DecodeTime : last;
|
||||||
|
return before > 0 && last > 4 * before ? 0 : last;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Action<int, Stream> Writer(MediaTrack track, RemuxSource reading)
|
||||||
|
{
|
||||||
|
var buffer = new byte[64 * 1024];
|
||||||
|
return (i, output) =>
|
||||||
|
{
|
||||||
|
var source = reading.Stream ?? throw new InvalidOperationException("Il rimuxaggio non ha la sua sorgente.");
|
||||||
|
output.Write(ContainerReader.ReadSample(source, track.Samples[i], ref buffer));
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -41,6 +41,135 @@ public sealed class Mp4OutputTrack
|
|||||||
|
|
||||||
/// <summary>Duration of the last sample, when the times cannot tell it (0: as the one before it).</summary>
|
/// <summary>Duration of the last sample, when the times cannot tell it (0: as the one before it).</summary>
|
||||||
public long LastSampleDuration { get; init; }
|
public long LastSampleDuration { get; init; }
|
||||||
|
|
||||||
|
/// <summary>The ISO 639-2/T language of the <c>mdhd</c> («ita»); null writes «und».</summary>
|
||||||
|
public string? Language { get; init; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The sample entry of a video track: «avc1» or «avc3» (H.264), «hvc1» or «hev1» (HEVC), as the source has it;
|
||||||
|
/// null writes «avc1» or «hvc1».
|
||||||
|
/// </summary>
|
||||||
|
public string? SampleEntryType { get; init; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// MPEG-1/2 audio layer III in an <c>mp4a</c> entry (objectTypeIndication 0x6B, or 0x69 at 24 kHz and below,
|
||||||
|
/// ISO/IEC 14496-1): it has no AudioSpecificConfig, so <see cref="AacConfiguration"/> stays null.
|
||||||
|
/// </summary>
|
||||||
|
public bool IsMp3 { get; init; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The media time, on the scale of <see cref="Mp4OutputSample.PresentationTime"/>, shown at the start of the
|
||||||
|
/// presentation (the source's edit, so that AAC priming stays hidden); null lets the writer start at the first
|
||||||
|
/// shown sample, as before tappa E3.
|
||||||
|
/// </summary>
|
||||||
|
public long? EditMediaTime { get; init; }
|
||||||
|
|
||||||
|
/// <summary>A delayed start in track units: an empty edit before the media (0: none).</summary>
|
||||||
|
public long EmptyEditDuration { get; init; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// How long the edit shows the media, in track units (the source's segment: a trimmed end stays hidden); null shows
|
||||||
|
/// it from <see cref="EditMediaTime"/> to the end. Never longer than the media.
|
||||||
|
/// </summary>
|
||||||
|
public long? EditSegmentDuration { get; init; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The dates of the movie header; the modification date falls back to the creation date.</summary>
|
||||||
|
public sealed record Mp4MovieInfo(DateTimeOffset? Created, DateTimeOffset? Modified);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// An MP4 file planned by <see cref="Mp4Writer.Prepare"/>: its exact <see cref="Length"/> is known before a byte is
|
||||||
|
/// written, and <see cref="WriteTo"/> streams it, one sample at a time.
|
||||||
|
/// </summary>
|
||||||
|
public sealed class Mp4Layout
|
||||||
|
{
|
||||||
|
private readonly IReadOnlyList<Mp4OutputTrack> tracks;
|
||||||
|
private readonly List<(int Track, int First, int Count)> chunks;
|
||||||
|
private readonly byte[] head;
|
||||||
|
|
||||||
|
internal Mp4Layout(IReadOnlyList<Mp4OutputTrack> tracks, List<(int Track, int First, int Count)> chunks, byte[] head, long payload)
|
||||||
|
{
|
||||||
|
this.tracks = tracks;
|
||||||
|
this.chunks = chunks;
|
||||||
|
this.head = head;
|
||||||
|
Length = head.LongLength + payload;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Bytes of the whole file.</summary>
|
||||||
|
public long Length { get; }
|
||||||
|
|
||||||
|
/// <summary>Writes the file into <paramref name="output"/> (from its current position).</summary>
|
||||||
|
/// <exception cref="InvalidOperationException">A sample writer wrote another number of bytes than its size.</exception>
|
||||||
|
public void WriteTo(Stream output, CancellationToken ct = default)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(output);
|
||||||
|
var counting = new CountingStream(output);
|
||||||
|
counting.Write(head);
|
||||||
|
foreach (var (track, first, count) in chunks)
|
||||||
|
{
|
||||||
|
for (var k = first; k < first + count; k++)
|
||||||
|
{
|
||||||
|
ct.ThrowIfCancellationRequested();
|
||||||
|
var before = counting.Count;
|
||||||
|
tracks[track].WriteSample(k, counting);
|
||||||
|
if (counting.Count - before != tracks[track].Samples[k].Size)
|
||||||
|
{
|
||||||
|
throw new InvalidOperationException("Un campione non ha la lunghezza dichiarata.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (counting.Count != Length)
|
||||||
|
{
|
||||||
|
throw new InvalidOperationException("Il file scritto non ha la lunghezza prevista.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Counts the bytes written through it, whatever the stream below can tell.</summary>
|
||||||
|
private sealed class CountingStream(Stream inner) : Stream
|
||||||
|
{
|
||||||
|
public long Count { get; private set; }
|
||||||
|
|
||||||
|
public override bool CanRead => false;
|
||||||
|
|
||||||
|
public override bool CanSeek => false;
|
||||||
|
|
||||||
|
public override bool CanWrite => true;
|
||||||
|
|
||||||
|
public override long Length => throw new NotSupportedException();
|
||||||
|
|
||||||
|
public override long Position
|
||||||
|
{
|
||||||
|
get => Count;
|
||||||
|
set => throw new NotSupportedException();
|
||||||
|
}
|
||||||
|
|
||||||
|
public override void Flush() => inner.Flush();
|
||||||
|
|
||||||
|
public override int Read(byte[] buffer, int offset, int count) => throw new NotSupportedException();
|
||||||
|
|
||||||
|
public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException();
|
||||||
|
|
||||||
|
public override void SetLength(long value) => throw new NotSupportedException();
|
||||||
|
|
||||||
|
public override void Write(byte[] buffer, int offset, int count)
|
||||||
|
{
|
||||||
|
inner.Write(buffer, offset, count);
|
||||||
|
Count += count;
|
||||||
|
}
|
||||||
|
|
||||||
|
public override void Write(ReadOnlySpan<byte> buffer)
|
||||||
|
{
|
||||||
|
inner.Write(buffer);
|
||||||
|
Count += buffer.Length;
|
||||||
|
}
|
||||||
|
|
||||||
|
public override void WriteByte(byte value)
|
||||||
|
{
|
||||||
|
inner.WriteByte(value);
|
||||||
|
Count++;
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -57,6 +186,16 @@ public static class Mp4Writer
|
|||||||
public static void Write(Stream output, IReadOnlyList<Mp4OutputTrack> tracks, DateTimeOffset? created = null)
|
public static void Write(Stream output, IReadOnlyList<Mp4OutputTrack> tracks, DateTimeOffset? created = null)
|
||||||
{
|
{
|
||||||
ArgumentNullException.ThrowIfNull(output);
|
ArgumentNullException.ThrowIfNull(output);
|
||||||
|
Prepare(tracks, created is null ? null : new Mp4MovieInfo(created, created)).WriteTo(output);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Plans the file of <paramref name="tracks"/>: every box but the media data is built, so the length is known;
|
||||||
|
/// <see cref="Mp4Layout.WriteTo"/> writes it.
|
||||||
|
/// </summary>
|
||||||
|
/// <exception cref="ArgumentException">A track has no samples, no timescale or no codec configuration.</exception>
|
||||||
|
public static Mp4Layout Prepare(IReadOnlyList<Mp4OutputTrack> tracks, Mp4MovieInfo? info)
|
||||||
|
{
|
||||||
ArgumentNullException.ThrowIfNull(tracks);
|
ArgumentNullException.ThrowIfNull(tracks);
|
||||||
if (tracks.Count == 0 || tracks.Any(t => t.Samples.Count == 0 || t.Timescale <= 0))
|
if (tracks.Count == 0 || tracks.Any(t => t.Samples.Count == 0 || t.Timescale <= 0))
|
||||||
{
|
{
|
||||||
@@ -65,7 +204,7 @@ public static class Mp4Writer
|
|||||||
|
|
||||||
foreach (var track in tracks)
|
foreach (var track in tracks)
|
||||||
{
|
{
|
||||||
if (track.IsVideo ? (track.AvcConfiguration is null) == (track.HevcConfiguration is null) : track.AacConfiguration is null)
|
if (track.IsVideo ? (track.AvcConfiguration is null) == (track.HevcConfiguration is null) : track.AacConfiguration is null && !track.IsMp3)
|
||||||
{
|
{
|
||||||
throw new ArgumentException("Manca la configurazione del codificatore.", nameof(tracks));
|
throw new ArgumentException("Manca la configurazione del codificatore.", nameof(tracks));
|
||||||
}
|
}
|
||||||
@@ -84,7 +223,9 @@ public static class Mp4Writer
|
|||||||
|
|
||||||
var wideMdat = payload + 8 > uint.MaxValue;
|
var wideMdat = payload + 8 > uint.MaxValue;
|
||||||
var ftyp = Ftyp();
|
var ftyp = Ftyp();
|
||||||
var time = created is { } c && c > Epoch1904 ? (ulong)(c - Epoch1904).TotalSeconds : 0UL;
|
var creation = info?.Created is { } c && c > Epoch1904 ? (ulong)(c - Epoch1904).TotalSeconds : 0UL;
|
||||||
|
var modification = (info?.Modified ?? info?.Created) is { } m && m > Epoch1904 ? (ulong)(m - Epoch1904).TotalSeconds : 0UL;
|
||||||
|
var time = (creation, modification);
|
||||||
|
|
||||||
// The moov box has the same size whatever the chunk offsets: build it once to know where the data starts.
|
// The moov box has the same size whatever the chunk offsets: build it once to know where the data starts.
|
||||||
var co64 = false;
|
var co64 = false;
|
||||||
@@ -110,40 +251,35 @@ public static class Mp4Writer
|
|||||||
}
|
}
|
||||||
|
|
||||||
moov = Moov(tracks, timing, chunks, offsets, co64, time);
|
moov = Moov(tracks, timing, chunks, offsets, co64, time);
|
||||||
output.Write(ftyp);
|
var head = new byte[ftyp.Length + moov.Length + (wideMdat ? 16 : 8)];
|
||||||
output.Write(moov);
|
ftyp.CopyTo(head, 0);
|
||||||
Span<byte> header = stackalloc byte[16];
|
moov.CopyTo(head, ftyp.Length);
|
||||||
|
var header = head.AsSpan(ftyp.Length + moov.Length);
|
||||||
if (wideMdat)
|
if (wideMdat)
|
||||||
{
|
{
|
||||||
BinaryPrimitives.WriteUInt32BigEndian(header, 1);
|
BinaryPrimitives.WriteUInt32BigEndian(header, 1);
|
||||||
"mdat"u8.CopyTo(header[4..]);
|
"mdat"u8.CopyTo(header[4..]);
|
||||||
BinaryPrimitives.WriteUInt64BigEndian(header[8..], (ulong)(payload + 16));
|
BinaryPrimitives.WriteUInt64BigEndian(header[8..], (ulong)(payload + 16));
|
||||||
output.Write(header);
|
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
BinaryPrimitives.WriteUInt32BigEndian(header, (uint)(payload + 8));
|
BinaryPrimitives.WriteUInt32BigEndian(header, (uint)(payload + 8));
|
||||||
"mdat"u8.CopyTo(header[4..]);
|
"mdat"u8.CopyTo(header[4..]);
|
||||||
output.Write(header[..8]);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
foreach (var (track, first, count) in chunks)
|
return new Mp4Layout(tracks, chunks, head, payload);
|
||||||
{
|
|
||||||
for (var k = first; k < first + count; k++)
|
|
||||||
{
|
|
||||||
var before = output.CanSeek ? output.Position : -1;
|
|
||||||
tracks[track].WriteSample(k, output);
|
|
||||||
if (before >= 0 && output.Position - before != tracks[track].Samples[k].Size)
|
|
||||||
{
|
|
||||||
throw new InvalidOperationException("Un campione non ha la lunghezza dichiarata.");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>Times of a track as the boxes need them.</summary>
|
/// <summary>
|
||||||
private sealed record Timing(long[] Durations, int[] CompositionOffsets, long MediaDuration, long EditMediaTime, bool AllKey)
|
/// Times of a track as the boxes need them; <paramref name="EmptyEdit"/>, <paramref name="Shown"/> (the media
|
||||||
|
/// the edit shows, from <paramref name="EditMediaTime"/>) and <paramref name="PresentationEnd"/> (where the last
|
||||||
|
/// sample stops being shown, in composition time) are in track units.
|
||||||
|
/// </summary>
|
||||||
|
private sealed record Timing(long[] Durations, int[] CompositionOffsets, long MediaDuration, long EditMediaTime, bool AllKey, long EmptyEdit, long Shown, long PresentationEnd)
|
||||||
{
|
{
|
||||||
|
/// <summary>Whether the edit hides the end of the media (it must then be written).</summary>
|
||||||
|
public bool TrimsEnd => Shown < PresentationEnd - EditMediaTime;
|
||||||
|
|
||||||
internal static Timing Of(Mp4OutputTrack track)
|
internal static Timing Of(Mp4OutputTrack track)
|
||||||
{
|
{
|
||||||
var samples = track.Samples;
|
var samples = track.Samples;
|
||||||
@@ -180,9 +316,31 @@ public static class Mp4Writer
|
|||||||
total += d;
|
total += d;
|
||||||
}
|
}
|
||||||
|
|
||||||
// The edit list starts the presentation at the first shown sample.
|
// The presentation ends where the sample shown last stops, in composition time: with B frames that is later
|
||||||
var editTime = minPts - first + shift;
|
// than the decoding durations add up to (by the first composition offset), and the edit starts there too.
|
||||||
return new Timing(durations, offsets, total, editTime, allKey);
|
long presentationEnd = 0;
|
||||||
|
for (var i = 0; i < n; i++)
|
||||||
|
{
|
||||||
|
presentationEnd = Math.Max(presentationEnd, samples[i].DecodeTime - first + offsets[i] + durations[i]);
|
||||||
|
}
|
||||||
|
|
||||||
|
// The edit list starts the presentation at the first shown sample, or where the track says; a start before
|
||||||
|
// the first sample becomes an empty edit.
|
||||||
|
var editTime = (track.EditMediaTime ?? minPts) - first + shift;
|
||||||
|
var empty = Math.Max(0, track.EmptyEditDuration);
|
||||||
|
if (editTime < 0)
|
||||||
|
{
|
||||||
|
empty += -editTime;
|
||||||
|
editTime = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
var shown = Math.Max(0, presentationEnd - editTime);
|
||||||
|
if (track.EditSegmentDuration is { } segment && segment > 0)
|
||||||
|
{
|
||||||
|
shown = Math.Min(shown, segment);
|
||||||
|
}
|
||||||
|
|
||||||
|
return new Timing(durations, offsets, total, editTime, allKey, empty, shown, presentationEnd);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -222,17 +380,17 @@ public static class Mp4Writer
|
|||||||
return box.ToArray();
|
return box.ToArray();
|
||||||
}
|
}
|
||||||
|
|
||||||
private static byte[] Moov(IReadOnlyList<Mp4OutputTrack> tracks, Timing[] timing, List<(int Track, int First, int Count)> chunks, long[] offsets, bool co64, ulong time)
|
private static byte[] Moov(IReadOnlyList<Mp4OutputTrack> tracks, Timing[] timing, List<(int Track, int First, int Count)> chunks, long[] offsets, bool co64, (ulong Created, ulong Modified) time)
|
||||||
{
|
{
|
||||||
long movieDuration = 0;
|
long movieDuration = 0;
|
||||||
for (var t = 0; t < tracks.Count; t++)
|
for (var t = 0; t < tracks.Count; t++)
|
||||||
{
|
{
|
||||||
movieDuration = Math.Max(movieDuration, ToMovie(timing[t].MediaDuration - timing[t].EditMediaTime, tracks[t].Timescale));
|
movieDuration = Math.Max(movieDuration, EmptyMovie(timing[t], tracks[t].Timescale) + ToMovie(timing[t].Shown, tracks[t].Timescale));
|
||||||
}
|
}
|
||||||
|
|
||||||
var moov = new Box("moov");
|
var moov = new Box("moov");
|
||||||
var mvhd = new Box("mvhd");
|
var mvhd = new Box("mvhd");
|
||||||
var wide = movieDuration > uint.MaxValue || time > uint.MaxValue;
|
var wide = movieDuration > uint.MaxValue || Wide(time);
|
||||||
mvhd.U32(wide ? 0x01000000u : 0);
|
mvhd.U32(wide ? 0x01000000u : 0);
|
||||||
Times(mvhd, wide, time, MovieTimescale, movieDuration);
|
Times(mvhd, wide, time, MovieTimescale, movieDuration);
|
||||||
mvhd.U32(0x00010000);
|
mvhd.U32(0x00010000);
|
||||||
@@ -253,19 +411,25 @@ public static class Mp4Writer
|
|||||||
|
|
||||||
private static long ToMovie(long ticks, long timescale) => (long)Math.Ceiling(Math.Max(0, ticks) * (double)MovieTimescale / timescale);
|
private static long ToMovie(long ticks, long timescale) => (long)Math.Ceiling(Math.Max(0, ticks) * (double)MovieTimescale / timescale);
|
||||||
|
|
||||||
private static void Times(Box box, bool wide, ulong time, long timescale, long duration)
|
/// <summary>The empty edit of a track in movie units, rounded to the nearest.</summary>
|
||||||
|
private static long EmptyMovie(Timing timing, long timescale) =>
|
||||||
|
timing.EmptyEdit <= 0 ? 0 : (long)((((Int128)timing.EmptyEdit * MovieTimescale) + (timescale / 2)) / timescale);
|
||||||
|
|
||||||
|
private static bool Wide((ulong Created, ulong Modified) time) => time.Created > uint.MaxValue || time.Modified > uint.MaxValue;
|
||||||
|
|
||||||
|
private static void Times(Box box, bool wide, (ulong Created, ulong Modified) time, long timescale, long duration)
|
||||||
{
|
{
|
||||||
if (wide)
|
if (wide)
|
||||||
{
|
{
|
||||||
box.U64(time);
|
box.U64(time.Created);
|
||||||
box.U64(time);
|
box.U64(time.Modified);
|
||||||
box.U32((uint)timescale);
|
box.U32((uint)timescale);
|
||||||
box.U64((ulong)duration);
|
box.U64((ulong)duration);
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
box.U32((uint)time);
|
box.U32((uint)time.Created);
|
||||||
box.U32((uint)time);
|
box.U32((uint)time.Modified);
|
||||||
box.U32((uint)timescale);
|
box.U32((uint)timescale);
|
||||||
box.U32((uint)duration);
|
box.U32((uint)duration);
|
||||||
}
|
}
|
||||||
@@ -293,25 +457,27 @@ public static class Mp4Writer
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private static Box Trak(Mp4OutputTrack track, Timing timing, int index, List<(int Track, int First, int Count)> chunks, long[] offsets, bool co64, ulong time)
|
private static Box Trak(Mp4OutputTrack track, Timing timing, int index, List<(int Track, int First, int Count)> chunks, long[] offsets, bool co64, (ulong Created, ulong Modified) time)
|
||||||
{
|
{
|
||||||
var trak = new Box("trak");
|
var trak = new Box("trak");
|
||||||
var duration = ToMovie(timing.MediaDuration - timing.EditMediaTime, track.Timescale);
|
var segment = ToMovie(timing.Shown, track.Timescale);
|
||||||
var wide = duration > uint.MaxValue || time > uint.MaxValue;
|
var empty = EmptyMovie(timing, track.Timescale);
|
||||||
|
var duration = empty + segment;
|
||||||
|
var wide = duration > uint.MaxValue || Wide(time);
|
||||||
var tkhd = new Box("tkhd");
|
var tkhd = new Box("tkhd");
|
||||||
tkhd.U32((wide ? 0x01000000u : 0) | 3);
|
tkhd.U32((wide ? 0x01000000u : 0) | 3);
|
||||||
if (wide)
|
if (wide)
|
||||||
{
|
{
|
||||||
tkhd.U64(time);
|
tkhd.U64(time.Created);
|
||||||
tkhd.U64(time);
|
tkhd.U64(time.Modified);
|
||||||
tkhd.U32((uint)index + 1);
|
tkhd.U32((uint)index + 1);
|
||||||
tkhd.U32(0);
|
tkhd.U32(0);
|
||||||
tkhd.U64((ulong)duration);
|
tkhd.U64((ulong)duration);
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
tkhd.U32((uint)time);
|
tkhd.U32((uint)time.Created);
|
||||||
tkhd.U32((uint)time);
|
tkhd.U32((uint)time.Modified);
|
||||||
tkhd.U32((uint)index + 1);
|
tkhd.U32((uint)index + 1);
|
||||||
tkhd.U32(0);
|
tkhd.U32(0);
|
||||||
tkhd.U32((uint)duration);
|
tkhd.U32((uint)duration);
|
||||||
@@ -327,13 +493,21 @@ public static class Mp4Writer
|
|||||||
tkhd.U32(track.IsVideo ? (uint)track.Height << 16 : 0);
|
tkhd.U32(track.IsVideo ? (uint)track.Height << 16 : 0);
|
||||||
trak.Child(tkhd);
|
trak.Child(tkhd);
|
||||||
|
|
||||||
if (timing.EditMediaTime != 0)
|
if (timing.EditMediaTime != 0 || empty > 0 || timing.TrimsEnd)
|
||||||
{
|
{
|
||||||
var edts = new Box("edts");
|
var edts = new Box("edts");
|
||||||
var elst = new Box("elst");
|
var elst = new Box("elst");
|
||||||
elst.U32(0x01000000);
|
elst.U32(0x01000000);
|
||||||
elst.U32(1);
|
elst.U32(empty > 0 ? 2u : 1u);
|
||||||
elst.U64((ulong)duration);
|
if (empty > 0)
|
||||||
|
{
|
||||||
|
elst.U64((ulong)empty);
|
||||||
|
elst.U64(ulong.MaxValue); // media_time −1: an empty edit
|
||||||
|
elst.U16(1);
|
||||||
|
elst.U16(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
elst.U64((ulong)segment);
|
||||||
elst.U64((ulong)timing.EditMediaTime);
|
elst.U64((ulong)timing.EditMediaTime);
|
||||||
elst.U16(1);
|
elst.U16(1);
|
||||||
elst.U16(0);
|
elst.U16(0);
|
||||||
@@ -343,10 +517,10 @@ public static class Mp4Writer
|
|||||||
|
|
||||||
var mdia = new Box("mdia");
|
var mdia = new Box("mdia");
|
||||||
var mdhd = new Box("mdhd");
|
var mdhd = new Box("mdhd");
|
||||||
var mediaWide = timing.MediaDuration > uint.MaxValue || time > uint.MaxValue;
|
var mediaWide = timing.MediaDuration > uint.MaxValue || Wide(time);
|
||||||
mdhd.U32(mediaWide ? 0x01000000u : 0);
|
mdhd.U32(mediaWide ? 0x01000000u : 0);
|
||||||
Times(mdhd, mediaWide, time, track.Timescale, timing.MediaDuration);
|
Times(mdhd, mediaWide, time, track.Timescale, timing.MediaDuration);
|
||||||
mdhd.U16(0x55C4); // «und»
|
mdhd.U16(PackedLanguage(track.Language));
|
||||||
mdhd.U16(0);
|
mdhd.U16(0);
|
||||||
mdia.Child(mdhd);
|
mdia.Child(mdhd);
|
||||||
|
|
||||||
@@ -389,6 +563,17 @@ public static class Mp4Writer
|
|||||||
return trak;
|
return trak;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>An ISO 639-2/T code packed in 15 bits (ISO/IEC 14496-12 §8.4.2.3); «und» for anything else.</summary>
|
||||||
|
private static ushort PackedLanguage(string? language)
|
||||||
|
{
|
||||||
|
if (language is not { Length: 3 } || !language.All(char.IsAsciiLetterLower))
|
||||||
|
{
|
||||||
|
return 0x55C4; // «und»
|
||||||
|
}
|
||||||
|
|
||||||
|
return (ushort)(((language[0] - 0x60) << 10) | ((language[1] - 0x60) << 5) | (language[2] - 0x60));
|
||||||
|
}
|
||||||
|
|
||||||
private static Box Stbl(Mp4OutputTrack track, Timing timing, int index, List<(int Track, int First, int Count)> chunks, long[] offsets, bool co64)
|
private static Box Stbl(Mp4OutputTrack track, Timing timing, int index, List<(int Track, int First, int Count)> chunks, long[] offsets, bool co64)
|
||||||
{
|
{
|
||||||
var stbl = new Box("stbl");
|
var stbl = new Box("stbl");
|
||||||
@@ -540,7 +725,10 @@ public static class Mp4Writer
|
|||||||
private static Box Avc1(Mp4OutputTrack track)
|
private static Box Avc1(Mp4OutputTrack track)
|
||||||
{
|
{
|
||||||
var hevc = track.HevcConfiguration is not null;
|
var hevc = track.HevcConfiguration is not null;
|
||||||
var entry = new Box(hevc ? "hvc1" : "avc1");
|
var type = hevc
|
||||||
|
? track.SampleEntryType is "hvc1" or "hev1" ? track.SampleEntryType : "hvc1"
|
||||||
|
: track.SampleEntryType is "avc1" or "avc3" ? track.SampleEntryType : "avc1";
|
||||||
|
var entry = new Box(type);
|
||||||
entry.Zero(6);
|
entry.Zero(6);
|
||||||
entry.U16(1);
|
entry.U16(1);
|
||||||
entry.Zero(16);
|
entry.Zero(16);
|
||||||
@@ -571,10 +759,11 @@ public static class Mp4Writer
|
|||||||
entry.U16(0);
|
entry.U16(0);
|
||||||
entry.U32((uint)Math.Min(track.SampleRate, 65535) << 16);
|
entry.U32((uint)Math.Min(track.SampleRate, 65535) << 16);
|
||||||
|
|
||||||
var asc = track.AacConfiguration!;
|
var decoderSpecific = track.IsMp3 ? [] : Descriptor(0x05, track.AacConfiguration!);
|
||||||
var decoderSpecific = Descriptor(0x05, asc);
|
|
||||||
var config = new byte[13 + decoderSpecific.Length];
|
var config = new byte[13 + decoderSpecific.Length];
|
||||||
config[0] = 0x40; // MPEG-4 audio
|
// MPEG-4 audio, or layer III: MPEG-1 audio (ISO/IEC 11172-3, 32 to 48 kHz) or the MPEG-2 audio of the lower
|
||||||
|
// rates (ISO/IEC 13818-3, 16 to 24 kHz and the 8 to 12 kHz of «MPEG-2.5»): ISO/IEC 14496-1 Table 5.
|
||||||
|
config[0] = !track.IsMp3 ? (byte)0x40 : track.SampleRate is > 0 and <= 24000 ? (byte)0x69 : (byte)0x6B;
|
||||||
config[1] = 0x15; // audio stream
|
config[1] = 0x15; // audio stream
|
||||||
decoderSpecific.CopyTo(config, 13);
|
decoderSpecific.CopyTo(config, 13);
|
||||||
byte[] es = [0, 0, 0, .. Descriptor(0x04, config), .. Descriptor(0x06, [0x02])];
|
byte[] es = [0, 0, 0, .. Descriptor(0x04, config), .. Descriptor(0x06, [0x02])];
|
||||||
|
|||||||
@@ -216,6 +216,93 @@ public sealed partial class H264Decoder
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Whether the access unit carries a recovery point SEI (H.264 §D.1.8) with recovery_frame_cnt 0 and exact_match_flag
|
||||||
|
/// 1: decoding from it gives exact pictures from it on in output order, as from an IDR picture. Only the SEI before
|
||||||
|
/// the first slice counts.
|
||||||
|
/// </summary>
|
||||||
|
internal static bool HasExactRecoveryPoint(ReadOnlySpan<byte> accessUnit, int lengthSize)
|
||||||
|
{
|
||||||
|
var position = 0;
|
||||||
|
while (true)
|
||||||
|
{
|
||||||
|
Range unit;
|
||||||
|
var more = lengthSize == 0
|
||||||
|
? NalUnits.NextAnnexB(accessUnit, ref position, out unit)
|
||||||
|
: NalUnits.NextLengthPrefixed(accessUnit, lengthSize, ref position, out unit);
|
||||||
|
if (!more)
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
var nal = accessUnit[unit];
|
||||||
|
var type = nal[0] & 0x1F;
|
||||||
|
if (type is 1 or 2 or 5)
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (type != 6)
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var sei = NalUnits.Parse(nal);
|
||||||
|
var data = sei.Rbsp;
|
||||||
|
var length = sei.Length;
|
||||||
|
var p = sei.HeaderLength;
|
||||||
|
while (p < length - 1)
|
||||||
|
{
|
||||||
|
var payloadType = 0;
|
||||||
|
while (p < length && data[p] == 0xFF)
|
||||||
|
{
|
||||||
|
payloadType += 255;
|
||||||
|
p++;
|
||||||
|
}
|
||||||
|
|
||||||
|
var payloadSize = 0;
|
||||||
|
if (p < length)
|
||||||
|
{
|
||||||
|
payloadType += data[p++];
|
||||||
|
}
|
||||||
|
|
||||||
|
while (p < length && data[p] == 0xFF)
|
||||||
|
{
|
||||||
|
payloadSize += 255;
|
||||||
|
p++;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (p >= length)
|
||||||
|
{
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
payloadSize += data[p++];
|
||||||
|
if (payloadType == 6)
|
||||||
|
{
|
||||||
|
// recovery_frame_cnt 0, then exact_match_flag 1 (§D.2.8): with 0 the pictures from here may
|
||||||
|
// differ from those decoded from the IDR before, so it is no exact start.
|
||||||
|
if (payloadSize <= 0)
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
var reader = new RbspReader(data, Math.Min(length, p + payloadSize), p);
|
||||||
|
return reader.ReadUe() == 0 && reader.BitsLeft > 0 && reader.ReadFlag();
|
||||||
|
}
|
||||||
|
|
||||||
|
p += payloadSize;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (H264Exception)
|
||||||
|
{
|
||||||
|
// A damaged SEI says nothing.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private void DecodeUnitsAnnexB(ReadOnlySpan<byte> stream)
|
private void DecodeUnitsAnnexB(ReadOnlySpan<byte> stream)
|
||||||
{
|
{
|
||||||
var position = 0;
|
var position = 0;
|
||||||
|
|||||||
@@ -0,0 +1,322 @@
|
|||||||
|
using Febe.Core.Codecs.Containers;
|
||||||
|
|
||||||
|
namespace Febe.Core.Codecs.H264;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// One picture of an I_PCM stream in 4:2:0: <see cref="Y"/> is <c>Width × Height</c> luma samples, <see cref="Cb"/> and
|
||||||
|
/// <see cref="Cr"/> are <c>Width/2 × Height/2</c>, row by row. Width and height are multiples of 16.
|
||||||
|
/// </summary>
|
||||||
|
public sealed class H264PcmPicture
|
||||||
|
{
|
||||||
|
public H264PcmPicture(int width, int height)
|
||||||
|
{
|
||||||
|
if (width <= 0 || height <= 0 || width % 16 != 0 || height % 16 != 0)
|
||||||
|
{
|
||||||
|
throw new ArgumentOutOfRangeException(nameof(width), "Larghezza e altezza devono essere multipli di 16.");
|
||||||
|
}
|
||||||
|
|
||||||
|
Width = width;
|
||||||
|
Height = height;
|
||||||
|
Y = new byte[width * height];
|
||||||
|
Cb = new byte[width / 2 * (height / 2)];
|
||||||
|
Cr = new byte[width / 2 * (height / 2)];
|
||||||
|
}
|
||||||
|
|
||||||
|
public int Width { get; }
|
||||||
|
|
||||||
|
public int Height { get; }
|
||||||
|
|
||||||
|
public byte[] Y { get; }
|
||||||
|
|
||||||
|
public byte[] Cb { get; }
|
||||||
|
|
||||||
|
public byte[] Cr { get; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Writes H.264 streams made only of IDR pictures of I_PCM macroblocks (ITU-T H.264 §7.3: Baseline parameter sets, one
|
||||||
|
/// slice per picture, every sample written as it is), muxed in MP4 with <see cref="Mp4Writer"/>. Every pixel is known
|
||||||
|
/// and every picture is an exact start for a decoder: the demo's video (frames in <c>--demo</c>) and the tests use it.
|
||||||
|
/// Nothing is compressed, so the files are large (about 1,5 bytes per pixel per picture): for short, small videos only.
|
||||||
|
/// </summary>
|
||||||
|
public static class H264PcmWriter
|
||||||
|
{
|
||||||
|
/// <summary>Width of the demo video (15 macroblocks, no cropping).</summary>
|
||||||
|
public const int DemoWidth = 240;
|
||||||
|
|
||||||
|
/// <summary>Height of the demo video (27 macroblocks, no cropping).</summary>
|
||||||
|
public const int DemoHeight = 432;
|
||||||
|
|
||||||
|
/// <summary>Pictures per second of the demo video.</summary>
|
||||||
|
public const int DemoFps = 8;
|
||||||
|
|
||||||
|
/// <summary>Pictures of the demo video (two seconds).</summary>
|
||||||
|
public const int DemoPictures = 16;
|
||||||
|
|
||||||
|
/// <summary>The sequence parameter set (RBSP with emulation prevention, no start code), POC type 2, no VUI.</summary>
|
||||||
|
public static byte[] Sps(int width, int height)
|
||||||
|
{
|
||||||
|
var bits = new Bits();
|
||||||
|
bits.Write(66, 8); // profile_idc: Baseline
|
||||||
|
bits.Write(0, 8); // constraint_set flags
|
||||||
|
bits.Write(30, 8); // level_idc 3.0
|
||||||
|
bits.Ue(0); // seq_parameter_set_id
|
||||||
|
bits.Ue(0); // log2_max_frame_num_minus4
|
||||||
|
bits.Ue(2); // pic_order_cnt_type: output order = decoding order
|
||||||
|
bits.Ue(1); // max_num_ref_frames
|
||||||
|
bits.Write(0, 1); // gaps_in_frame_num_value_allowed_flag
|
||||||
|
bits.Ue((uint)(width / 16) - 1); // pic_width_in_mbs_minus1
|
||||||
|
bits.Ue((uint)(height / 16) - 1); // pic_height_in_map_units_minus1
|
||||||
|
bits.Write(1, 1); // frame_mbs_only_flag
|
||||||
|
bits.Write(1, 1); // direct_8x8_inference_flag
|
||||||
|
bits.Write(0, 1); // frame_cropping_flag
|
||||||
|
bits.Write(0, 1); // vui_parameters_present_flag
|
||||||
|
return Nal(0x67, bits);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The picture parameter set (CAVLC, one slice group, deblocking control present).</summary>
|
||||||
|
public static byte[] Pps()
|
||||||
|
{
|
||||||
|
var bits = new Bits();
|
||||||
|
bits.Ue(0); // pic_parameter_set_id
|
||||||
|
bits.Ue(0); // seq_parameter_set_id
|
||||||
|
bits.Write(0, 1); // entropy_coding_mode_flag: CAVLC
|
||||||
|
bits.Write(0, 1); // bottom_field_pic_order_in_frame_present_flag
|
||||||
|
bits.Ue(0); // num_slice_groups_minus1
|
||||||
|
bits.Ue(0); // num_ref_idx_l0_default_active_minus1
|
||||||
|
bits.Ue(0); // num_ref_idx_l1_default_active_minus1
|
||||||
|
bits.Write(0, 1); // weighted_pred_flag
|
||||||
|
bits.Write(0, 2); // weighted_bipred_idc
|
||||||
|
bits.Se(0); // pic_init_qp_minus26
|
||||||
|
bits.Se(0); // pic_init_qs_minus26
|
||||||
|
bits.Se(0); // chroma_qp_index_offset
|
||||||
|
bits.Write(1, 1); // deblocking_filter_control_present_flag
|
||||||
|
bits.Write(0, 1); // constrained_intra_pred_flag
|
||||||
|
bits.Write(0, 1); // redundant_pic_cnt_present_flag
|
||||||
|
return Nal(0x68, bits);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>An IDR picture of I_PCM macroblocks (one slice, deblocking off), as a NAL unit without start code.</summary>
|
||||||
|
/// <param name="picture">The samples.</param>
|
||||||
|
/// <param name="idrPicId">idr_pic_id: two IDR pictures in a row must differ (0 and 1 alternate).</param>
|
||||||
|
public static byte[] Idr(H264PcmPicture picture, int idrPicId)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(picture);
|
||||||
|
var bits = new Bits(picture.Y.Length * 3 / 2 + 1024);
|
||||||
|
bits.Ue(0); // first_mb_in_slice
|
||||||
|
bits.Ue(7); // slice_type: I (all slices of the picture)
|
||||||
|
bits.Ue(0); // pic_parameter_set_id
|
||||||
|
bits.Write(0, 4); // frame_num
|
||||||
|
bits.Ue((uint)idrPicId);
|
||||||
|
bits.Write(0, 1); // no_output_of_prior_pics_flag
|
||||||
|
bits.Write(0, 1); // long_term_reference_flag
|
||||||
|
bits.Se(0); // slice_qp_delta
|
||||||
|
bits.Ue(1); // disable_deblocking_filter_idc: off
|
||||||
|
var mbWidth = picture.Width / 16;
|
||||||
|
var mbHeight = picture.Height / 16;
|
||||||
|
var chromaWidth = picture.Width / 2;
|
||||||
|
for (var my = 0; my < mbHeight; my++)
|
||||||
|
{
|
||||||
|
for (var mx = 0; mx < mbWidth; mx++)
|
||||||
|
{
|
||||||
|
bits.Ue(25); // mb_type: I_PCM
|
||||||
|
bits.Align(); // pcm_alignment_zero_bit
|
||||||
|
for (var y = 0; y < 16; y++)
|
||||||
|
{
|
||||||
|
bits.Bytes(picture.Y.AsSpan(((my * 16) + y) * picture.Width + (mx * 16), 16));
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach (var plane in new[] { picture.Cb, picture.Cr })
|
||||||
|
{
|
||||||
|
for (var y = 0; y < 8; y++)
|
||||||
|
{
|
||||||
|
bits.Bytes(plane.AsSpan(((my * 8) + y) * chromaWidth + (mx * 8), 8));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return Nal(0x65, bits);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The <c>avcC</c> of a stream with these parameter sets (ISO/IEC 14496-15 §5.3.3.1), lengths on 4 bytes.</summary>
|
||||||
|
public static byte[] AvcConfiguration(byte[] sps, byte[] pps)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(sps);
|
||||||
|
ArgumentNullException.ThrowIfNull(pps);
|
||||||
|
return
|
||||||
|
[
|
||||||
|
1, sps[1], sps[2], sps[3], 0xFF, 0xE1,
|
||||||
|
(byte)(sps.Length >> 8), (byte)sps.Length, .. sps,
|
||||||
|
1, (byte)(pps.Length >> 8), (byte)pps.Length, .. pps,
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Writes an MP4 of <paramref name="count"/> pictures at <paramref name="fps"/> per second, picture <c>i</c> given by
|
||||||
|
/// <paramref name="picture"/>, every one an IDR sync sample.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="output">Where the file goes (from its current position).</param>
|
||||||
|
/// <param name="width">Width, a multiple of 16.</param>
|
||||||
|
/// <param name="height">Height, a multiple of 16.</param>
|
||||||
|
/// <param name="count">Pictures.</param>
|
||||||
|
/// <param name="fps">Pictures per second.</param>
|
||||||
|
/// <param name="picture">The samples of picture <c>i</c> (called once per picture, in order).</param>
|
||||||
|
/// <param name="created">The creation date of the movie; null writes none.</param>
|
||||||
|
public static void WriteMp4(Stream output, int width, int height, int count, int fps, Func<int, H264PcmPicture> picture, DateTimeOffset? created = null)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(output);
|
||||||
|
ArgumentNullException.ThrowIfNull(picture);
|
||||||
|
ArgumentOutOfRangeException.ThrowIfLessThan(count, 1);
|
||||||
|
ArgumentOutOfRangeException.ThrowIfLessThan(fps, 1);
|
||||||
|
var sps = Sps(width, height);
|
||||||
|
var pps = Pps();
|
||||||
|
var samples = new List<byte[]>(count);
|
||||||
|
for (var i = 0; i < count; i++)
|
||||||
|
{
|
||||||
|
var p = picture(i);
|
||||||
|
if (p.Width != width || p.Height != height)
|
||||||
|
{
|
||||||
|
throw new ArgumentException("Ogni fotogramma deve avere le dimensioni del video.", nameof(picture));
|
||||||
|
}
|
||||||
|
|
||||||
|
var nal = Idr(p, i % 2);
|
||||||
|
var sample = new byte[nal.Length + 4];
|
||||||
|
System.Buffers.Binary.BinaryPrimitives.WriteInt32BigEndian(sample, nal.Length);
|
||||||
|
nal.CopyTo(sample, 4);
|
||||||
|
samples.Add(sample);
|
||||||
|
}
|
||||||
|
|
||||||
|
const int Ticks = 1000;
|
||||||
|
var track = new Mp4OutputTrack
|
||||||
|
{
|
||||||
|
IsVideo = true,
|
||||||
|
Timescale = (long)fps * Ticks,
|
||||||
|
Samples = [.. samples.Select((s, i) => new Mp4OutputSample(s.Length, (long)i * Ticks, (long)i * Ticks, true))],
|
||||||
|
WriteSample = (i, s) => s.Write(samples[i]),
|
||||||
|
Width = width,
|
||||||
|
Height = height,
|
||||||
|
AvcConfiguration = AvcConfiguration(sps, pps),
|
||||||
|
LastSampleDuration = Ticks,
|
||||||
|
};
|
||||||
|
Mp4Writer.Write(output, [track], created);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The demo's video: <see cref="DemoWidth"/>×<see cref="DemoHeight"/>, <see cref="DemoFps"/> pictures per second for
|
||||||
|
/// two seconds, a diagonal gradient that moves to the right with colours that change over time.
|
||||||
|
/// </summary>
|
||||||
|
public static byte[] DemoVideo()
|
||||||
|
{
|
||||||
|
using var output = new MemoryStream();
|
||||||
|
WriteMp4(output, DemoWidth, DemoHeight, DemoPictures, DemoFps, DemoPicture, new DateTimeOffset(2026, 1, 1, 12, 0, 0, TimeSpan.Zero));
|
||||||
|
return output.ToArray();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Picture <paramref name="index"/> of the demo video (luma 16-235, chroma 16-240: no zero byte).</summary>
|
||||||
|
public static H264PcmPicture DemoPicture(int index)
|
||||||
|
{
|
||||||
|
var p = new H264PcmPicture(DemoWidth, DemoHeight);
|
||||||
|
var shift = index * 219 / DemoPictures;
|
||||||
|
for (var y = 0; y < DemoHeight; y++)
|
||||||
|
{
|
||||||
|
for (var x = 0; x < DemoWidth; x++)
|
||||||
|
{
|
||||||
|
var ramp = ((x * 219 / DemoWidth) + (y * 219 / DemoHeight / 2) + 219 - shift) % 219;
|
||||||
|
p.Y[(y * DemoWidth) + x] = (byte)(16 + ramp);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var chromaWidth = DemoWidth / 2;
|
||||||
|
for (var y = 0; y < DemoHeight / 2; y++)
|
||||||
|
{
|
||||||
|
for (var x = 0; x < chromaWidth; x++)
|
||||||
|
{
|
||||||
|
p.Cb[(y * chromaWidth) + x] = (byte)(64 + (y * 128 / (DemoHeight / 2)));
|
||||||
|
p.Cr[(y * chromaWidth) + x] = (byte)(64 + ((x * 64 / chromaWidth) + (index * 64 / DemoPictures)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return p;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>A NAL unit (header byte, then the RBSP with its trailing bits and emulation prevention).</summary>
|
||||||
|
private static byte[] Nal(byte header, Bits bits)
|
||||||
|
{
|
||||||
|
bits.Write(1, 1); // rbsp_stop_one_bit
|
||||||
|
bits.Align();
|
||||||
|
var rbsp = bits.ToArray();
|
||||||
|
var output = new List<byte>(rbsp.Length + (rbsp.Length / 64) + 2) { header };
|
||||||
|
var zeros = 0;
|
||||||
|
foreach (var b in rbsp)
|
||||||
|
{
|
||||||
|
// Never two zero bytes followed by a byte up to 3 (§7.4.1).
|
||||||
|
if (zeros >= 2 && b <= 3)
|
||||||
|
{
|
||||||
|
output.Add(3);
|
||||||
|
zeros = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
output.Add(b);
|
||||||
|
zeros = b == 0 ? zeros + 1 : 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
return [.. output];
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>A big-endian bit writer for the RBSP.</summary>
|
||||||
|
private sealed class Bits(int capacity = 64)
|
||||||
|
{
|
||||||
|
private readonly List<byte> _bytes = new(capacity);
|
||||||
|
private int _current;
|
||||||
|
private int _used;
|
||||||
|
|
||||||
|
public void Write(uint value, int count)
|
||||||
|
{
|
||||||
|
for (var i = count - 1; i >= 0; i--)
|
||||||
|
{
|
||||||
|
_current = (_current << 1) | (int)((value >> i) & 1);
|
||||||
|
if (++_used == 8)
|
||||||
|
{
|
||||||
|
_bytes.Add((byte)_current);
|
||||||
|
_current = 0;
|
||||||
|
_used = 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Ue(uint value)
|
||||||
|
{
|
||||||
|
var code = value + 1;
|
||||||
|
var length = 32 - System.Numerics.BitOperations.LeadingZeroCount(code);
|
||||||
|
Write(0, length - 1);
|
||||||
|
Write(code, length);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Se(int value) => Ue(value <= 0 ? (uint)(-2 * value) : (uint)((2 * value) - 1));
|
||||||
|
|
||||||
|
public void Align()
|
||||||
|
{
|
||||||
|
while (_used != 0)
|
||||||
|
{
|
||||||
|
Write(0, 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Whole bytes, after <see cref="Align"/>.</summary>
|
||||||
|
public void Bytes(ReadOnlySpan<byte> data)
|
||||||
|
{
|
||||||
|
if (_used != 0)
|
||||||
|
{
|
||||||
|
throw new InvalidOperationException("Bytes only at a byte boundary.");
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach (var b in data)
|
||||||
|
{
|
||||||
|
_bytes.Add(b);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public byte[] ToArray() => _used == 0 ? [.. _bytes] : throw new InvalidOperationException("Not aligned.");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -71,6 +71,67 @@ internal static class ExifOrientation
|
|||||||
return 1;
|
return 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Whether <paramref name="tiff"/> is a TIFF structure an encoder can carry: the «II*\0» or «MM\0*» header and a
|
||||||
|
/// first IFD whose entry count lies inside the block. A damaged EXIF block fails and is left behind by a conversion.
|
||||||
|
/// </summary>
|
||||||
|
public static bool IsTiff(ReadOnlySpan<byte> tiff)
|
||||||
|
{
|
||||||
|
if (tiff.Length < 8 || !(tiff.StartsWith("II*\0"u8) || tiff.StartsWith("MM\0*"u8)))
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
var ifd = U32(tiff[4..], tiff[0] == (byte)'I');
|
||||||
|
return ifd >= 8 && ifd <= (uint)(tiff.Length - 2);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The smallest EXIF block that carries <paramref name="orientation"/>: a TIFF header in the byte order asked, a
|
||||||
|
/// first IFD at offset 8 with the one Orientation entry (SHORT, count 1) and no next IFD. 26 bytes.
|
||||||
|
/// </summary>
|
||||||
|
public static byte[] Minimal(int orientation, bool littleEndian)
|
||||||
|
{
|
||||||
|
ArgumentOutOfRangeException.ThrowIfLessThan(orientation, 1);
|
||||||
|
ArgumentOutOfRangeException.ThrowIfGreaterThan(orientation, 8);
|
||||||
|
var block = new byte[26];
|
||||||
|
var b = block.AsSpan();
|
||||||
|
b[0] = b[1] = littleEndian ? (byte)'I' : (byte)'M';
|
||||||
|
W16(b[2..], 42, littleEndian);
|
||||||
|
W32(b[4..], 8, littleEndian); // the first IFD
|
||||||
|
W16(b[8..], 1, littleEndian); // one entry
|
||||||
|
W16(b[10..], OrientationTag, littleEndian);
|
||||||
|
W16(b[12..], 3, littleEndian); // SHORT
|
||||||
|
W32(b[14..], 1, littleEndian); // count
|
||||||
|
W16(b[18..], (ushort)orientation, littleEndian); // the value, left-justified in the 4-byte field
|
||||||
|
// Bytes 22-25: the offset of the next IFD, 0.
|
||||||
|
return block;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void W16(Span<byte> b, ushort value, bool little)
|
||||||
|
{
|
||||||
|
if (little)
|
||||||
|
{
|
||||||
|
BinaryPrimitives.WriteUInt16LittleEndian(b, value);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
BinaryPrimitives.WriteUInt16BigEndian(b, value);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void W32(Span<byte> b, uint value, bool little)
|
||||||
|
{
|
||||||
|
if (little)
|
||||||
|
{
|
||||||
|
BinaryPrimitives.WriteUInt32LittleEndian(b, value);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
BinaryPrimitives.WriteUInt32BigEndian(b, value);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private static ushort U16(ReadOnlySpan<byte> b, bool little) =>
|
private static ushort U16(ReadOnlySpan<byte> b, bool little) =>
|
||||||
little ? BinaryPrimitives.ReadUInt16LittleEndian(b) : BinaryPrimitives.ReadUInt16BigEndian(b);
|
little ? BinaryPrimitives.ReadUInt16LittleEndian(b) : BinaryPrimitives.ReadUInt16BigEndian(b);
|
||||||
|
|
||||||
|
|||||||
@@ -77,7 +77,10 @@ public static class GifDecoder
|
|||||||
CanvasHeight,
|
CanvasHeight,
|
||||||
Math.Max(1, FrameCount),
|
Math.Max(1, FrameCount),
|
||||||
true,
|
true,
|
||||||
Comments is null ? ImageMetadata.Empty : new ImageMetadata { Texts = Comments });
|
Comments is null ? ImageMetadata.Empty : new ImageMetadata { Texts = Comments })
|
||||||
|
{
|
||||||
|
IsAnimated = FrameCount > 1,
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
private static GifFile Walk(ReadOnlySpan<byte> data, ImageLimits limits, bool countFrames)
|
private static GifFile Walk(ReadOnlySpan<byte> data, ImageLimits limits, bool countFrames)
|
||||||
|
|||||||
@@ -33,6 +33,10 @@ public sealed record ImageConversionOptions
|
|||||||
/// </param>
|
/// </param>
|
||||||
/// <param name="Metadata">The metadata written.</param>
|
/// <param name="Metadata">The metadata written.</param>
|
||||||
/// <param name="NotCarried">What of the source's metadata the target could not take, in Italian, for the interface.</param>
|
/// <param name="NotCarried">What of the source's metadata the target could not take, in Italian, for the interface.</param>
|
||||||
|
/// <param name="Losses">
|
||||||
|
/// The same as note codes (tappa E3, <see cref="ImageConversionLosses"/>), once each, in a fixed order: what the export
|
||||||
|
/// and the library conversion record.
|
||||||
|
/// </param>
|
||||||
public sealed record ImageConversionResult(
|
public sealed record ImageConversionResult(
|
||||||
byte[] Data,
|
byte[] Data,
|
||||||
ImageFormat Source,
|
ImageFormat Source,
|
||||||
@@ -41,7 +45,60 @@ public sealed record ImageConversionResult(
|
|||||||
int Height,
|
int Height,
|
||||||
bool Lossy,
|
bool Lossy,
|
||||||
ImageMetadata Metadata,
|
ImageMetadata Metadata,
|
||||||
IReadOnlyList<string> NotCarried);
|
IReadOnlyList<string> NotCarried,
|
||||||
|
IReadOnlyList<string> Losses);
|
||||||
|
|
||||||
|
/// <summary>What a conversion does with a source (tappa E3, decisions D5 and D6).</summary>
|
||||||
|
public enum ImageConversionAction
|
||||||
|
{
|
||||||
|
/// <summary>The source is already in the target format: it is copied byte for byte, without a note.</summary>
|
||||||
|
CopyAsIs,
|
||||||
|
|
||||||
|
/// <summary>The source is decoded and written in the target format.</summary>
|
||||||
|
Convert,
|
||||||
|
|
||||||
|
/// <summary>The source cannot be converted without losing what matters: it is copied as it is, with a note.</summary>
|
||||||
|
CopyOriginal,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The outcome of <see cref="ImageConverter.Check"/>.</summary>
|
||||||
|
/// <param name="Action">What to do.</param>
|
||||||
|
/// <param name="Source">The format of the source by its bytes; null when it is not recognised.</param>
|
||||||
|
/// <param name="NoteCode">For <see cref="ImageConversionAction.CopyOriginal"/>, why (<c>AsIsHeif</c>, <c>AsIsAnimated</c>...).</param>
|
||||||
|
public sealed record ImageConversionCheck(ImageConversionAction Action, ImageFormat? Source, string? NoteCode);
|
||||||
|
|
||||||
|
/// <summary>The note codes of what a conversion copies as it is or does not keep (decision D19 of tappa E3).</summary>
|
||||||
|
public static class ImageConversionLosses
|
||||||
|
{
|
||||||
|
public const string AsIsHeif = "AsIsHeif";
|
||||||
|
public const string AsIsAvif = "AsIsAvif";
|
||||||
|
public const string AsIsRaw = "AsIsRaw";
|
||||||
|
public const string AsIsAnimated = "AsIsAnimated";
|
||||||
|
public const string AsIsNotDecodable = "AsIsNotDecodable";
|
||||||
|
public const string AsIsDeepColor = "AsIsDeepColor";
|
||||||
|
public const string AsIsCmyk = "AsIsCmyk";
|
||||||
|
public const string AsIsTooLarge = "AsIsTooLarge";
|
||||||
|
|
||||||
|
public const string LostTexts = "LostTexts";
|
||||||
|
public const string LostColorChunks = "LostColorChunks";
|
||||||
|
public const string LostIcc = "LostIcc";
|
||||||
|
public const string LostIccTooLarge = "LostIccTooLarge";
|
||||||
|
public const string LostExifTooLarge = "LostExifTooLarge";
|
||||||
|
public const string LostXmpTooLarge = "LostXmpTooLarge";
|
||||||
|
public const string LostExtendedXmp = "LostExtendedXmp";
|
||||||
|
public const string LostExifUnreadable = "LostExifUnreadable";
|
||||||
|
public const string LostIptc = "LostIptc";
|
||||||
|
public const string LostOtherSegments = "LostOtherSegments";
|
||||||
|
public const string LostCommentTooLarge = "LostCommentTooLarge";
|
||||||
|
public const string TransparencyWhite = "TransparencyWhite";
|
||||||
|
|
||||||
|
/// <summary>The order in which the codes are listed, so that the same source always gives the same note.</summary>
|
||||||
|
internal static readonly string[] Order =
|
||||||
|
[
|
||||||
|
TransparencyWhite, LostExifUnreadable, LostExifTooLarge, LostIcc, LostIccTooLarge, LostXmpTooLarge, LostExtendedXmp,
|
||||||
|
LostIptc, LostTexts, LostCommentTooLarge, LostColorChunks, LostOtherSegments,
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Turns a picture into another format with the same pixels and the same metadata, so that the converted file is
|
/// Turns a picture into another format with the same pixels and the same metadata, so that the converted file is
|
||||||
@@ -57,9 +114,101 @@ public sealed record ImageConversionResult(
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public static class ImageConverter
|
public static class ImageConverter
|
||||||
{
|
{
|
||||||
|
/// <summary>The largest source a conversion reads into memory (decision D6 of tappa E3: 512 MiB).</summary>
|
||||||
|
public const long MaxSourceBytes = 512L * 1024 * 1024;
|
||||||
|
|
||||||
|
/// <summary>The largest picture written as WebP (decision D6 of tappa E3: about 1.1 GB of working memory).</summary>
|
||||||
|
public const long MaxWebPPixels = 40_000_000;
|
||||||
|
|
||||||
/// <summary>The formats a conversion can write.</summary>
|
/// <summary>The formats a conversion can write.</summary>
|
||||||
public static bool CanWrite(ImageFormat format) => format is ImageFormat.Jpeg or ImageFormat.Png or ImageFormat.WebP;
|
public static bool CanWrite(ImageFormat format) => format is ImageFormat.Jpeg or ImageFormat.Png or ImageFormat.WebP;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// What a conversion of <paramref name="data"/> to <paramref name="target"/> does, from its bytes and its header
|
||||||
|
/// only (tappa E3, D5 and D6): the same format is copied byte for byte (a lossy WebP to WebP too); HEIF, AVIF, TIFF
|
||||||
|
/// and raw files, animations, damaged or unknown files, CMYK and deep-colour sources to PNG or WebP and pictures
|
||||||
|
/// over the pixel budget of the target are copied as they are, with the reason. Never throws for a bad file.
|
||||||
|
/// </summary>
|
||||||
|
/// <exception cref="ArgumentException">The target is not JPEG, PNG or WebP.</exception>
|
||||||
|
public static ImageConversionCheck Check(ReadOnlyMemory<byte> data, ImageFormat target, ImageConversionOptions? options = null)
|
||||||
|
{
|
||||||
|
if (!CanWrite(target))
|
||||||
|
{
|
||||||
|
throw new ArgumentException($"Febe non scrive immagini {target.ToString().ToUpperInvariant()}.", nameof(target));
|
||||||
|
}
|
||||||
|
|
||||||
|
options ??= ImageConversionOptions.Default;
|
||||||
|
var source = ImageFormatSniffer.Detect(data.Span);
|
||||||
|
if (source == target)
|
||||||
|
{
|
||||||
|
return new ImageConversionCheck(ImageConversionAction.CopyAsIs, source, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
string? asIs = source switch
|
||||||
|
{
|
||||||
|
ImageFormat.Heif => ImageConversionLosses.AsIsHeif,
|
||||||
|
ImageFormat.Avif => ImageConversionLosses.AsIsAvif,
|
||||||
|
ImageFormat.Tiff => ImageConversionLosses.AsIsRaw, // TIFF and the raw formats built on it (DNG, NEF, CR2...)
|
||||||
|
ImageFormat.Unknown => ImageConversionLosses.AsIsNotDecodable,
|
||||||
|
_ => null,
|
||||||
|
};
|
||||||
|
if (asIs is null && data.Length > MaxSourceBytes)
|
||||||
|
{
|
||||||
|
asIs = ImageConversionLosses.AsIsTooLarge;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (asIs is null)
|
||||||
|
{
|
||||||
|
asIs = IdentifyOutcome(data, target, options.Limits);
|
||||||
|
}
|
||||||
|
|
||||||
|
return asIs is null
|
||||||
|
? new ImageConversionCheck(ImageConversionAction.Convert, source, null)
|
||||||
|
: new ImageConversionCheck(ImageConversionAction.CopyOriginal, source == ImageFormat.Unknown ? null : source, asIs);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string? IdentifyOutcome(ReadOnlyMemory<byte> data, ImageFormat target, ImageLimits limits)
|
||||||
|
{
|
||||||
|
ImageInfo info;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
info = ImageDecoder.Identify(data, limits);
|
||||||
|
}
|
||||||
|
catch (ImageLimitException)
|
||||||
|
{
|
||||||
|
return ImageConversionLosses.AsIsTooLarge;
|
||||||
|
}
|
||||||
|
catch (ImageDecodeException)
|
||||||
|
{
|
||||||
|
return ImageConversionLosses.AsIsNotDecodable;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (info.IsAnimated)
|
||||||
|
{
|
||||||
|
return ImageConversionLosses.AsIsAnimated;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (target != ImageFormat.Jpeg && info.IsCmyk)
|
||||||
|
{
|
||||||
|
return ImageConversionLosses.AsIsCmyk;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (target != ImageFormat.Jpeg && info.BitsPerSample > 8)
|
||||||
|
{
|
||||||
|
return ImageConversionLosses.AsIsDeepColor;
|
||||||
|
}
|
||||||
|
|
||||||
|
var pixels = (long)info.Width * info.Height;
|
||||||
|
var tooLarge = target == ImageFormat.WebP
|
||||||
|
? pixels > MaxWebPPixels || info.Width > WebPEncoder.MaxDimension || info.Height > WebPEncoder.MaxDimension
|
||||||
|
: pixels > ImageLimits.Default.MaxPixels;
|
||||||
|
|
||||||
|
// What the decoder will ask besides the pixels (a progressive JPEG keeps its coefficients): a file the decoder
|
||||||
|
// would refuse is too large for the conversion, never «not readable» (§4.10).
|
||||||
|
tooLarge |= info.DecodeWorkingBytes > limits.MaxWorkingBytes;
|
||||||
|
return tooLarge ? ImageConversionLosses.AsIsTooLarge : null;
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>Converts <paramref name="source"/> (any format <see cref="ImageDecoder"/> reads) to <paramref name="target"/>.</summary>
|
/// <summary>Converts <paramref name="source"/> (any format <see cref="ImageDecoder"/> reads) to <paramref name="target"/>.</summary>
|
||||||
/// <exception cref="ArgumentException">The target is not JPEG, PNG or WebP.</exception>
|
/// <exception cref="ArgumentException">The target is not JPEG, PNG or WebP.</exception>
|
||||||
/// <exception cref="ImageDecodeException">The source is damaged, too large or in a format Febe does not read.</exception>
|
/// <exception cref="ImageDecodeException">The source is damaged, too large or in a format Febe does not read.</exception>
|
||||||
@@ -85,8 +234,58 @@ public static class ImageConverter
|
|||||||
lossy = true;
|
lossy = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
var metadata = info.Metadata;
|
var losses = new HashSet<string>(StringComparer.Ordinal);
|
||||||
|
var data = EncodeCore(image, target, info.Metadata, options, notCarried, losses, out var written);
|
||||||
|
return new ImageConversionResult(data, info.Format, target, image.Width, image.Height, lossy, written, notCarried, Ordered(losses));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Writes <paramref name="image"/> (straight RGBA) as <paramref name="target"/> with what of
|
||||||
|
/// <paramref name="metadata"/> the target can carry (none when null: the frames of tappa E3). A transparent image
|
||||||
|
/// to JPEG is first flattened over the background of the options, on a copy: <paramref name="image"/> is never
|
||||||
|
/// changed.
|
||||||
|
/// </summary>
|
||||||
|
/// <exception cref="ArgumentException">The target is not JPEG, PNG or WebP, or a WebP side is over 16384.</exception>
|
||||||
|
public static byte[] Encode(RgbaImage image, ImageFormat target, ImageMetadata? metadata, ImageConversionOptions? options = null)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(image);
|
||||||
|
if (!CanWrite(target))
|
||||||
|
{
|
||||||
|
throw new ArgumentException($"Febe non scrive immagini {target.ToString().ToUpperInvariant()}.", nameof(target));
|
||||||
|
}
|
||||||
|
|
||||||
|
options ??= ImageConversionOptions.Default;
|
||||||
|
if (target == ImageFormat.Jpeg && !image.IsOpaque())
|
||||||
|
{
|
||||||
|
using var copy = new RgbaImage(image.Width, image.Height, image.ToArray());
|
||||||
|
return EncodeCore(copy, target, metadata ?? ImageMetadata.Empty, options, [], new HashSet<string>(StringComparer.Ordinal), out _);
|
||||||
|
}
|
||||||
|
|
||||||
|
return EncodeCore(image, target, metadata ?? ImageMetadata.Empty, options, [], new HashSet<string>(StringComparer.Ordinal), out _);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The codes of <paramref name="losses"/> in the order of <see cref="ImageConversionLosses.Order"/>.</summary>
|
||||||
|
private static string[] Ordered(HashSet<string> losses) =>
|
||||||
|
[.. ImageConversionLosses.Order.Where(losses.Contains)];
|
||||||
|
|
||||||
|
/// <summary>Encodes; flattens <paramref name="image"/> in place for a JPEG target that is not opaque.</summary>
|
||||||
|
private static byte[] EncodeCore(
|
||||||
|
RgbaImage image,
|
||||||
|
ImageFormat target,
|
||||||
|
ImageMetadata metadata,
|
||||||
|
ImageConversionOptions options,
|
||||||
|
List<string> notCarried,
|
||||||
|
HashSet<string> losses,
|
||||||
|
out ImageMetadata written)
|
||||||
|
{
|
||||||
var exif = metadata.Exif;
|
var exif = metadata.Exif;
|
||||||
|
if (exif is not null && !ExifOrientation.IsTiff(exif))
|
||||||
|
{
|
||||||
|
notCarried.Add("l'EXIF (rovinato: non è una struttura TIFF leggibile)");
|
||||||
|
losses.Add(ImageConversionLosses.LostExifUnreadable);
|
||||||
|
exif = OrientationOnly(metadata);
|
||||||
|
}
|
||||||
|
|
||||||
var icc = metadata.IccProfile;
|
var icc = metadata.IccProfile;
|
||||||
var iccName = metadata.IccProfileName;
|
var iccName = metadata.IccProfileName;
|
||||||
if (icc is not null && IccColorSpace(icc) != "RGB ")
|
if (icc is not null && IccColorSpace(icc) != "RGB ")
|
||||||
@@ -97,6 +296,7 @@ public static class ImageConverter
|
|||||||
"GRAY" => "il profilo colore in scala di grigi (i pixel sono scritti in RGB)",
|
"GRAY" => "il profilo colore in scala di grigi (i pixel sono scritti in RGB)",
|
||||||
_ => "il profilo colore (non descrive pixel RGB)",
|
_ => "il profilo colore (non descrive pixel RGB)",
|
||||||
});
|
});
|
||||||
|
losses.Add(ImageConversionLosses.LostIcc);
|
||||||
icc = null;
|
icc = null;
|
||||||
iccName = null;
|
iccName = null;
|
||||||
}
|
}
|
||||||
@@ -104,23 +304,49 @@ public static class ImageConverter
|
|||||||
foreach (var chunk in metadata.ColorChunks)
|
foreach (var chunk in metadata.ColorChunks)
|
||||||
{
|
{
|
||||||
notCarried.Add($"il blocco di colore {chunk} del PNG (non viene scritto)");
|
notCarried.Add($"il blocco di colore {chunk} del PNG (non viene scritto)");
|
||||||
|
losses.Add(ImageConversionLosses.LostColorChunks);
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach (var block in metadata.Unread)
|
||||||
|
{
|
||||||
|
switch (block)
|
||||||
|
{
|
||||||
|
case "APP13":
|
||||||
|
notCarried.Add("i dati IPTC (segmento APP13)");
|
||||||
|
losses.Add(ImageConversionLosses.LostIptc);
|
||||||
|
break;
|
||||||
|
case "ExtendedXmp":
|
||||||
|
notCarried.Add("l'XMP esteso");
|
||||||
|
losses.Add(ImageConversionLosses.LostExtendedXmp);
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
notCarried.Add($"il blocco {block}");
|
||||||
|
losses.Add(ImageConversionLosses.LostOtherSegments);
|
||||||
|
break;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
var xmp = metadata.Xmp;
|
var xmp = metadata.Xmp;
|
||||||
var texts = metadata.Texts;
|
var texts = metadata.Texts;
|
||||||
|
IReadOnlyList<ImageText> writtenTexts = texts;
|
||||||
byte[] data;
|
byte[] data;
|
||||||
switch (target)
|
switch (target)
|
||||||
{
|
{
|
||||||
case ImageFormat.Png:
|
case ImageFormat.Png:
|
||||||
data = PngEncoder.Encode(image, new PngEncoderOptions
|
|
||||||
{
|
{
|
||||||
Exif = exif,
|
var pngTexts = PngTexts(texts, notCarried, losses);
|
||||||
IccProfile = icc,
|
writtenTexts = pngTexts;
|
||||||
IccProfileName = ValidIccName(iccName) ?? PngEncoderOptions.Default.IccProfileName,
|
data = PngEncoder.Encode(image, new PngEncoderOptions
|
||||||
Xmp = xmp,
|
{
|
||||||
Texts = PngTexts(texts, notCarried),
|
Exif = exif,
|
||||||
});
|
IccProfile = icc,
|
||||||
break;
|
IccProfileName = ValidIccName(iccName) ?? PngEncoderOptions.Default.IccProfileName,
|
||||||
|
Xmp = xmp,
|
||||||
|
Texts = pngTexts,
|
||||||
|
});
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
case ImageFormat.WebP:
|
case ImageFormat.WebP:
|
||||||
if (image.Width > WebPEncoder.MaxDimension || image.Height > WebPEncoder.MaxDimension)
|
if (image.Width > WebPEncoder.MaxDimension || image.Height > WebPEncoder.MaxDimension)
|
||||||
{
|
{
|
||||||
@@ -130,8 +356,10 @@ public static class ImageConverter
|
|||||||
if (texts.Count > 0)
|
if (texts.Count > 0)
|
||||||
{
|
{
|
||||||
notCarried.Add(texts.Count == 1 ? "un testo (WebP non ne ha)" : $"{texts.Count} testi (WebP non ne ha)");
|
notCarried.Add(texts.Count == 1 ? "un testo (WebP non ne ha)" : $"{texts.Count} testi (WebP non ne ha)");
|
||||||
|
losses.Add(ImageConversionLosses.LostTexts);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
writtenTexts = [];
|
||||||
data = WebPEncoder.Encode(image, new WebPEncoderOptions { Exif = exif, IccProfile = icc, Xmp = xmp });
|
data = WebPEncoder.Encode(image, new WebPEncoderOptions { Exif = exif, IccProfile = icc, Xmp = xmp });
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
@@ -139,25 +367,47 @@ public static class ImageConverter
|
|||||||
if (exif is not null && exif.Length > JpegMaxSegmentPayload - 6)
|
if (exif is not null && exif.Length > JpegMaxSegmentPayload - 6)
|
||||||
{
|
{
|
||||||
notCarried.Add($"l'EXIF ({exif.Length} byte, più di quanto entra in un segmento JPEG)");
|
notCarried.Add($"l'EXIF ({exif.Length} byte, più di quanto entra in un segmento JPEG)");
|
||||||
exif = null;
|
losses.Add(ImageConversionLosses.LostExifTooLarge);
|
||||||
|
exif = OrientationOnly(metadata);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (xmp is not null && Encoding.UTF8.GetByteCount(xmp) > JpegMaxSegmentPayload - 29)
|
if (xmp is not null && Encoding.UTF8.GetByteCount(xmp) > JpegMaxSegmentPayload - 29)
|
||||||
{
|
{
|
||||||
notCarried.Add("l'XMP (più di quanto entra in un segmento JPEG)");
|
notCarried.Add("l'XMP (più di quanto entra in un segmento JPEG)");
|
||||||
|
losses.Add(ImageConversionLosses.LostXmpTooLarge);
|
||||||
xmp = null;
|
xmp = null;
|
||||||
}
|
}
|
||||||
|
|
||||||
var comments = new List<string>();
|
if (icc is not null && (icc.Length + JpegIccChunk - 1) / JpegIccChunk > 255)
|
||||||
foreach (var text in texts)
|
|
||||||
{
|
{
|
||||||
comments.Add(text.Keyword.Length == 0 || text.Keyword == "Comment" ? text.Text : $"{text.Keyword}: {text.Text}");
|
notCarried.Add($"il profilo colore ({icc.Length} byte, più di quanto entra in 255 segmenti JPEG)");
|
||||||
|
losses.Add(ImageConversionLosses.LostIccTooLarge);
|
||||||
|
icc = null;
|
||||||
|
iccName = null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var comments = new List<string>();
|
||||||
|
var kept = new List<ImageText>();
|
||||||
|
foreach (var text in texts)
|
||||||
|
{
|
||||||
|
var comment = text.Keyword.Length == 0 || text.Keyword == "Comment" ? text.Text : $"{text.Keyword}: {text.Text}";
|
||||||
|
if (Encoding.UTF8.GetByteCount(comment) > JpegMaxSegmentPayload)
|
||||||
|
{
|
||||||
|
notCarried.Add("un commento (più lungo di quanto entra in un segmento JPEG)");
|
||||||
|
losses.Add(ImageConversionLosses.LostCommentTooLarge);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
comments.Add(comment);
|
||||||
|
kept.Add(text);
|
||||||
|
}
|
||||||
|
|
||||||
|
writtenTexts = kept;
|
||||||
if (!image.IsOpaque())
|
if (!image.IsOpaque())
|
||||||
{
|
{
|
||||||
ImageBackground.Flatten(image, options.JpegBackground);
|
ImageBackground.Flatten(image, options.JpegBackground);
|
||||||
notCarried.Add("la trasparenza (JPEG non ce l'ha: le parti trasparenti diventano dello sfondo)");
|
notCarried.Add("la trasparenza (JPEG non ce l'ha: le parti trasparenti diventano dello sfondo)");
|
||||||
|
losses.Add(ImageConversionLosses.TransparencyWhite);
|
||||||
}
|
}
|
||||||
|
|
||||||
data = JpegEncoder.Encode(image, new JpegEncoderOptions
|
data = JpegEncoder.Encode(image, new JpegEncoderOptions
|
||||||
@@ -173,18 +423,28 @@ public static class ImageConverter
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
var written = new ImageMetadata
|
written = new ImageMetadata
|
||||||
{
|
{
|
||||||
Exif = exif,
|
Exif = exif,
|
||||||
Orientation = metadata.Orientation,
|
Orientation = exif is null ? 1 : metadata.Orientation,
|
||||||
IccProfile = icc,
|
IccProfile = icc,
|
||||||
IccProfileName = icc is null ? null : iccName,
|
IccProfileName = icc is null ? null : iccName,
|
||||||
Xmp = xmp,
|
Xmp = xmp,
|
||||||
Texts = target == ImageFormat.WebP ? [] : texts,
|
Texts = writtenTexts,
|
||||||
};
|
};
|
||||||
return new ImageConversionResult(data, info.Format, target, image.Width, image.Height, lossy, written, notCarried);
|
return data;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// In place of an EXIF block left behind, the smallest one that keeps its orientation (in the source's byte order),
|
||||||
|
/// or null when the orientation is 1: the pixels are never turned (§4.10), so without the tag the picture would
|
||||||
|
/// show turned. The loss stays in the notes.
|
||||||
|
/// </summary>
|
||||||
|
private static byte[]? OrientationOnly(ImageMetadata metadata) =>
|
||||||
|
metadata.Orientation is > 1 and <= 8
|
||||||
|
? ExifOrientation.Minimal(metadata.Orientation, metadata.Exif is not { Length: > 0 } e || e[0] != (byte)'M')
|
||||||
|
: null;
|
||||||
|
|
||||||
/// <summary>The data colour space of an ICC profile (bytes 16-19 of its header: «RGB », «GRAY», «CMYK»...), or null.</summary>
|
/// <summary>The data colour space of an ICC profile (bytes 16-19 of its header: «RGB », «GRAY», «CMYK»...), or null.</summary>
|
||||||
internal static string? IccColorSpace(ReadOnlySpan<byte> profile)
|
internal static string? IccColorSpace(ReadOnlySpan<byte> profile)
|
||||||
{
|
{
|
||||||
@@ -211,6 +471,9 @@ public static class ImageConverter
|
|||||||
/// <summary>Bytes of payload in one JPEG marker segment (65535 less the two of the length).</summary>
|
/// <summary>Bytes of payload in one JPEG marker segment (65535 less the two of the length).</summary>
|
||||||
private const int JpegMaxSegmentPayload = 65533;
|
private const int JpegMaxSegmentPayload = 65533;
|
||||||
|
|
||||||
|
/// <summary>Bytes of an ICC profile in one APP2 segment (the payload less «ICC_PROFILE\0» and the two counters).</summary>
|
||||||
|
private const int JpegIccChunk = 65519;
|
||||||
|
|
||||||
private static string? ValidIccName(string? name)
|
private static string? ValidIccName(string? name)
|
||||||
{
|
{
|
||||||
if (string.IsNullOrEmpty(name) || name.Length > 79)
|
if (string.IsNullOrEmpty(name) || name.Length > 79)
|
||||||
@@ -229,7 +492,7 @@ public static class ImageConverter
|
|||||||
return name.Trim().Length == name.Length ? name : null;
|
return name.Trim().Length == name.Length ? name : null;
|
||||||
}
|
}
|
||||||
|
|
||||||
private static List<ImageText> PngTexts(IReadOnlyList<ImageText> texts, List<string> notCarried)
|
private static List<ImageText> PngTexts(IReadOnlyList<ImageText> texts, List<string> notCarried, HashSet<string> losses)
|
||||||
{
|
{
|
||||||
var result = new List<ImageText>(texts.Count);
|
var result = new List<ImageText>(texts.Count);
|
||||||
foreach (var text in texts)
|
foreach (var text in texts)
|
||||||
@@ -238,6 +501,7 @@ public static class ImageConverter
|
|||||||
if (!PngEncoder.IsValidKeyword(keyword))
|
if (!PngEncoder.IsValidKeyword(keyword))
|
||||||
{
|
{
|
||||||
notCarried.Add($"il testo «{keyword}» (nome non valido per un PNG)");
|
notCarried.Add($"il testo «{keyword}» (nome non valido per un PNG)");
|
||||||
|
losses.Add(ImageConversionLosses.LostTexts);
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -248,6 +512,7 @@ public static class ImageConverter
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
/// <summary>Composites an image over a plain colour.</summary>
|
/// <summary>Composites an image over a plain colour.</summary>
|
||||||
public static class ImageBackground
|
public static class ImageBackground
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -39,6 +39,13 @@ public sealed class ImageMetadata
|
|||||||
/// not applied to the pixels and no encoder writes them, so a conversion says they are left behind.
|
/// not applied to the pixels and no encoder writes them, so a conversion says they are left behind.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public IReadOnlyList<string> ColorChunks { get; init; } = [];
|
public IReadOnlyList<string> ColorChunks { get; init; } = [];
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Blocks of the file that hold data no reader of Febe interprets and no encoder writes, in file order and once
|
||||||
|
/// each: JPEG segments («APP13» for IPTC/Photoshop, «ExtendedXmp», «APP2» for MPF, other «APPn»), PNG ancillary
|
||||||
|
/// chunks («pHYs», «tIME»...), WebP chunks. A conversion reports them as not kept.
|
||||||
|
/// </summary>
|
||||||
|
public IReadOnlyList<string> Unread { get; init; } = [];
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>What a file says about its image, read without decoding the pixels.</summary>
|
/// <summary>What a file says about its image, read without decoding the pixels.</summary>
|
||||||
@@ -55,4 +62,20 @@ public sealed record ImageInfo(ImageFormat Format, int Width, int Height, int Fr
|
|||||||
/// for GIF and WebP). The decoders give 8-bit samples, so above 8 the decoded pixels have lost precision.
|
/// for GIF and WebP). The decoders give 8-bit samples, so above 8 the decoded pixels have lost precision.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public int BitsPerSample { get; init; } = 8;
|
public int BitsPerSample { get; init; } = 8;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Whether the file is an animation, by the presence of its marks (spec §4.10): a PNG with an <c>acTL</c> chunk
|
||||||
|
/// before its image data, a WebP with an <c>ANIM</c> or <c>ANMF</c> chunk, a GIF with more than one image.
|
||||||
|
/// </summary>
|
||||||
|
public bool IsAnimated { get; init; }
|
||||||
|
|
||||||
|
/// <summary>Whether the pixels are stored as CMYK or YCCK (a JPEG with four components).</summary>
|
||||||
|
public bool IsCmyk { get; init; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The working memory a full decode asks besides the decoded image, as the decoder checks it against
|
||||||
|
/// <see cref="ImageLimits.MaxWorkingBytes"/> (a progressive or lossless JPEG keeps its coefficients or samples:
|
||||||
|
/// up to 9 bytes a pixel); 0 when the format's decoder needs none worth counting before it starts.
|
||||||
|
/// </summary>
|
||||||
|
public long DecodeWorkingBytes { get; init; }
|
||||||
}
|
}
|
||||||
@@ -76,6 +76,7 @@ internal sealed partial class JpegFile : IDisposable
|
|||||||
private string? _xmp;
|
private string? _xmp;
|
||||||
private List<(int Sequence, int Count, byte[] Data)>? _iccChunks;
|
private List<(int Sequence, int Count, byte[] Data)>? _iccChunks;
|
||||||
private List<ImageText>? _texts;
|
private List<ImageText>? _texts;
|
||||||
|
private List<string>? _unread;
|
||||||
|
|
||||||
private bool _allocated;
|
private bool _allocated;
|
||||||
private bool _pooledArrays;
|
private bool _pooledArrays;
|
||||||
@@ -320,7 +321,7 @@ internal sealed partial class JpegFile : IDisposable
|
|||||||
public ImageInfo ToInfo()
|
public ImageInfo ToInfo()
|
||||||
{
|
{
|
||||||
var icc = AssembleIcc();
|
var icc = AssembleIcc();
|
||||||
var metadata = _exif is null && icc is null && _xmp is null && _texts is null
|
var metadata = _exif is null && icc is null && _xmp is null && _texts is null && _unread is null
|
||||||
? ImageMetadata.Empty
|
? ImageMetadata.Empty
|
||||||
: new ImageMetadata
|
: new ImageMetadata
|
||||||
{
|
{
|
||||||
@@ -329,8 +330,14 @@ internal sealed partial class JpegFile : IDisposable
|
|||||||
IccProfile = icc,
|
IccProfile = icc,
|
||||||
Xmp = _xmp,
|
Xmp = _xmp,
|
||||||
Texts = _texts ?? [],
|
Texts = _texts ?? [],
|
||||||
|
Unread = _unread ?? [],
|
||||||
};
|
};
|
||||||
return new ImageInfo(ImageFormat.Jpeg, Width, Height, 1, false, metadata) { BitsPerSample = Precision };
|
return new ImageInfo(ImageFormat.Jpeg, Width, Height, 1, false, metadata)
|
||||||
|
{
|
||||||
|
BitsPerSample = Precision,
|
||||||
|
IsCmyk = Components.Length == 4,
|
||||||
|
DecodeWorkingBytes = Height == 0 ? 0 : WorkingBytes(Progressive, 0),
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
public JpegCoefficients ToCoefficients()
|
public JpegCoefficients ToCoefficients()
|
||||||
@@ -476,6 +483,34 @@ internal sealed partial class JpegFile : IDisposable
|
|||||||
|
|
||||||
private static int Ceil(int value, int divisor) => (value + divisor - 1) / divisor;
|
private static int Ceil(int value, int divisor) => (value + divisor - 1) / divisor;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The working memory <see cref="Allocate"/> asks of the limits: the sample planes (reduced by
|
||||||
|
/// <paramref name="scaleShift"/>), the coefficients when kept (a progressive file), the samples of a lossless one.
|
||||||
|
/// </summary>
|
||||||
|
private long WorkingBytes(bool keepCoefficients, int scaleShift)
|
||||||
|
{
|
||||||
|
long bytes = 0;
|
||||||
|
foreach (var c in Components)
|
||||||
|
{
|
||||||
|
var unit = Lossless ? 1 : 8;
|
||||||
|
long samples = (long)c.PaddedUnitsWide * unit * c.PaddedUnitsHigh * unit;
|
||||||
|
bytes += samples >> (2 * scaleShift);
|
||||||
|
if (keepCoefficients && !Lossless)
|
||||||
|
{
|
||||||
|
bytes += samples * 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (Lossless)
|
||||||
|
{
|
||||||
|
// The samples before the point transform, and for arithmetic coding the class of every difference.
|
||||||
|
bytes += samples * (Arithmetic ? 3 : 2);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return bytes;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
private void ReadDnl(ReadOnlySpan<byte> p)
|
private void ReadDnl(ReadOnlySpan<byte> p)
|
||||||
{
|
{
|
||||||
if (p.Length < 2)
|
if (p.Length < 2)
|
||||||
@@ -625,6 +660,12 @@ internal sealed partial class JpegFile : IDisposable
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (marker is not (0xE1 or 0xE2))
|
||||||
|
{
|
||||||
|
NotRead(marker == 0xED ? "APP13" : $"APP{marker - 0xE0}");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
// Damaged or oversized metadata is skipped: it must never stop an image from being shown.
|
// Damaged or oversized metadata is skipped: it must never stop an image from being shown.
|
||||||
if (marker == 0xE1)
|
if (marker == 0xE1)
|
||||||
{
|
{
|
||||||
@@ -644,8 +685,16 @@ internal sealed partial class JpegFile : IDisposable
|
|||||||
_xmp = Encoding.UTF8.GetString(packet);
|
_xmp = Encoding.UTF8.GetString(packet);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
else if (p.StartsWith(ExtendedXmpNamespace))
|
||||||
|
{
|
||||||
|
NotRead("ExtendedXmp");
|
||||||
|
}
|
||||||
|
else if (!(p.Length > 6 && p[..4].SequenceEqual("Exif"u8)) && !p.StartsWith(XmpNamespace))
|
||||||
|
{
|
||||||
|
NotRead("APP1");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
else if (marker == 0xE2 && p.Length > 14 && p[..12].SequenceEqual("ICC_PROFILE\0"u8))
|
else if (p.Length > 14 && p[..12].SequenceEqual("ICC_PROFILE\0"u8))
|
||||||
{
|
{
|
||||||
int sequence = p[12];
|
int sequence = p[12];
|
||||||
int count = p[13];
|
int count = p[13];
|
||||||
@@ -655,6 +704,22 @@ internal sealed partial class JpegFile : IDisposable
|
|||||||
(_iccChunks ??= []).Add((sequence, count, chunk.ToArray()));
|
(_iccChunks ??= []).Add((sequence, count, chunk.ToArray()));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
NotRead("APP2"); // MPF and the like
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The namespace that starts an extended XMP APP1 segment (XMP part 3), with its terminating zero.</summary>
|
||||||
|
private static ReadOnlySpan<byte> ExtendedXmpNamespace => "http://ns.adobe.com/xmp/extension/\0"u8;
|
||||||
|
|
||||||
|
private void NotRead(string name)
|
||||||
|
{
|
||||||
|
_unread ??= [];
|
||||||
|
if (!_unread.Contains(name))
|
||||||
|
{
|
||||||
|
_unread.Add(name);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>The namespace that starts an XMP APP1 segment, with its terminating zero.</summary>
|
/// <summary>The namespace that starts an XMP APP1 segment, with its terminating zero.</summary>
|
||||||
@@ -801,25 +866,7 @@ internal sealed partial class JpegFile : IDisposable
|
|||||||
|
|
||||||
_limits.CheckSize(OutputWidth, OutputHeight);
|
_limits.CheckSize(OutputWidth, OutputHeight);
|
||||||
var keepCoefficients = Progressive || _mode == Mode.Coefficients;
|
var keepCoefficients = Progressive || _mode == Mode.Coefficients;
|
||||||
long bytes = 0;
|
_limits.CheckWorkingBytes(WorkingBytes(keepCoefficients, _scaleShift));
|
||||||
foreach (var c in Components)
|
|
||||||
{
|
|
||||||
var unit = Lossless ? 1 : 8;
|
|
||||||
long samples = (long)c.PaddedUnitsWide * unit * c.PaddedUnitsHigh * unit;
|
|
||||||
bytes += samples >> (2 * _scaleShift);
|
|
||||||
if (keepCoefficients && !Lossless)
|
|
||||||
{
|
|
||||||
bytes += samples * 2;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (Lossless)
|
|
||||||
{
|
|
||||||
// The samples before the point transform, and for arithmetic coding the class of every difference.
|
|
||||||
bytes += samples * (Arithmetic ? 3 : 2);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
_limits.CheckWorkingBytes(bytes);
|
|
||||||
_pooledArrays = _mode == Mode.Pixels;
|
_pooledArrays = _mode == Mode.Pixels;
|
||||||
foreach (var c in Components)
|
foreach (var c in Components)
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -103,6 +103,8 @@ public static class PngDecoder
|
|||||||
public string? Xmp;
|
public string? Xmp;
|
||||||
public List<ImageText>? Texts;
|
public List<ImageText>? Texts;
|
||||||
public List<string>? ColorChunks;
|
public List<string>? ColorChunks;
|
||||||
|
public List<string>? Unread;
|
||||||
|
public bool Animated;
|
||||||
|
|
||||||
public int Channels => ColorType switch { 2 => 3, 4 => 2, 6 => 4, _ => 1 };
|
public int Channels => ColorType switch { 2 => 3, 4 => 2, 6 => 4, _ => 1 };
|
||||||
|
|
||||||
@@ -114,7 +116,7 @@ public static class PngDecoder
|
|||||||
Height,
|
Height,
|
||||||
FrameCount,
|
FrameCount,
|
||||||
ColorType is 4 or 6 || HasColorKey || HasPaletteAlpha,
|
ColorType is 4 or 6 || HasColorKey || HasPaletteAlpha,
|
||||||
Exif is null && Icc is null && Xmp is null && Texts is null && ColorChunks is null
|
Exif is null && Icc is null && Xmp is null && Texts is null && ColorChunks is null && Unread is null
|
||||||
? ImageMetadata.Empty
|
? ImageMetadata.Empty
|
||||||
: new ImageMetadata
|
: new ImageMetadata
|
||||||
{
|
{
|
||||||
@@ -125,9 +127,11 @@ public static class PngDecoder
|
|||||||
Xmp = Xmp,
|
Xmp = Xmp,
|
||||||
Texts = Texts ?? [],
|
Texts = Texts ?? [],
|
||||||
ColorChunks = ColorChunks ?? [],
|
ColorChunks = ColorChunks ?? [],
|
||||||
|
Unread = Unread ?? [],
|
||||||
})
|
})
|
||||||
{
|
{
|
||||||
BitsPerSample = ColorType == 3 ? 8 : BitDepth,
|
BitsPerSample = ColorType == 3 ? 8 : BitDepth,
|
||||||
|
IsAnimated = Animated,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -248,6 +252,7 @@ public static class PngDecoder
|
|||||||
break;
|
break;
|
||||||
|
|
||||||
case "acTL":
|
case "acTL":
|
||||||
|
file.Animated |= idatState == 0;
|
||||||
if (payload.Length >= 8 && idatState == 0)
|
if (payload.Length >= 8 && idatState == 0)
|
||||||
{
|
{
|
||||||
var frames = BinaryPrimitives.ReadUInt32BigEndian(payload);
|
var frames = BinaryPrimitives.ReadUInt32BigEndian(payload);
|
||||||
@@ -272,12 +277,20 @@ public static class PngDecoder
|
|||||||
|
|
||||||
break;
|
break;
|
||||||
|
|
||||||
|
case "fcTL" or "fdAT":
|
||||||
|
break;
|
||||||
|
|
||||||
default:
|
default:
|
||||||
if (critical)
|
if (critical)
|
||||||
{
|
{
|
||||||
throw new ImageFormatNotSupportedException($"PNG con un blocco critico che Febe non conosce ({name}).");
|
throw new ImageFormatNotSupportedException($"PNG con un blocco critico che Febe non conosce ({name}).");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (readMetadata && !(file.Unread ??= []).Contains(name))
|
||||||
|
{
|
||||||
|
file.Unread.Add(name);
|
||||||
|
}
|
||||||
|
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -576,7 +576,7 @@ internal static class Vp8LEncoder
|
|||||||
private static int ChooseCacheBits(uint[] pixels, ReadOnlySpan<int> lengths)
|
private static int ChooseCacheBits(uint[] pixels, ReadOnlySpan<int> lengths)
|
||||||
{
|
{
|
||||||
var bestBits = 0;
|
var bestBits = 0;
|
||||||
var bestCost = double.MaxValue;
|
var bestCost = long.MaxValue;
|
||||||
var green = new int[256 + NumLengthCodes + (1 << 10)];
|
var green = new int[256 + NumLengthCodes + (1 << 10)];
|
||||||
var red = new int[256];
|
var red = new int[256];
|
||||||
var blue = new int[256];
|
var blue = new int[256];
|
||||||
@@ -637,8 +637,10 @@ internal static class Vp8LEncoder
|
|||||||
return bestBits;
|
return bestBits;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Bits to code the counts with an ideal code, plus a rough price for describing the code.
|
// Bits to code the counts with an ideal code, plus a rough price for describing the code, in units of
|
||||||
private static double Entropy(ReadOnlySpan<int> counts)
|
// 2^-LogFractionBits bits: Σ c·log2(total / c) = total·log2(total) − Σ c·log2(c), in integers only, so that the
|
||||||
|
// choice never depends on the floating-point library of the platform (decision D9 of tappa E3).
|
||||||
|
internal static long Entropy(ReadOnlySpan<int> counts)
|
||||||
{
|
{
|
||||||
long total = 0;
|
long total = 0;
|
||||||
var used = 0;
|
var used = 0;
|
||||||
@@ -650,19 +652,66 @@ internal static class Vp8LEncoder
|
|||||||
|
|
||||||
if (used <= 1)
|
if (used <= 1)
|
||||||
{
|
{
|
||||||
return 8;
|
return 8L << LogFractionBits;
|
||||||
}
|
}
|
||||||
|
|
||||||
var bits = 0.0;
|
var bits = total * Log2Fixed((ulong)total);
|
||||||
foreach (var c in counts)
|
foreach (var c in counts)
|
||||||
{
|
{
|
||||||
if (c > 0)
|
if (c > 0)
|
||||||
{
|
{
|
||||||
bits -= c * Math.Log2((double)c / total);
|
bits -= c * Log2Fixed((ulong)c);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return bits + (used * 4.0);
|
return bits + ((long)used * 4 << LogFractionBits);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Fractional bits of <see cref="Log2Fixed"/>.</summary>
|
||||||
|
internal const int LogFractionBits = 16;
|
||||||
|
|
||||||
|
/// <summary>Base-2 logarithms of 1-4095 in fixed point, computed once by <see cref="Log2Exact"/>.</summary>
|
||||||
|
private static readonly long[] SmallLog2 = BuildSmallLog2();
|
||||||
|
|
||||||
|
private static long[] BuildSmallLog2()
|
||||||
|
{
|
||||||
|
var table = new long[4096];
|
||||||
|
for (var i = 1; i < table.Length; i++)
|
||||||
|
{
|
||||||
|
table[i] = Log2Exact((ulong)i);
|
||||||
|
}
|
||||||
|
|
||||||
|
return table;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>log2(<paramref name="value"/>) in fixed point with <see cref="LogFractionBits"/> fractional bits; 0 for 0.</summary>
|
||||||
|
internal static long Log2Fixed(ulong value) => value < (ulong)SmallLog2.Length ? SmallLog2[value] : Log2Exact(value);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// log2 by integers only: the integer part from the highest bit, the fraction bit by bit by repeated squaring of
|
||||||
|
/// the mantissa (kept as a 1.31 fixed-point number), rounded down.
|
||||||
|
/// </summary>
|
||||||
|
private static long Log2Exact(ulong value)
|
||||||
|
{
|
||||||
|
if (value == 0)
|
||||||
|
{
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
var high = 63 - System.Numerics.BitOperations.LeadingZeroCount(value);
|
||||||
|
ulong mantissa = high >= 31 ? value >> (high - 31) : value << (31 - high); // in [2^31, 2^32): 1.0 ≤ m < 2.0
|
||||||
|
long fraction = 0;
|
||||||
|
for (var bit = LogFractionBits - 1; bit >= 0; bit--)
|
||||||
|
{
|
||||||
|
mantissa = (mantissa * mantissa) >> 31;
|
||||||
|
if (mantissa >= 1UL << 32)
|
||||||
|
{
|
||||||
|
mantissa >>= 1;
|
||||||
|
fraction |= 1L << bit;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return ((long)high << LogFractionBits) | fraction;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Writes a prefix code: the simple form for at most two symbols below 256, otherwise the code lengths, run-length
|
// Writes a prefix code: the simple form for at most two symbols below 256, otherwise the code lengths, run-length
|
||||||
|
|||||||
@@ -96,6 +96,8 @@ public static class WebPDecoder
|
|||||||
public byte[]? Exif;
|
public byte[]? Exif;
|
||||||
public byte[]? Icc;
|
public byte[]? Icc;
|
||||||
public string? Xmp;
|
public string? Xmp;
|
||||||
|
public bool Animated;
|
||||||
|
public List<string>? Unread;
|
||||||
|
|
||||||
public ImageInfo ToInfo() => new(
|
public ImageInfo ToInfo() => new(
|
||||||
ImageFormat.WebP,
|
ImageFormat.WebP,
|
||||||
@@ -103,9 +105,12 @@ public static class WebPDecoder
|
|||||||
Height,
|
Height,
|
||||||
FrameCount,
|
FrameCount,
|
||||||
HasAlpha,
|
HasAlpha,
|
||||||
Exif is null && Icc is null && Xmp is null
|
Exif is null && Icc is null && Xmp is null && Unread is null
|
||||||
? ImageMetadata.Empty
|
? ImageMetadata.Empty
|
||||||
: new ImageMetadata { Exif = Exif, Orientation = Exif is null ? 1 : ExifOrientation.Read(Exif), IccProfile = Icc, Xmp = Xmp });
|
: new ImageMetadata { Exif = Exif, Orientation = Exif is null ? 1 : ExifOrientation.Read(Exif), IccProfile = Icc, Xmp = Xmp, Unread = Unread ?? [] })
|
||||||
|
{
|
||||||
|
IsAnimated = Animated,
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
private static WebPFile Parse(byte[] data, int offset, int length, ImageLimits limits, bool readMetadata)
|
private static WebPFile Parse(byte[] data, int offset, int length, ImageLimits limits, bool readMetadata)
|
||||||
@@ -174,7 +179,11 @@ public static class WebPDecoder
|
|||||||
var chunk = chunks[i];
|
var chunk = chunks[i];
|
||||||
switch (chunk.Type)
|
switch (chunk.Type)
|
||||||
{
|
{
|
||||||
|
case Anim:
|
||||||
|
file.Animated = true;
|
||||||
|
break;
|
||||||
case Anmf:
|
case Anmf:
|
||||||
|
file.Animated = true;
|
||||||
if (frames++ == 0)
|
if (frames++ == 0)
|
||||||
{
|
{
|
||||||
file.FirstFrame = ReadFrame(data, chunk, file.Width, file.Height);
|
file.FirstFrame = ReadFrame(data, chunk, file.Width, file.Height);
|
||||||
@@ -200,6 +209,25 @@ public static class WebPDecoder
|
|||||||
case Xmp when readMetadata && file.Xmp is null && chunk.Length <= budget:
|
case Xmp when readMetadata && file.Xmp is null && chunk.Length <= budget:
|
||||||
file.Xmp = Encoding.UTF8.GetString(data, chunk.Start, chunk.Length);
|
file.Xmp = Encoding.UTF8.GetString(data, chunk.Start, chunk.Length);
|
||||||
budget -= chunk.Length;
|
budget -= chunk.Length;
|
||||||
|
break;
|
||||||
|
case Iccp or Exif or Xmp:
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
if (readMetadata)
|
||||||
|
{
|
||||||
|
var name = string.Create(4, chunk.Type, static (c, t) =>
|
||||||
|
{
|
||||||
|
for (var k = 0; k < 4; k++)
|
||||||
|
{
|
||||||
|
c[k] = (char)(byte)(t >> (8 * k));
|
||||||
|
}
|
||||||
|
}).TrimEnd();
|
||||||
|
if (!(file.Unread ??= []).Contains(name))
|
||||||
|
{
|
||||||
|
file.Unread.Add(name);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,87 @@
|
|||||||
|
using System.Security.Cryptography;
|
||||||
|
using Febe.Core.Domain;
|
||||||
|
using Febe.Core.Library;
|
||||||
|
using Febe.Core.Library.Conversion;
|
||||||
|
|
||||||
|
namespace Febe.Core.Export;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The conversion of a library file for a copy (tappa E3, WP1.6b): <see cref="MediaConverter"/> with the files of the
|
||||||
|
/// export environment, and the hash of content that is only known once written (a remux).
|
||||||
|
/// </summary>
|
||||||
|
internal static class ExportConversion
|
||||||
|
{
|
||||||
|
/// <summary>Prepares the library file at <paramref name="source"/> in <paramref name="target"/> (never Original).</summary>
|
||||||
|
/// <exception cref="ContentChangedException">A photo's bytes are not those of <paramref name="sha256"/>.</exception>
|
||||||
|
public static Task<MediaConversionResult> PrepareAsync(ExportEnvironment env, string source, Media media, ExportFormat target, string sha256, CancellationToken ct) =>
|
||||||
|
MediaConverter.PrepareAsync(() => env.FileSystem.OpenRandomAccess(source), media.RelativePath!, media.Kind, target, sha256, env.Throttle, ct);
|
||||||
|
|
||||||
|
/// <summary>The SHA-256 (lowercase hex) and length of what <paramref name="produce"/> writes, written nowhere.</summary>
|
||||||
|
public static async Task<(string Sha256, long Length)> HashAsync(Func<Stream, CancellationToken, Task> produce, CancellationToken ct)
|
||||||
|
{
|
||||||
|
await using var sink = new HashingSink();
|
||||||
|
await produce(sink, ct).ConfigureAwait(false);
|
||||||
|
return (sink.Finish(), sink.Length);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>A stream that only hashes and counts what is written to it.</summary>
|
||||||
|
private sealed class HashingSink : Stream
|
||||||
|
{
|
||||||
|
private readonly IncrementalHash hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256);
|
||||||
|
private long length;
|
||||||
|
|
||||||
|
public override bool CanRead => false;
|
||||||
|
|
||||||
|
public override bool CanSeek => false;
|
||||||
|
|
||||||
|
public override bool CanWrite => true;
|
||||||
|
|
||||||
|
public override long Length => length;
|
||||||
|
|
||||||
|
public override long Position
|
||||||
|
{
|
||||||
|
get => length;
|
||||||
|
set => throw new NotSupportedException();
|
||||||
|
}
|
||||||
|
|
||||||
|
public string Finish() => Convert.ToHexStringLower(hash.GetHashAndReset());
|
||||||
|
|
||||||
|
public override void Write(byte[] buffer, int offset, int count) => Write(buffer.AsSpan(offset, count));
|
||||||
|
|
||||||
|
public override void Write(ReadOnlySpan<byte> buffer)
|
||||||
|
{
|
||||||
|
hash.AppendData(buffer);
|
||||||
|
length += buffer.Length;
|
||||||
|
}
|
||||||
|
|
||||||
|
public override ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
cancellationToken.ThrowIfCancellationRequested();
|
||||||
|
Write(buffer.Span);
|
||||||
|
return ValueTask.CompletedTask;
|
||||||
|
}
|
||||||
|
|
||||||
|
public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) =>
|
||||||
|
WriteAsync(buffer.AsMemory(offset, count), cancellationToken).AsTask();
|
||||||
|
|
||||||
|
public override void Flush()
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
public override int Read(byte[] buffer, int offset, int count) => throw new NotSupportedException();
|
||||||
|
|
||||||
|
public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException();
|
||||||
|
|
||||||
|
public override void SetLength(long value) => throw new NotSupportedException();
|
||||||
|
|
||||||
|
protected override void Dispose(bool disposing)
|
||||||
|
{
|
||||||
|
if (disposing)
|
||||||
|
{
|
||||||
|
hash.Dispose();
|
||||||
|
}
|
||||||
|
|
||||||
|
base.Dispose(disposing);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,99 @@
|
|||||||
|
using Febe.Core.Domain;
|
||||||
|
using Febe.Core.Library.Conversion;
|
||||||
|
|
||||||
|
namespace Febe.Core.Export;
|
||||||
|
|
||||||
|
/// <summary>What the plan expects of a file in a format, from its name only (tappa E3: the copy decides on the bytes).</summary>
|
||||||
|
public enum ExportPrediction
|
||||||
|
{
|
||||||
|
/// <summary>Copied byte for byte: Original, or already in the format asked.</summary>
|
||||||
|
Whole,
|
||||||
|
|
||||||
|
/// <summary>Converted into the format asked.</summary>
|
||||||
|
Converted,
|
||||||
|
|
||||||
|
/// <summary>Copied as it is with a note (HEIC, AVIF, raw, GIF, WebM).</summary>
|
||||||
|
AsIs,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The format of a copy (spec §4.10 «Conversione del formato», decisions D1, D2 and D5-D7 of tappa E3): which format a
|
||||||
|
/// file gets in a destination, and what the plan predicts of it from its name.
|
||||||
|
/// </summary>
|
||||||
|
public static class ExportConversions
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// The format of a file of <paramref name="kind"/>: the «Copia in…» override of this request, else the destination's,
|
||||||
|
/// else the general settings' (D1). A value that does not belong to the kind counts as not set.
|
||||||
|
/// </summary>
|
||||||
|
public static ExportFormat Resolve(MediaKind kind, ExportFormatChoice? request, ExportDestination destination, ExportSettings settings)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(destination);
|
||||||
|
ArgumentNullException.ThrowIfNull(settings);
|
||||||
|
Func<ExportFormat, bool> fits = kind == MediaKind.Photo ? ExportFormats.IsPhotoFormat : ExportFormats.IsVideoFormat;
|
||||||
|
var chosen = kind == MediaKind.Photo
|
||||||
|
? new[] { request?.Photo, destination.PhotoFormat, settings.PhotoFormat }
|
||||||
|
: [request?.Video, destination.VideoFormat, settings.VideoFormat];
|
||||||
|
foreach (var format in chosen)
|
||||||
|
{
|
||||||
|
if (format is { } f && fits(f))
|
||||||
|
{
|
||||||
|
return f;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return ExportFormat.Original;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The variant a format asks for: Whole for Original, Converted otherwise.</summary>
|
||||||
|
public static ExportVariant VariantOf(ExportFormat format) => format == ExportFormat.Original ? ExportVariant.Whole : ExportVariant.Converted;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// What the plan expects, by extension («circa»): Original, or the same format (<c>.jpg/.jpeg</c>, <c>.png</c>,
|
||||||
|
/// <c>.webp</c>, <c>.mp4</c>) → Whole; HEIC, HEIF, AVIF, raw, GIF and WebM → AsIs; anything else → Converted.
|
||||||
|
/// </summary>
|
||||||
|
public static ExportPrediction Predict(string relativePath, MediaKind kind, ExportFormat target)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(relativePath);
|
||||||
|
if (target == ExportFormat.Original)
|
||||||
|
{
|
||||||
|
return ExportPrediction.Whole;
|
||||||
|
}
|
||||||
|
|
||||||
|
var extension = Path.GetExtension(relativePath).ToLowerInvariant();
|
||||||
|
var same = target switch
|
||||||
|
{
|
||||||
|
ExportFormat.Jpg => extension is ".jpg" or ".jpeg",
|
||||||
|
ExportFormat.Png => extension == ".png",
|
||||||
|
ExportFormat.WebpLossless => extension == ".webp",
|
||||||
|
ExportFormat.Mp4 => extension == ".mp4",
|
||||||
|
_ => false,
|
||||||
|
};
|
||||||
|
if (same)
|
||||||
|
{
|
||||||
|
return ExportPrediction.Whole;
|
||||||
|
}
|
||||||
|
|
||||||
|
return AsIsLabel(relativePath) is not null ? ExportPrediction.AsIs : ExportPrediction.Converted;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The kind of a file copied as it is, for «3 HEIC copiati come sono»: «HEIC», «AVIF», «raw», «GIF», «WebM»; null otherwise.</summary>
|
||||||
|
public static string? AsIsLabel(string relativePath)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(relativePath);
|
||||||
|
var extension = Path.GetExtension(relativePath).ToLowerInvariant();
|
||||||
|
return extension switch
|
||||||
|
{
|
||||||
|
".heic" or ".heif" => "HEIC",
|
||||||
|
".avif" => "AVIF",
|
||||||
|
".gif" => "GIF",
|
||||||
|
".webm" => "WebM",
|
||||||
|
_ when MediaConverter.IsRawExtension(extension) => "raw",
|
||||||
|
_ => null,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The effective identity the plan expects (D2): (Converted, format) when predicted converted, else (Whole, Original).</summary>
|
||||||
|
public static (ExportVariant Variant, ExportFormat Format) PredictedIdentity(string relativePath, MediaKind kind, ExportFormat target) =>
|
||||||
|
Predict(relativePath, kind, target) == ExportPrediction.Converted ? (ExportVariant.Converted, target) : (ExportVariant.Whole, ExportFormat.Original);
|
||||||
|
}
|
||||||
@@ -15,6 +15,8 @@ namespace Febe.Core.Export;
|
|||||||
/// <param name="ProfileNamingScheme">Scheme of profile pictures; null: «Come la libreria».</param>
|
/// <param name="ProfileNamingScheme">Scheme of profile pictures; null: «Come la libreria».</param>
|
||||||
/// <param name="Automatic">«Automatica»: stored only in tappa E2 (tappa E5 acts on it).</param>
|
/// <param name="Automatic">«Automatica»: stored only in tappa E2 (tappa E5 acts on it).</param>
|
||||||
/// <param name="OnlyNew">«Solo i nuovi» when «Automatica» is turned on.</param>
|
/// <param name="OnlyNew">«Solo i nuovi» when «Automatica» is turned on.</param>
|
||||||
|
/// <param name="PhotoFormat">Format of the copies of photos here; null: «Come le impostazioni generali» (tappa E3, D1).</param>
|
||||||
|
/// <param name="VideoFormat">Format of the copies of videos here (Original or Mp4); null: «Come le impostazioni generali».</param>
|
||||||
public sealed record DestinationSpec(
|
public sealed record DestinationSpec(
|
||||||
ExportScope Scope,
|
ExportScope Scope,
|
||||||
long? AccountId,
|
long? AccountId,
|
||||||
@@ -25,7 +27,9 @@ public sealed record DestinationSpec(
|
|||||||
string? HighlightNamingScheme,
|
string? HighlightNamingScheme,
|
||||||
string? ProfileNamingScheme,
|
string? ProfileNamingScheme,
|
||||||
bool Automatic = false,
|
bool Automatic = false,
|
||||||
bool OnlyNew = true);
|
bool OnlyNew = true,
|
||||||
|
ExportFormat? PhotoFormat = null,
|
||||||
|
ExportFormat? VideoFormat = null);
|
||||||
|
|
||||||
/// <summary>A saved destination and the warnings of its naming schemes (shown, they do not block).</summary>
|
/// <summary>A saved destination and the warnings of its naming schemes (shown, they do not block).</summary>
|
||||||
public sealed record DestinationSaveResult(ExportDestination Destination, IReadOnlyList<string> Warnings);
|
public sealed record DestinationSaveResult(ExportDestination Destination, IReadOnlyList<string> Warnings);
|
||||||
@@ -347,6 +351,17 @@ public sealed class ExportDestinations(ExportEnvironment env)
|
|||||||
throw new ArgumentException("Scegli almeno un tipo di contenuto.", nameof(spec));
|
throw new ArgumentException("Scegli almeno un tipo di contenuto.", nameof(spec));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// A change of format is not a new folder: the copies already made stay «già copiato» (D3 of tappa E3).
|
||||||
|
if (spec.PhotoFormat is { } photo && !ExportFormats.IsPhotoFormat(photo))
|
||||||
|
{
|
||||||
|
throw new ArgumentException("Per le foto si sceglie Originale, JPG, PNG o WEBP senza perdita.", nameof(spec));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (spec.VideoFormat is { } video && !ExportFormats.IsVideoFormat(video))
|
||||||
|
{
|
||||||
|
throw new ArgumentException("Per i video si sceglie Originale o MP4.", nameof(spec));
|
||||||
|
}
|
||||||
|
|
||||||
var errors = new List<string>();
|
var errors = new List<string>();
|
||||||
var warnings = new List<string>();
|
var warnings = new List<string>();
|
||||||
void Check(string? text, NamingSchemeUse use)
|
void Check(string? text, NamingSchemeUse use)
|
||||||
@@ -392,6 +407,8 @@ public sealed class ExportDestinations(ExportEnvironment env)
|
|||||||
NamingScheme = Clean(spec.NamingScheme),
|
NamingScheme = Clean(spec.NamingScheme),
|
||||||
HighlightNamingScheme = Clean(spec.HighlightNamingScheme),
|
HighlightNamingScheme = Clean(spec.HighlightNamingScheme),
|
||||||
ProfileNamingScheme = Clean(spec.ProfileNamingScheme),
|
ProfileNamingScheme = Clean(spec.ProfileNamingScheme),
|
||||||
|
PhotoFormat = spec.PhotoFormat,
|
||||||
|
VideoFormat = spec.VideoFormat,
|
||||||
Automatic = spec.Automatic,
|
Automatic = spec.Automatic,
|
||||||
CreatedAt = createdAt,
|
CreatedAt = createdAt,
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ using System.Security.Cryptography;
|
|||||||
using Febe.Core.Abstractions;
|
using Febe.Core.Abstractions;
|
||||||
using Febe.Core.Domain;
|
using Febe.Core.Domain;
|
||||||
using Febe.Core.Library;
|
using Febe.Core.Library;
|
||||||
|
using Febe.Core.Library.Conversion;
|
||||||
using Febe.Core.Storage;
|
using Febe.Core.Storage;
|
||||||
|
|
||||||
namespace Febe.Core.Export;
|
namespace Febe.Core.Export;
|
||||||
@@ -61,6 +62,9 @@ public sealed record ExportEnvironment
|
|||||||
/// <summary>…or this many planned bytes, whichever comes first.</summary>
|
/// <summary>…or this many planned bytes, whichever comes first.</summary>
|
||||||
public long GroupBytes { get; init; } = 1L << 30;
|
public long GroupBytes { get; init; } = 1L << 30;
|
||||||
|
|
||||||
|
/// <summary>One conversion at a time in the process (tappa E3, D16): shared with the library conversion.</summary>
|
||||||
|
public ConversionThrottle Throttle { get; init; } = ConversionThrottle.Shared;
|
||||||
|
|
||||||
/// <summary>The checker of destination folders of this environment.</summary>
|
/// <summary>The checker of destination folders of this environment.</summary>
|
||||||
public ExportFolderCheck CreateFolderCheck() => new(Root.Mounts, FolderCheckTimeout, WriteProbe);
|
public ExportFolderCheck CreateFolderCheck() => new(Root.Mounts, FolderCheckTimeout, WriteProbe);
|
||||||
|
|
||||||
@@ -101,6 +105,12 @@ public interface IExportFileSystem
|
|||||||
/// <summary>Opens a file for reading only.</summary>
|
/// <summary>Opens a file for reading only.</summary>
|
||||||
Stream OpenRead(string path);
|
Stream OpenRead(string path);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Opens a file for reading at any position (a video to remux or to take frames from, tappa E3). By default the
|
||||||
|
/// stream of <see cref="OpenRead"/>, which can seek.
|
||||||
|
/// </summary>
|
||||||
|
Stream OpenRandomAccess(string path) => OpenRead(path);
|
||||||
|
|
||||||
/// <summary>SHA-256 (lowercase hex) of a file as it is on disk now.</summary>
|
/// <summary>SHA-256 (lowercase hex) of a file as it is on disk now.</summary>
|
||||||
Task<string> ComputeSha256Async(string path, CancellationToken ct);
|
Task<string> ComputeSha256Async(string path, CancellationToken ct);
|
||||||
|
|
||||||
@@ -121,8 +131,13 @@ public sealed class ExportFileSystem : IExportFileSystem
|
|||||||
|
|
||||||
public static ExportFileSystem Instance { get; } = new();
|
public static ExportFileSystem Instance { get; } = new();
|
||||||
|
|
||||||
|
// FileShare.Delete: a long read never blocks «Elimina dalla libreria» on Windows (tappa E3).
|
||||||
public Stream OpenRead(string path) =>
|
public Stream OpenRead(string path) =>
|
||||||
new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, BufferSize, FileOptions.Asynchronous | FileOptions.SequentialScan);
|
new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete, BufferSize, FileOptions.Asynchronous | FileOptions.SequentialScan);
|
||||||
|
|
||||||
|
/// <summary>As <c>ContainerReader.OpenRead</c>: shared for reading, writing and deleting, read at random positions.</summary>
|
||||||
|
public Stream OpenRandomAccess(string path) =>
|
||||||
|
new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete, BufferSize, FileOptions.RandomAccess);
|
||||||
|
|
||||||
public async Task<string> ComputeSha256Async(string path, CancellationToken ct)
|
public async Task<string> ComputeSha256Async(string path, CancellationToken ct)
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -0,0 +1,170 @@
|
|||||||
|
using System.Globalization;
|
||||||
|
|
||||||
|
namespace Febe.Core.Export;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 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.
|
||||||
|
/// </summary>
|
||||||
|
public static class ExportFrames
|
||||||
|
{
|
||||||
|
/// <summary>The shortest step of «Uno ogni k secondi».</summary>
|
||||||
|
public static readonly TimeSpan MinEvery = TimeSpan.FromMilliseconds(100);
|
||||||
|
|
||||||
|
/// <summary>The most frames of «N in tutto».</summary>
|
||||||
|
public const int MaxCount = 1000;
|
||||||
|
|
||||||
|
/// <summary>The most frames taken from one video.</summary>
|
||||||
|
public const int MaxPerVideo = 1000;
|
||||||
|
|
||||||
|
/// <summary>The most frames of one request.</summary>
|
||||||
|
public const int MaxPerRequest = 20000;
|
||||||
|
|
||||||
|
/// <summary>Why a request over <see cref="MaxPerVideo"/> is refused.</summary>
|
||||||
|
public const string OverCapMessage = "Più di 1.000 fotogrammi per un video: scegli un intervallo più lungo";
|
||||||
|
|
||||||
|
/// <summary>The suffix of the single frame of «Salva il fotogramma» (tappa E4).</summary>
|
||||||
|
public const string SingleSuffix = "_fotogramma";
|
||||||
|
|
||||||
|
/// <summary>How many frames <paramref name="request"/> asks of a video of <paramref name="duration"/>.</summary>
|
||||||
|
public static long FrameCount(TimeSpan duration, ExportFramesRequest request)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(request);
|
||||||
|
return request.Mode switch
|
||||||
|
{
|
||||||
|
FrameMode.At => 1,
|
||||||
|
FrameMode.Every => EveryCount(duration, request.Every ?? throw new ArgumentException("Manca l'intervallo dei fotogrammi.", nameof(request))),
|
||||||
|
FrameMode.Count => request.Count ?? throw new ArgumentException("Manca il numero dei fotogrammi.", nameof(request)),
|
||||||
|
_ => throw new ArgumentOutOfRangeException(nameof(request)),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The instants <paramref name="request"/> asks of a video of <paramref name="duration"/>, in increasing order.
|
||||||
|
/// Refused (<see cref="ArgumentException"/> with <see cref="OverCapMessage"/>) over <see cref="MaxPerVideo"/>.
|
||||||
|
/// </summary>
|
||||||
|
public static IReadOnlyList<TimeSpan> Instants(TimeSpan duration, ExportFramesRequest request)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(request);
|
||||||
|
return request.Mode switch
|
||||||
|
{
|
||||||
|
FrameMode.At => [request.At is { } at && at > TimeSpan.Zero ? at : TimeSpan.Zero],
|
||||||
|
FrameMode.Every => Every(duration, request.Every ?? throw new ArgumentException("Manca l'intervallo dei fotogrammi.", nameof(request))),
|
||||||
|
FrameMode.Count => Spread(duration, request.Count ?? throw new ArgumentException("Manca il numero dei fotogrammi.", nameof(request))),
|
||||||
|
_ => throw new ArgumentOutOfRangeException(nameof(request)),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>«Uno ogni k secondi»: 0, k, 2k… before <paramref name="duration"/> (only 0 for a video without length).</summary>
|
||||||
|
public static IReadOnlyList<TimeSpan> Every(TimeSpan duration, TimeSpan step)
|
||||||
|
{
|
||||||
|
if (step < MinEvery)
|
||||||
|
{
|
||||||
|
throw new ArgumentOutOfRangeException(nameof(step), "L'intervallo minimo è 0,1 secondi.");
|
||||||
|
}
|
||||||
|
|
||||||
|
var count = EveryCount(duration, step);
|
||||||
|
if (count > MaxPerVideo)
|
||||||
|
{
|
||||||
|
throw new ArgumentException(OverCapMessage, nameof(step));
|
||||||
|
}
|
||||||
|
|
||||||
|
var instants = new TimeSpan[count];
|
||||||
|
for (var i = 0; i < count; i++)
|
||||||
|
{
|
||||||
|
instants[i] = WholeMs(TimeSpan.FromTicks(step.Ticks * i));
|
||||||
|
}
|
||||||
|
|
||||||
|
return instants;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// «N in tutto»: (i + ½) · duration / N for i = 0…N − 1, rounded up to the millisecond: the item, the preview and
|
||||||
|
/// the download locate the same instant. On a video shorter than N milliseconds neighbours can share one.
|
||||||
|
/// </summary>
|
||||||
|
public static IReadOnlyList<TimeSpan> Spread(TimeSpan duration, int count)
|
||||||
|
{
|
||||||
|
if (count is < 1 or > MaxCount)
|
||||||
|
{
|
||||||
|
throw new ArgumentOutOfRangeException(nameof(count), "Da 1 a 1.000 fotogrammi.");
|
||||||
|
}
|
||||||
|
|
||||||
|
var length = (Int128)Math.Max(0, duration.Ticks);
|
||||||
|
var instants = new TimeSpan[count];
|
||||||
|
for (var i = 0; i < count; i++)
|
||||||
|
{
|
||||||
|
instants[i] = WholeMs(TimeSpan.FromTicks((long)(((2 * i) + 1) * length / (2 * (Int128)count))));
|
||||||
|
}
|
||||||
|
|
||||||
|
return instants;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The suffix of a frame file, appended to the stem: <c>_t0m12s340</c> (the actual instant: minutes, seconds on two
|
||||||
|
/// digits, milliseconds on three) for «Questo istante» and «Uno ogni k secondi»; <c>_f001</c> (the position among
|
||||||
|
/// the <paramref name="count"/> instants, at least three digits) for «N in tutto».
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="index">0-based position of the instant in the request.</param>
|
||||||
|
public static string Suffix(FrameMode mode, TimeSpan actual, int index, int count)
|
||||||
|
{
|
||||||
|
if (mode == FrameMode.Count)
|
||||||
|
{
|
||||||
|
var digits = Math.Max(3, Math.Max(1, count).ToString(CultureInfo.InvariantCulture).Length);
|
||||||
|
return "_f" + (index + 1).ToString("D" + digits.ToString(CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
|
||||||
|
}
|
||||||
|
|
||||||
|
var ms = ActualMs(actual);
|
||||||
|
return string.Create(CultureInfo.InvariantCulture, $"_t{ms / 60000}m{ms / 1000 % 60:D2}s{ms % 1000:D3}");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// An instant as the viewer and the dialog show it: <c>m:ss</c> («0:01»), followed by a comma and the milliseconds
|
||||||
|
/// without trailing zeros only when it is not a whole second («0:01,25»).
|
||||||
|
/// </summary>
|
||||||
|
public static string Label(TimeSpan actual)
|
||||||
|
{
|
||||||
|
var ms = ActualMs(actual);
|
||||||
|
var label = string.Create(CultureInfo.InvariantCulture, $"{ms / 60000}:{ms / 1000 % 60:D2}");
|
||||||
|
var fraction = ms % 1000;
|
||||||
|
return fraction == 0
|
||||||
|
? label
|
||||||
|
: label + "," + fraction.ToString("D3", CultureInfo.InvariantCulture).TrimEnd('0');
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The position of <paramref name="requested"/> among <paramref name="instants"/> (the first of those on the same
|
||||||
|
/// millisecond, as the items keep them), or null when it is not one of them.
|
||||||
|
/// </summary>
|
||||||
|
public static int? IndexOf(IReadOnlyList<TimeSpan> instants, TimeSpan requested)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(instants);
|
||||||
|
var ms = (long)requested.TotalMilliseconds;
|
||||||
|
for (var i = 0; i < instants.Count; i++)
|
||||||
|
{
|
||||||
|
if ((long)instants[i].TotalMilliseconds == ms)
|
||||||
|
{
|
||||||
|
return i;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>An instant rounded up to the whole millisecond (never before the instant computed).</summary>
|
||||||
|
private static TimeSpan WholeMs(TimeSpan at) => TimeSpan.FromMilliseconds(ActualMs(at));
|
||||||
|
|
||||||
|
/// <summary>The identity of a frame's instant: its shown time in milliseconds, rounded up.</summary>
|
||||||
|
public static long ActualMs(TimeSpan shown) =>
|
||||||
|
shown <= TimeSpan.Zero ? 0 : (shown.Ticks + TimeSpan.TicksPerMillisecond - 1) / TimeSpan.TicksPerMillisecond;
|
||||||
|
|
||||||
|
private static long EveryCount(TimeSpan duration, TimeSpan step)
|
||||||
|
{
|
||||||
|
if (step <= TimeSpan.Zero)
|
||||||
|
{
|
||||||
|
throw new ArgumentOutOfRangeException(nameof(step));
|
||||||
|
}
|
||||||
|
|
||||||
|
// 0, k, 2k… strictly before the end: ceil(duration / k), and at least the frame at 0.
|
||||||
|
return duration <= TimeSpan.Zero ? 1 : Math.Max(1, (duration.Ticks + step.Ticks - 1) / step.Ticks);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -23,8 +23,43 @@ public abstract record ExportSelection
|
|||||||
public sealed record Account(long AccountId) : ExportSelection;
|
public sealed record Account(long AccountId) : ExportSelection;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>How the instants of «Fotogrammi» are chosen (spec §4.10 «Fotogrammi»).</summary>
|
||||||
|
public enum FrameMode
|
||||||
|
{
|
||||||
|
/// <summary>«Questo istante»: one frame at <see cref="ExportFramesRequest.At"/>.</summary>
|
||||||
|
At,
|
||||||
|
|
||||||
|
/// <summary>«Uno ogni k secondi»: at 0, k, 2k… before the end.</summary>
|
||||||
|
Every,
|
||||||
|
|
||||||
|
/// <summary>«N in tutto»: N frames spread over the video, each in the middle of its share.</summary>
|
||||||
|
Count,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>A request of frames of videos, in a photo format (Jpg, Png or WebpLossless).</summary>
|
||||||
|
public sealed record ExportFramesRequest(FrameMode Mode, TimeSpan? At, TimeSpan? Every, int? Count, ExportFormat Format);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The formats of «Copia in…» for this request only (tappa E3, D1): null keeps the destination's (or the general
|
||||||
|
/// settings'). A photo format or Original for photos; Mp4 or Original for videos.
|
||||||
|
/// </summary>
|
||||||
|
public sealed record ExportFormatChoice(ExportFormat? Photo, ExportFormat? Video);
|
||||||
|
|
||||||
|
/// <summary>«Copia di nuovo» of one copy row (tappa E3, D11): the form of that row, looked up only by its exact identity.</summary>
|
||||||
|
/// <param name="FrameAt">The instant of a frame row; null otherwise.</param>
|
||||||
|
public sealed record ExportCopyRequest(ExportVariant Variant, ExportFormat Format, TimeSpan? FrameAt);
|
||||||
|
|
||||||
/// <summary>A «Copia in…»: what to copy, whether «Tolti» and «Superati» are copied again (D9), who asked.</summary>
|
/// <summary>A «Copia in…»: what to copy, whether «Tolti» and «Superati» are copied again (D9), who asked.</summary>
|
||||||
public sealed record ExportJobRequest(ExportSelection Selection, bool CopyAgain = false, ExportRunOrigin Origin = ExportRunOrigin.Manual);
|
/// <param name="Formats">The formats of this request («Copia in…» → «Cambia»); null: those of the destination.</param>
|
||||||
|
/// <param name="Frames">Not null: a frames job («Fotogrammi…» → «Nella cartella delle copie»), videos only.</param>
|
||||||
|
/// <param name="Exact">«Copia di nuovo» of one copy row, only with a selection of one file.</param>
|
||||||
|
public sealed record ExportJobRequest(
|
||||||
|
ExportSelection Selection,
|
||||||
|
bool CopyAgain = false,
|
||||||
|
ExportRunOrigin Origin = ExportRunOrigin.Manual,
|
||||||
|
ExportFormatChoice? Formats = null,
|
||||||
|
ExportFramesRequest? Frames = null,
|
||||||
|
ExportCopyRequest? Exact = null);
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// What a «Copia in…» would do (database only, decisions D3 and D9 of tappa E2). Each file goes to the effective
|
/// What a «Copia in…» would do (database only, decisions D3 and D9 of tappa E2). Each file goes to the effective
|
||||||
@@ -55,8 +90,35 @@ public sealed record ExportPlan(
|
|||||||
bool HasDestination = true)
|
bool HasDestination = true)
|
||||||
{
|
{
|
||||||
public static ExportPlan Empty { get; } = new(0, 0, 0, 0, 0, 0, []);
|
public static ExportPlan Empty { get; } = new(0, 0, 0, 0, 0, 0, []);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Files predicted to be copied as they are, by kind («3 HEIC copiati come sono»): a prediction from the names
|
||||||
|
/// («circa»), the copy decides on the bytes (tappa E3).
|
||||||
|
/// </summary>
|
||||||
|
public IReadOnlyList<ExportPlanAsIs> AsIs { get; init; } = [];
|
||||||
|
|
||||||
|
/// <summary>Files predicted to be converted.</summary>
|
||||||
|
public int Converted { get; init; }
|
||||||
|
|
||||||
|
/// <summary>«Con perdita»: at least one file predicted converted to JPG, or JPG frames (D7 of tappa E3).</summary>
|
||||||
|
public bool Lossy { get; init; }
|
||||||
|
|
||||||
|
/// <summary>Frames job: the due videos.</summary>
|
||||||
|
public int Videos { get; init; }
|
||||||
|
|
||||||
|
/// <summary>Frames job: the photos of the selection, skipped («Le 4 foto si saltano»).</summary>
|
||||||
|
public int PhotosSkipped { get; init; }
|
||||||
|
|
||||||
|
/// <summary>Frames job: the frames to write (also in <see cref="Files"/>); «circa» for a video of unknown length.</summary>
|
||||||
|
public int Frames { get; init; }
|
||||||
|
|
||||||
|
/// <summary>Frames job: videos that would give more than <see cref="ExportFrames.MaxPerVideo"/> frames (the job is refused).</summary>
|
||||||
|
public int OverCap { get; init; }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>Files of a plan copied as they are, of one kind («HEIC», «AVIF», «raw», «GIF», «WebM»).</summary>
|
||||||
|
public sealed record ExportPlanAsIs(string Label, int Files);
|
||||||
|
|
||||||
/// <summary>A destination of a plan.</summary>
|
/// <summary>A destination of a plan.</summary>
|
||||||
/// <param name="Username">The account of an own folder; null for the general folder.</param>
|
/// <param name="Username">The account of an own folder; null for the general folder.</param>
|
||||||
/// <param name="Files">Files to write there.</param>
|
/// <param name="Files">Files to write there.</param>
|
||||||
|
|||||||
@@ -4,6 +4,12 @@ using Febe.Core.Library;
|
|||||||
|
|
||||||
namespace Febe.Core.Export;
|
namespace Febe.Core.Export;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// How the file name of a copy differs from the library's (tappa E3): the extension of the effective format
|
||||||
|
/// («.jpg»; null keeps the source's) and the suffix of a frame («_t0m12s340»; null for none), appended to the stem.
|
||||||
|
/// </summary>
|
||||||
|
public sealed record ExportNameOptions(string? Extension, string? Suffix);
|
||||||
|
|
||||||
/// <summary>Paths and content types of the export (spec §4.10).</summary>
|
/// <summary>Paths and content types of the export (spec §4.10).</summary>
|
||||||
public static class ExportPaths
|
public static class ExportPaths
|
||||||
{
|
{
|
||||||
@@ -63,7 +69,8 @@ public static class ExportPaths
|
|||||||
Media media,
|
Media media,
|
||||||
string? highlightTitle,
|
string? highlightTitle,
|
||||||
bool inHighlight,
|
bool inHighlight,
|
||||||
TimeZoneInfo zone)
|
TimeZoneInfo zone,
|
||||||
|
ExportNameOptions? name = null)
|
||||||
{
|
{
|
||||||
ArgumentNullException.ThrowIfNull(d);
|
ArgumentNullException.ThrowIfNull(d);
|
||||||
ArgumentNullException.ThrowIfNull(library);
|
ArgumentNullException.ThrowIfNull(library);
|
||||||
@@ -106,22 +113,42 @@ public static class ExportPaths
|
|||||||
segments = scheme.Render(values, zone);
|
segments = scheme.Render(values, zone);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
segments = Renamed(segments, name);
|
||||||
return d.Scope == ExportScope.General ? [WindowsFileNames.SanitizeSegment(account.Username), .. segments] : segments;
|
return d.Scope == ExportScope.General ? [WindowsFileNames.SanitizeSegment(account.Username), .. segments] : segments;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>The last segment with the suffix appended to its stem and the extension of <paramref name="name"/>.</summary>
|
||||||
|
private static IReadOnlyList<string> Renamed(IReadOnlyList<string> segments, ExportNameOptions? name)
|
||||||
|
{
|
||||||
|
if (name is null || segments.Count == 0 || (name.Extension is null && string.IsNullOrEmpty(name.Suffix)))
|
||||||
|
{
|
||||||
|
return segments;
|
||||||
|
}
|
||||||
|
|
||||||
|
var (stem, extension) = WindowsFileNames.SplitExtension(segments[^1]);
|
||||||
|
var fileName = WindowsFileNames.SanitizeSegment(stem + (name.Suffix ?? string.Empty) + (name.Extension ?? extension));
|
||||||
|
return [.. segments.Take(segments.Count - 1), fileName];
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>The relative path ('/' separated) of a copy: the segments fitted to the length limit under the root.</summary>
|
/// <summary>The relative path ('/' separated) of a copy: the segments fitted to the length limit under the root.</summary>
|
||||||
|
/// <param name="d">The destination.</param>
|
||||||
|
/// <param name="segments">The segments of <see cref="Segments"/>.</param>
|
||||||
|
/// <param name="maxPath">The longest full path.</param>
|
||||||
|
/// <param name="keepSuffix">The frame suffix of the file name, never cut by the shortening.</param>
|
||||||
/// <exception cref="PathTooLongException">Even shortened, the path does not fit.</exception>
|
/// <exception cref="PathTooLongException">Even shortened, the path does not fit.</exception>
|
||||||
public static string RelativePathFor(ExportDestination d, IReadOnlyList<string> segments, int maxPath = WindowsFileNames.MaxPathLength)
|
public static string RelativePathFor(ExportDestination d, IReadOnlyList<string> segments, int maxPath = WindowsFileNames.MaxPathLength, string? keepSuffix = null)
|
||||||
{
|
{
|
||||||
ArgumentNullException.ThrowIfNull(d);
|
ArgumentNullException.ThrowIfNull(d);
|
||||||
return string.Join('/', WindowsFileNames.FitPath(d.RootPath, segments, maxPath));
|
return string.Join('/', WindowsFileNames.FitPath(d.RootPath, segments, maxPath, keepSuffix));
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// The name the safe writer gives a file at its <paramref name="attempt"/>-th try when the planned name is taken
|
/// The name the safe writer gives a file at its <paramref name="attempt"/>-th try when the planned name is taken
|
||||||
/// («nome (2).jpg», «nome (3).jpg», …), so a resumed copy finds a file it renamed before a crash.
|
/// («nome (2).jpg», «nome (3).jpg», …), so a resumed copy finds a file it renamed before a crash. With
|
||||||
|
/// <paramref name="keepSuffix"/> (a frame suffix, <see cref="SafeWriteOptions.KeepSuffix"/>) the number comes after
|
||||||
|
/// it and both survive the shortening: «x_f001 (2).png».
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public static string NumberedName(string root, string relativePath, int attempt, int maxPath = WindowsFileNames.MaxPathLength)
|
public static string NumberedName(string root, string relativePath, int attempt, int maxPath = WindowsFileNames.MaxPathLength, string? keepSuffix = null)
|
||||||
{
|
{
|
||||||
ArgumentException.ThrowIfNullOrWhiteSpace(relativePath);
|
ArgumentException.ThrowIfNullOrWhiteSpace(relativePath);
|
||||||
var segments = LibraryLayout.ToStored(relativePath).Split('/', StringSplitOptions.RemoveEmptyEntries);
|
var segments = LibraryLayout.ToStored(relativePath).Split('/', StringSplitOptions.RemoveEmptyEntries);
|
||||||
@@ -132,7 +159,8 @@ public static class ExportPaths
|
|||||||
|
|
||||||
var (stem, extension) = WindowsFileNames.SplitExtension(segments[^1]);
|
var (stem, extension) = WindowsFileNames.SplitExtension(segments[^1]);
|
||||||
var name = WindowsFileNames.SanitizeSegment(string.Create(CultureInfo.InvariantCulture, $"{stem} ({attempt}){extension}"));
|
var name = WindowsFileNames.SanitizeSegment(string.Create(CultureInfo.InvariantCulture, $"{stem} ({attempt}){extension}"));
|
||||||
return string.Join('/', WindowsFileNames.FitPath(root, [.. segments[..^1], name], maxPath));
|
var keep = keepSuffix is null ? null : string.Create(CultureInfo.InvariantCulture, $"{keepSuffix} ({attempt})");
|
||||||
|
return string.Join('/', WindowsFileNames.FitPath(root, [.. segments[..^1], name], maxPath, keep));
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>The scheme that names an entry kind.</summary>
|
/// <summary>The scheme that names an entry kind.</summary>
|
||||||
|
|||||||
@@ -6,8 +6,10 @@ namespace Febe.Core.Export;
|
|||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// What a «Copia in…» would do, from the database only (decisions D3, D5 and D9 of tappa E2): each file goes to the
|
/// What a «Copia in…» would do, from the database only (decisions D3, D5 and D9 of tappa E2): each file goes to the
|
||||||
/// effective destination of its account; a file already copied there is «già copiato»; «Tolti» and «Superati» are
|
/// effective destination of its account; a file already copied there, in any form but a frame, is «già copiato»
|
||||||
/// skipped unless «Copia di nuovo» was asked. The only look at a destination is whether it answers, for the dialog.
|
/// (decision D3 of tappa E3); «Tolti» and «Superati» are skipped unless «Copia di nuovo» was asked. The format of each
|
||||||
|
/// file is resolved and predicted from its name (D1, «circa»); a frames job plans one frame per instant of each due
|
||||||
|
/// video. The only look at a destination is whether it answers, for the dialog.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public sealed class ExportPlanner(ExportEnvironment env)
|
public sealed class ExportPlanner(ExportEnvironment env)
|
||||||
{
|
{
|
||||||
@@ -16,9 +18,11 @@ public sealed class ExportPlanner(ExportEnvironment env)
|
|||||||
private readonly ExportEnvironment _env = env ?? throw new ArgumentNullException(nameof(env));
|
private readonly ExportEnvironment _env = env ?? throw new ArgumentNullException(nameof(env));
|
||||||
|
|
||||||
/// <summary>The plan of a request, for the «Copia in…» dialog.</summary>
|
/// <summary>The plan of a request, for the «Copia in…» dialog.</summary>
|
||||||
|
/// <exception cref="ArgumentException">The request is not valid (Italian message).</exception>
|
||||||
public async Task<ExportPlan> PlanAsync(ExportJobRequest request, CancellationToken ct)
|
public async Task<ExportPlan> PlanAsync(ExportJobRequest request, CancellationToken ct)
|
||||||
{
|
{
|
||||||
ArgumentNullException.ThrowIfNull(request);
|
ArgumentNullException.ThrowIfNull(request);
|
||||||
|
Validate(request);
|
||||||
var destinations = new ExportDestinations(_env);
|
var destinations = new ExportDestinations(_env);
|
||||||
var effective = await destinations.ResolveAllAsync(ct).ConfigureAwait(false);
|
var effective = await destinations.ResolveAllAsync(ct).ConfigureAwait(false);
|
||||||
var settings = await ExportSettings.LoadAsync(_env.Storage.Settings, ct).ConfigureAwait(false);
|
var settings = await ExportSettings.LoadAsync(_env.Storage.Settings, ct).ConfigureAwait(false);
|
||||||
@@ -31,17 +35,108 @@ public sealed class ExportPlanner(ExportEnvironment env)
|
|||||||
return await tally.BuildAsync(_env, destinations, effective, checkDestinations: true, ct).ConfigureAwait(false);
|
return await tally.BuildAsync(_env, destinations, effective, checkDestinations: true, ct).ConfigureAwait(false);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>The checks of a request (tappa E3, WP1.1), with Italian messages.</summary>
|
||||||
|
/// <exception cref="ArgumentException">What is wrong.</exception>
|
||||||
|
public static void Validate(ExportJobRequest request)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(request);
|
||||||
|
ArgumentNullException.ThrowIfNull(request.Selection, nameof(request));
|
||||||
|
if (request.Frames is not null && request.Formats is not null)
|
||||||
|
{
|
||||||
|
throw new ArgumentException("I fotogrammi non si chiedono insieme ai formati delle copie.", nameof(request));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (request.Exact is { } exact)
|
||||||
|
{
|
||||||
|
if (request.Selection is not ExportSelection.Media { MediaIds.Count: 1 })
|
||||||
|
{
|
||||||
|
throw new ArgumentException("«Copia di nuovo» di una copia vale per un file solo.", nameof(request));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (request.Frames is not null || request.Formats is not null)
|
||||||
|
{
|
||||||
|
throw new ArgumentException("«Copia di nuovo» di una copia rifà la sua forma: niente altri formati né fotogrammi.", nameof(request));
|
||||||
|
}
|
||||||
|
|
||||||
|
var valid = exact.Variant switch
|
||||||
|
{
|
||||||
|
ExportVariant.Whole => exact.Format == ExportFormat.Original && exact.FrameAt is null,
|
||||||
|
ExportVariant.Converted => exact.Format != ExportFormat.Original && exact.FrameAt is null,
|
||||||
|
ExportVariant.Frame => IsFrameFormat(exact.Format) && exact.FrameAt is { } at && at >= TimeSpan.Zero,
|
||||||
|
_ => false,
|
||||||
|
};
|
||||||
|
if (!valid)
|
||||||
|
{
|
||||||
|
throw new ArgumentException("La forma della copia da rifare non è valida.", nameof(request));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (request.Formats is { } formats)
|
||||||
|
{
|
||||||
|
if (formats.Photo is { } photo && !ExportFormats.IsPhotoFormat(photo))
|
||||||
|
{
|
||||||
|
throw new ArgumentException("Per le foto si sceglie Originale, JPG, PNG o WEBP senza perdita.", nameof(request));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (formats.Video is { } video && !ExportFormats.IsVideoFormat(video))
|
||||||
|
{
|
||||||
|
throw new ArgumentException("Per i video si sceglie Originale o MP4.", nameof(request));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (request.Frames is { } frames)
|
||||||
|
{
|
||||||
|
if (!IsFrameFormat(frames.Format))
|
||||||
|
{
|
||||||
|
throw new ArgumentException("I fotogrammi si salvano in JPG, PNG o WEBP senza perdita.", nameof(request));
|
||||||
|
}
|
||||||
|
|
||||||
|
switch (frames.Mode)
|
||||||
|
{
|
||||||
|
case FrameMode.At when frames.At is not { } at || at < TimeSpan.Zero:
|
||||||
|
throw new ArgumentException("Scegli l'istante del fotogramma.", nameof(request));
|
||||||
|
case FrameMode.Every when frames.Every is not { } every || every < ExportFrames.MinEvery:
|
||||||
|
throw new ArgumentException("L'intervallo minimo è 0,1 secondi.", nameof(request));
|
||||||
|
case FrameMode.Count when frames.Count is not ({ } count and >= 1 and <= ExportFrames.MaxCount):
|
||||||
|
throw new ArgumentException("Da 1 a 1.000 fotogrammi.", nameof(request));
|
||||||
|
case FrameMode.At or FrameMode.Every or FrameMode.Count:
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
throw new ArgumentException("Modo dei fotogrammi sconosciuto.", nameof(request));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>JPG, PNG or WEBP senza perdita: the formats of a frame.</summary>
|
||||||
|
internal static bool IsFrameFormat(ExportFormat format) => format is ExportFormat.Jpg or ExportFormat.Png or ExportFormat.WebpLossless;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Every candidate of the request with what to do with it, in media id order. Within one plan the same file of an
|
/// Every candidate of the request with what to do with it, in media id order (a frames job: one planned file per
|
||||||
/// account in one destination counts once (a story and its highlight entry, two files with the same bytes); with
|
/// instant of each video, in instant order). Within one plan the same file of an account in one destination counts
|
||||||
/// «Una copia sola» the same file counts once across accounts.
|
/// once (a story and its highlight entry, two files with the same bytes); with «Una copia sola» the same file counts
|
||||||
|
/// once across accounts.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
|
/// <param name="lengthOf">
|
||||||
|
/// Frames job: the length of a video the library does not know, read from its file (null when unreadable); without
|
||||||
|
/// it such a video is one planned file without instants (<see cref="PlannedFile.UnknownDuration"/>, the dialog).
|
||||||
|
/// </param>
|
||||||
internal async IAsyncEnumerable<PlannedFile> EnumerateAsync(
|
internal async IAsyncEnumerable<PlannedFile> EnumerateAsync(
|
||||||
ExportJobRequest request,
|
ExportJobRequest request,
|
||||||
IReadOnlyDictionary<long, EffectiveDestination> effective,
|
IReadOnlyDictionary<long, EffectiveDestination> effective,
|
||||||
ExportSettings settings,
|
ExportSettings settings,
|
||||||
[EnumeratorCancellation] CancellationToken ct)
|
[EnumeratorCancellation] CancellationToken ct,
|
||||||
|
Func<ExportCandidate, CancellationToken, Task<TimeSpan?>>? lengthOf = null)
|
||||||
{
|
{
|
||||||
|
if (request.Frames is { } frames)
|
||||||
|
{
|
||||||
|
await foreach (var frame in EnumerateFramesAsync(request, frames, effective, lengthOf, ct).ConfigureAwait(false))
|
||||||
|
{
|
||||||
|
yield return frame;
|
||||||
|
}
|
||||||
|
|
||||||
|
yield break;
|
||||||
|
}
|
||||||
|
|
||||||
var exports = _env.Storage.Exports;
|
var exports = _env.Storage.Exports;
|
||||||
var oneOnly = settings.SamePost == SamePostCopies.OneOnly;
|
var oneOnly = settings.SamePost == SamePostCopies.OneOnly;
|
||||||
var seen = new HashSet<(long Destination, long Account, string Sha256)>();
|
var seen = new HashSet<(long Destination, long Account, string Sha256)>();
|
||||||
@@ -70,9 +165,12 @@ public sealed class ExportPlanner(ExportEnvironment env)
|
|||||||
}
|
}
|
||||||
|
|
||||||
var states = new Dictionary<long, IReadOnlyDictionary<(long AccountId, string Sha256), ExportCopyState>>();
|
var states = new Dictionary<long, IReadOnlyDictionary<(long AccountId, string Sha256), ExportCopyState>>();
|
||||||
foreach (var (destination, set) in keys)
|
if (request.Exact is null)
|
||||||
{
|
{
|
||||||
states[destination] = await exports.GetCopyStatesAsync(destination, set, ct).ConfigureAwait(false);
|
foreach (var (destination, set) in keys)
|
||||||
|
{
|
||||||
|
states[destination] = await exports.GetCopyStatesAsync(destination, set, ct).ConfigureAwait(false);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
foreach (var c in page)
|
foreach (var c in page)
|
||||||
@@ -91,25 +189,45 @@ public sealed class ExportPlanner(ExportEnvironment env)
|
|||||||
|
|
||||||
var sha = c.Sha256!;
|
var sha = c.Sha256!;
|
||||||
var key = oneOnly ? (0L, 0L, sha) : (destination, c.AccountId, sha);
|
var key = oneOnly ? (0L, 0L, sha) : (destination, c.AccountId, sha);
|
||||||
var state = states[destination].TryGetValue((c.AccountId, sha), out var s) ? s : (ExportCopyState?)null;
|
var form = Form(c, request, effective[c.AccountId].Destination!, settings);
|
||||||
|
ExportCopyState? state;
|
||||||
|
if (request.Exact is { } exact)
|
||||||
|
{
|
||||||
|
// «Copia di nuovo» of one row: only its exact identity counts (D11 of tappa E3).
|
||||||
|
var identity = new ExportCopyIdentity(destination, c.AccountId, sha, exact.Variant, exact.Format, exact.FrameAt);
|
||||||
|
if (await exports.FindCurrentCopyAsync(identity, ct).ConfigureAwait(false) is { } current)
|
||||||
|
{
|
||||||
|
state = current.State;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
var latest = await exports.FindLatestCopyAsync(identity, ct).ConfigureAwait(false);
|
||||||
|
state = latest is { State: ExportCopyState.Removed or ExportCopyState.Superseded } ? latest.State : null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
state = states[destination].TryGetValue((c.AccountId, sha), out var s) ? s : null;
|
||||||
|
}
|
||||||
|
|
||||||
PlannedFile planned;
|
PlannedFile planned;
|
||||||
if (state == ExportCopyState.Copied)
|
if (state == ExportCopyState.Copied)
|
||||||
{
|
{
|
||||||
planned = new PlannedFile(c, destination, PlannedCopy.AlreadyCopied);
|
planned = form with { DestinationId = destination, Action = PlannedCopy.AlreadyCopied };
|
||||||
}
|
}
|
||||||
else if (state is ExportCopyState.Removed or ExportCopyState.Superseded)
|
else if (state is ExportCopyState.Removed or ExportCopyState.Superseded)
|
||||||
{
|
{
|
||||||
planned = request.CopyAgain
|
planned = request.CopyAgain
|
||||||
? new PlannedFile(c, destination, PlannedCopy.Write, Again: true)
|
? form with { DestinationId = destination, Action = PlannedCopy.Write, Again = true }
|
||||||
: new PlannedFile(c, destination, PlannedCopy.RemovedOrSuperseded);
|
: form with { DestinationId = destination, Action = PlannedCopy.RemovedOrSuperseded };
|
||||||
}
|
}
|
||||||
else if (oneOnly && await exports.FindCopiedElsewhereAsync(sha, ExportVariant.Whole, ExportFormat.Original, c.AccountId, ct).ConfigureAwait(false) is not null)
|
else if (oneOnly && await exports.FindCopiedElsewhereAsync(sha, c.AccountId, ct).ConfigureAwait(false) is not null)
|
||||||
{
|
{
|
||||||
planned = new PlannedFile(c, destination, PlannedCopy.AlreadyCopied);
|
planned = form with { DestinationId = destination, Action = PlannedCopy.AlreadyCopied };
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
planned = new PlannedFile(c, destination, PlannedCopy.Write);
|
planned = form with { DestinationId = destination, Action = PlannedCopy.Write };
|
||||||
}
|
}
|
||||||
|
|
||||||
if (planned.Action is PlannedCopy.Write or PlannedCopy.AlreadyCopied && !seen.Add(key))
|
if (planned.Action is PlannedCopy.Write or PlannedCopy.AlreadyCopied && !seen.Add(key))
|
||||||
@@ -122,6 +240,128 @@ public sealed class ExportPlanner(ExportEnvironment env)
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// A frames job (D12, D14 of tappa E3): photos are skipped, videos not due are counted as in «Copia in…», each due
|
||||||
|
/// video gives one planned frame per instant of the request. A video of unknown length is measured by
|
||||||
|
/// <paramref name="lengthOf"/> (the job: before anything is recorded, so that its frames count against the caps of
|
||||||
|
/// D12) or, without it, gives one planned file without an instant (<see cref="PlannedFile.UnknownDuration"/>, the
|
||||||
|
/// dialog). One that cannot be read gets one instant, and the copy says «Fotogramma non disponibile per questo
|
||||||
|
/// video». Frames are not checked for «già copiato» here: the copy looks at each one's exact instant.
|
||||||
|
/// </summary>
|
||||||
|
private async IAsyncEnumerable<PlannedFile> EnumerateFramesAsync(
|
||||||
|
ExportJobRequest request,
|
||||||
|
ExportFramesRequest frames,
|
||||||
|
IReadOnlyDictionary<long, EffectiveDestination> effective,
|
||||||
|
Func<ExportCandidate, CancellationToken, Task<TimeSpan?>>? lengthOf,
|
||||||
|
[EnumeratorCancellation] CancellationToken ct)
|
||||||
|
{
|
||||||
|
var exports = _env.Storage.Exports;
|
||||||
|
var seen = new HashSet<(long Destination, long Account, string Sha256, long Ms, ExportFormat Format)>();
|
||||||
|
long after = 0;
|
||||||
|
while (true)
|
||||||
|
{
|
||||||
|
var page = await exports.ListCandidatesAsync(request.Selection, after, PageSize, ct).ConfigureAwait(false);
|
||||||
|
if (page.Count == 0)
|
||||||
|
{
|
||||||
|
yield break;
|
||||||
|
}
|
||||||
|
|
||||||
|
after = page[^1].MediaId;
|
||||||
|
foreach (var c in page)
|
||||||
|
{
|
||||||
|
if (!IsPresent(c))
|
||||||
|
{
|
||||||
|
yield return new PlannedFile(c, null, PlannedCopy.Missing);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (c.MediaKind != MediaKind.Video)
|
||||||
|
{
|
||||||
|
yield return new PlannedFile(c, null, PlannedCopy.PhotoSkipped);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (Due(c, effective) is not { } destination)
|
||||||
|
{
|
||||||
|
yield return new PlannedFile(c, null, PlannedCopy.NotExported);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
var frame = new PlannedFile(c, destination, PlannedCopy.Write)
|
||||||
|
{
|
||||||
|
Variant = ExportVariant.Frame,
|
||||||
|
Format = frames.Format,
|
||||||
|
Prediction = ExportPrediction.Converted,
|
||||||
|
FirstOfVideo = true,
|
||||||
|
};
|
||||||
|
var duration = c.Duration ?? TimeSpan.Zero;
|
||||||
|
if (frames.Mode != FrameMode.At && c.Duration is null)
|
||||||
|
{
|
||||||
|
if (lengthOf is null)
|
||||||
|
{
|
||||||
|
yield return frame with { UnknownDuration = true };
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (await lengthOf(c, ct).ConfigureAwait(false) is not { } measured || measured <= TimeSpan.Zero)
|
||||||
|
{
|
||||||
|
var unreadable = frame with { FrameAt = TimeSpan.Zero };
|
||||||
|
yield return seen.Add((destination, c.AccountId, c.Sha256!, 0, frames.Format))
|
||||||
|
? unreadable
|
||||||
|
: unreadable with { Action = PlannedCopy.AlreadyCopied };
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
duration = measured;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (ExportFrames.FrameCount(duration, frames) > ExportFrames.MaxPerVideo)
|
||||||
|
{
|
||||||
|
yield return frame with { Action = PlannedCopy.OverCap };
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
var first = true;
|
||||||
|
foreach (var at in ExportFrames.Instants(duration, frames))
|
||||||
|
{
|
||||||
|
var planned = frame with { FrameAt = at, FirstOfVideo = first };
|
||||||
|
first = false;
|
||||||
|
// By the millisecond the item keeps (ux_export_item_file): two instants on one are one item.
|
||||||
|
if (!seen.Add((destination, c.AccountId, c.Sha256!, (long)at.TotalMilliseconds, frames.Format)))
|
||||||
|
{
|
||||||
|
planned = planned with { Action = PlannedCopy.AlreadyCopied };
|
||||||
|
}
|
||||||
|
|
||||||
|
yield return planned;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The form a file is asked in (D1, D2): the request's identity, and what its name predicts.</summary>
|
||||||
|
private static PlannedFile Form(ExportCandidate c, ExportJobRequest request, ExportDestination destination, ExportSettings settings)
|
||||||
|
{
|
||||||
|
if (request.Exact is { } exact)
|
||||||
|
{
|
||||||
|
var prediction = exact.Variant == ExportVariant.Whole ? ExportPrediction.Whole : ExportConversions.Predict(c.RelativePath!, c.MediaKind, exact.Format);
|
||||||
|
return new PlannedFile(c, null, PlannedCopy.Write)
|
||||||
|
{
|
||||||
|
Variant = exact.Variant,
|
||||||
|
Format = exact.Format,
|
||||||
|
FrameAt = exact.FrameAt,
|
||||||
|
Prediction = exact.Variant == ExportVariant.Frame ? ExportPrediction.Converted : prediction,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
var target = ExportConversions.Resolve(c.MediaKind, request.Formats, destination, settings);
|
||||||
|
return new PlannedFile(c, null, PlannedCopy.Write)
|
||||||
|
{
|
||||||
|
Variant = ExportConversions.VariantOf(target),
|
||||||
|
Format = target,
|
||||||
|
Prediction = ExportConversions.Predict(c.RelativePath!, c.MediaKind, target),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>A file present in the library, with its SHA-256 and path.</summary>
|
/// <summary>A file present in the library, with its SHA-256 and path.</summary>
|
||||||
internal static bool IsPresent(ExportCandidate c) => EntryStateRules.IsPresent(c.State) && c.Sha256 is { Length: 64 } && !string.IsNullOrEmpty(c.RelativePath);
|
internal static bool IsPresent(ExportCandidate c) => EntryStateRules.IsPresent(c.State) && c.Sha256 is { Length: 64 } && !string.IsNullOrEmpty(c.RelativePath);
|
||||||
|
|
||||||
@@ -135,7 +375,26 @@ public sealed class ExportPlanner(ExportEnvironment env)
|
|||||||
/// <summary>A candidate with what the plan does with it.</summary>
|
/// <summary>A candidate with what the plan does with it.</summary>
|
||||||
/// <param name="DestinationId">Where it goes; null when not exported or missing.</param>
|
/// <param name="DestinationId">Where it goes; null when not exported or missing.</param>
|
||||||
/// <param name="Again">Written although «Tolto» or «Superato», because «Copia di nuovo» was asked.</param>
|
/// <param name="Again">Written although «Tolto» or «Superato», because «Copia di nuovo» was asked.</param>
|
||||||
internal sealed record PlannedFile(ExportCandidate Candidate, long? DestinationId, PlannedCopy Action, bool Again = false);
|
internal sealed record PlannedFile(ExportCandidate Candidate, long? DestinationId, PlannedCopy Action, bool Again = false)
|
||||||
|
{
|
||||||
|
/// <summary>The variant asked (the request, D2 of tappa E3): Whole, Converted or Frame.</summary>
|
||||||
|
public ExportVariant Variant { get; init; } = ExportVariant.Whole;
|
||||||
|
|
||||||
|
/// <summary>The format asked.</summary>
|
||||||
|
public ExportFormat Format { get; init; } = ExportFormat.Original;
|
||||||
|
|
||||||
|
/// <summary>The instant asked of a frame.</summary>
|
||||||
|
public TimeSpan? FrameAt { get; init; }
|
||||||
|
|
||||||
|
/// <summary>What the name predicts («circa»).</summary>
|
||||||
|
public ExportPrediction Prediction { get; init; } = ExportPrediction.Whole;
|
||||||
|
|
||||||
|
/// <summary>Frames job: the first planned file of its video (the videos are counted on it).</summary>
|
||||||
|
public bool FirstOfVideo { get; init; }
|
||||||
|
|
||||||
|
/// <summary>Frames job: a video of unknown length, without instants yet («circa» one frame).</summary>
|
||||||
|
public bool UnknownDuration { get; init; }
|
||||||
|
}
|
||||||
|
|
||||||
internal enum PlannedCopy
|
internal enum PlannedCopy
|
||||||
{
|
{
|
||||||
@@ -144,12 +403,19 @@ internal enum PlannedCopy
|
|||||||
RemovedOrSuperseded,
|
RemovedOrSuperseded,
|
||||||
NotExported,
|
NotExported,
|
||||||
Missing,
|
Missing,
|
||||||
|
|
||||||
|
/// <summary>Frames job: a photo of the selection.</summary>
|
||||||
|
PhotoSkipped,
|
||||||
|
|
||||||
|
/// <summary>Frames job: a video over <see cref="ExportFrames.MaxPerVideo"/> frames.</summary>
|
||||||
|
OverCap,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>Counts of a plan while its files go by.</summary>
|
/// <summary>Counts of a plan while its files go by.</summary>
|
||||||
internal sealed class PlanTally
|
internal sealed class PlanTally
|
||||||
{
|
{
|
||||||
private readonly Dictionary<long, (int Files, long Bytes)> _byDestination = [];
|
private readonly Dictionary<long, (int Files, long Bytes)> _byDestination = [];
|
||||||
|
private readonly Dictionary<string, int> _asIs = new(StringComparer.Ordinal);
|
||||||
|
|
||||||
public int Files { get; private set; }
|
public int Files { get; private set; }
|
||||||
|
|
||||||
@@ -163,8 +429,25 @@ internal sealed class PlanTally
|
|||||||
|
|
||||||
public int Missing { get; private set; }
|
public int Missing { get; private set; }
|
||||||
|
|
||||||
|
public int Converted { get; private set; }
|
||||||
|
|
||||||
|
public bool Lossy { get; private set; }
|
||||||
|
|
||||||
|
public int Videos { get; private set; }
|
||||||
|
|
||||||
|
public int PhotosSkipped { get; private set; }
|
||||||
|
|
||||||
|
public int Frames { get; private set; }
|
||||||
|
|
||||||
|
public int OverCap { get; private set; }
|
||||||
|
|
||||||
public void Add(PlannedFile file)
|
public void Add(PlannedFile file)
|
||||||
{
|
{
|
||||||
|
if (file.FirstOfVideo && file.Action is not (PlannedCopy.OverCap or PlannedCopy.NotExported or PlannedCopy.Missing))
|
||||||
|
{
|
||||||
|
Videos++;
|
||||||
|
}
|
||||||
|
|
||||||
switch (file.Action)
|
switch (file.Action)
|
||||||
{
|
{
|
||||||
case PlannedCopy.Missing:
|
case PlannedCopy.Missing:
|
||||||
@@ -173,6 +456,13 @@ internal sealed class PlanTally
|
|||||||
case PlannedCopy.NotExported:
|
case PlannedCopy.NotExported:
|
||||||
NotExported++;
|
NotExported++;
|
||||||
return;
|
return;
|
||||||
|
case PlannedCopy.PhotoSkipped:
|
||||||
|
PhotosSkipped++;
|
||||||
|
return;
|
||||||
|
case PlannedCopy.OverCap:
|
||||||
|
OverCap++;
|
||||||
|
Videos++;
|
||||||
|
return;
|
||||||
case PlannedCopy.AlreadyCopied:
|
case PlannedCopy.AlreadyCopied:
|
||||||
AlreadyCopied++;
|
AlreadyCopied++;
|
||||||
break;
|
break;
|
||||||
@@ -180,7 +470,8 @@ internal sealed class PlanTally
|
|||||||
RemovedOrSuperseded++;
|
RemovedOrSuperseded++;
|
||||||
break;
|
break;
|
||||||
case PlannedCopy.Write:
|
case PlannedCopy.Write:
|
||||||
var bytes = file.Candidate.Bytes ?? 0;
|
var frame = file.Variant == ExportVariant.Frame;
|
||||||
|
var bytes = frame ? 0 : file.Candidate.Bytes ?? 0;
|
||||||
Files++;
|
Files++;
|
||||||
Bytes += bytes;
|
Bytes += bytes;
|
||||||
if (file.Again)
|
if (file.Again)
|
||||||
@@ -188,6 +479,21 @@ internal sealed class PlanTally
|
|||||||
RemovedOrSuperseded++;
|
RemovedOrSuperseded++;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (frame)
|
||||||
|
{
|
||||||
|
Frames++;
|
||||||
|
Lossy |= file.Format == ExportFormat.Jpg;
|
||||||
|
}
|
||||||
|
else if (file.Prediction == ExportPrediction.Converted)
|
||||||
|
{
|
||||||
|
Converted++;
|
||||||
|
Lossy |= file.Format == ExportFormat.Jpg;
|
||||||
|
}
|
||||||
|
else if (file.Prediction == ExportPrediction.AsIs && ExportConversions.AsIsLabel(file.Candidate.RelativePath!) is { } label)
|
||||||
|
{
|
||||||
|
_asIs[label] = _asIs.GetValueOrDefault(label) + 1;
|
||||||
|
}
|
||||||
|
|
||||||
var (f, b) = _byDestination.GetValueOrDefault(file.DestinationId!.Value);
|
var (f, b) = _byDestination.GetValueOrDefault(file.DestinationId!.Value);
|
||||||
_byDestination[file.DestinationId.Value] = (f + 1, b + bytes);
|
_byDestination[file.DestinationId.Value] = (f + 1, b + bytes);
|
||||||
return;
|
return;
|
||||||
@@ -230,7 +536,16 @@ internal sealed class PlanTally
|
|||||||
}
|
}
|
||||||
|
|
||||||
var any = rows.Count > 0 || (await env.Storage.Exports.ListDestinationsAsync(false, ct).ConfigureAwait(false)).Count > 0;
|
var any = rows.Count > 0 || (await env.Storage.Exports.ListDestinationsAsync(false, ct).ConfigureAwait(false)).Count > 0;
|
||||||
return new ExportPlan(Files, Bytes, AlreadyCopied, RemovedOrSuperseded, NotExported, Missing, list, any);
|
return new ExportPlan(Files, Bytes, AlreadyCopied, RemovedOrSuperseded, NotExported, Missing, list, any)
|
||||||
|
{
|
||||||
|
AsIs = _asIs.OrderByDescending(p => p.Value).ThenBy(p => p.Key, StringComparer.Ordinal).Select(p => new ExportPlanAsIs(p.Key, p.Value)).ToList(),
|
||||||
|
Converted = Converted,
|
||||||
|
Lossy = Lossy,
|
||||||
|
Videos = Videos,
|
||||||
|
PhotosSkipped = PhotosSkipped,
|
||||||
|
Frames = Frames,
|
||||||
|
OverCap = OverCap,
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>Destinations that get a run: those with files to write, already copied, or «tolti o superati».</summary>
|
/// <summary>Destinations that get a run: those with files to write, already copied, or «tolti o superati».</summary>
|
||||||
|
|||||||
@@ -12,10 +12,24 @@ public sealed record ExportReport(
|
|||||||
IReadOnlyDictionary<ExportItemState, int> ByState,
|
IReadOnlyDictionary<ExportItemState, int> ByState,
|
||||||
long BytesCopied,
|
long BytesCopied,
|
||||||
IReadOnlyList<ExportReportAccount> Accounts,
|
IReadOnlyList<ExportReportAccount> Accounts,
|
||||||
IReadOnlyList<ExportReportLine> Problems);
|
IReadOnlyList<ExportReportLine> Problems)
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Tappa E3: at most <see cref="ExportReports.MaxProblems"/> files copied or adopted with a note (copied as they
|
||||||
|
/// are, what a conversion did not keep, a free name).
|
||||||
|
/// </summary>
|
||||||
|
public IReadOnlyList<ExportReportLine> Notes { get; init; } = [];
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>The files of one account in a job («Copiato» counts written and adopted files).</summary>
|
/// <summary>The files of one account in a job («Copiato» counts written and adopted files).</summary>
|
||||||
public sealed record ExportReportAccount(long? AccountId, string Username, int Copied, int AlreadyCopied, int Skipped, int Failed);
|
public sealed record ExportReportAccount(long? AccountId, string Username, int Copied, int AlreadyCopied, int Skipped, int Failed)
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Tappa E3: the files copied as they are, by kind («HEIC», «AVIF», «raw», «animata», «video», «altro»): the exact
|
||||||
|
/// counts of the job, where the plan's are predictions.
|
||||||
|
/// </summary>
|
||||||
|
public IReadOnlyDictionary<string, int> AsIs { get; init; } = new Dictionary<string, int>();
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>A file of the report, with its reason in Italian.</summary>
|
/// <summary>A file of the report, with its reason in Italian.</summary>
|
||||||
public sealed record ExportReportLine(long ItemId, string Username, string? RelativePath, ExportItemState State, string Text);
|
public sealed record ExportReportLine(long ItemId, string Username, string? RelativePath, ExportItemState State, string Text);
|
||||||
@@ -45,6 +59,8 @@ public sealed class ExportReports(ExportEnvironment env)
|
|||||||
|
|
||||||
var accounts = new Dictionary<long, int[]>();
|
var accounts = new Dictionary<long, int[]>();
|
||||||
var problems = new List<ExportReportLine>();
|
var problems = new List<ExportReportLine>();
|
||||||
|
var notes = new List<ExportReportLine>();
|
||||||
|
var asIs = new Dictionary<long, Dictionary<string, int>>();
|
||||||
long bytes = 0;
|
long bytes = 0;
|
||||||
long after = 0;
|
long after = 0;
|
||||||
while (true)
|
while (true)
|
||||||
@@ -68,6 +84,21 @@ public sealed class ExportReports(ExportEnvironment env)
|
|||||||
{
|
{
|
||||||
case ExportItemState.Copied or ExportItemState.Adopted:
|
case ExportItemState.Copied or ExportItemState.Adopted:
|
||||||
row[0]++;
|
row[0]++;
|
||||||
|
if (AsIsLabel(item.Note) is { } label)
|
||||||
|
{
|
||||||
|
if (!asIs.TryGetValue(key, out var kinds))
|
||||||
|
{
|
||||||
|
asIs[key] = kinds = new Dictionary<string, int>(StringComparer.Ordinal);
|
||||||
|
}
|
||||||
|
|
||||||
|
kinds[label] = kinds.GetValueOrDefault(label) + 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (item.Note is not null && notes.Count < MaxProblems && ExportText.Note(item.Note) is { } noted)
|
||||||
|
{
|
||||||
|
notes.Add(new ExportReportLine(item.Id, Name(item.AccountId), item.RelativePath, item.State, noted));
|
||||||
|
}
|
||||||
|
|
||||||
if (item.CopyId is { } copyId && await exports.GetCopyAsync(copyId, ct).ConfigureAwait(false) is { Bytes: { } b })
|
if (item.CopyId is { } copyId && await exports.GetCopyAsync(copyId, ct).ConfigureAwait(false) is { Bytes: { } b })
|
||||||
{
|
{
|
||||||
bytes += b;
|
bytes += b;
|
||||||
@@ -98,9 +129,42 @@ public sealed class ExportReports(ExportEnvironment env)
|
|||||||
}
|
}
|
||||||
|
|
||||||
var perAccount = accounts
|
var perAccount = accounts
|
||||||
.Select(a => new ExportReportAccount(a.Key == 0 ? null : a.Key, Name(a.Key == 0 ? null : a.Key), a.Value[0], a.Value[1], a.Value[2], a.Value[3]))
|
.Select(a => new ExportReportAccount(a.Key == 0 ? null : a.Key, Name(a.Key == 0 ? null : a.Key), a.Value[0], a.Value[1], a.Value[2], a.Value[3])
|
||||||
|
{
|
||||||
|
AsIs = asIs.TryGetValue(a.Key, out var kinds) ? kinds : new Dictionary<string, int>(),
|
||||||
|
})
|
||||||
.OrderBy(a => a.Username, StringComparer.OrdinalIgnoreCase)
|
.OrderBy(a => a.Username, StringComparer.OrdinalIgnoreCase)
|
||||||
.ToList();
|
.ToList();
|
||||||
return new ExportReport(run, destination, summary.Total, summary.ByState, bytes, perAccount, problems);
|
return new ExportReport(run, destination, summary.Total, summary.ByState, bytes, perAccount, problems) { Notes = notes };
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The kind of a file copied as it is, from the codes of its note; null when it was not.</summary>
|
||||||
|
internal static string? AsIsLabel(string? note)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(note))
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach (var code in note.Split(' ', StringSplitOptions.RemoveEmptyEntries))
|
||||||
|
{
|
||||||
|
var name = code.Split(':', 2)[0];
|
||||||
|
var label = name switch
|
||||||
|
{
|
||||||
|
ExportText.Notes.AsIsHeif => "HEIC",
|
||||||
|
ExportText.Notes.AsIsAvif => "AVIF",
|
||||||
|
ExportText.Notes.AsIsRaw => "raw",
|
||||||
|
ExportText.Notes.AsIsAnimated => "animata",
|
||||||
|
ExportText.Notes.AsIsNotRemuxable => "video",
|
||||||
|
_ when name.StartsWith("AsIs", StringComparison.Ordinal) => "altro",
|
||||||
|
_ => null,
|
||||||
|
};
|
||||||
|
if (label is not null)
|
||||||
|
{
|
||||||
|
return label;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -11,6 +11,53 @@ internal static class ExportRunSettings
|
|||||||
{
|
{
|
||||||
public static string CopyAgainKey(long runId) => string.Create(CultureInfo.InvariantCulture, $"esportazione.lavoro.{runId}.copia-di-nuovo");
|
public static string CopyAgainKey(long runId) => string.Create(CultureInfo.InvariantCulture, $"esportazione.lavoro.{runId}.copia-di-nuovo");
|
||||||
|
|
||||||
|
/// <summary>How the frames of a frames job were asked (tappa E3): <c>Istante</c>, <c>Ogni</c> or <c>Numero:N</c>.</summary>
|
||||||
|
public static string FramesKey(long runId) => string.Create(CultureInfo.InvariantCulture, $"esportazione.lavoro.{runId}.fotogrammi");
|
||||||
|
|
||||||
|
/// <summary>«Copia di nuovo» of one copy row: only its exact identity is looked up (decision D11 of tappa E3).</summary>
|
||||||
|
public static string ExactKey(long runId) => string.Create(CultureInfo.InvariantCulture, $"esportazione.lavoro.{runId}.esatta");
|
||||||
|
|
||||||
|
/// <summary>The frames request of a job, or null for a job of whole or converted files.</summary>
|
||||||
|
public static async Task<(FrameMode Mode, int Count)?> GetFramesAsync(ISettingsStore store, long runId, CancellationToken ct)
|
||||||
|
{
|
||||||
|
var text = (await store.GetAsync(FramesKey(runId), ct).ConfigureAwait(false))?.Trim();
|
||||||
|
if (text is null)
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (string.Equals(text, "Istante", StringComparison.Ordinal))
|
||||||
|
{
|
||||||
|
return (FrameMode.At, 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (string.Equals(text, "Ogni", StringComparison.Ordinal))
|
||||||
|
{
|
||||||
|
return (FrameMode.Every, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
return text.StartsWith("Numero:", StringComparison.Ordinal)
|
||||||
|
&& int.TryParse(text.AsSpan("Numero:".Length), NumberStyles.None, CultureInfo.InvariantCulture, out var count) && count > 0
|
||||||
|
? (FrameMode.Count, count)
|
||||||
|
: null;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Task SetFramesAsync(ISettingsStore store, long runId, FrameMode mode, int count, CancellationToken ct) =>
|
||||||
|
store.SetAsync(
|
||||||
|
FramesKey(runId),
|
||||||
|
mode switch
|
||||||
|
{
|
||||||
|
FrameMode.At => "Istante",
|
||||||
|
FrameMode.Every => "Ogni",
|
||||||
|
_ => string.Create(CultureInfo.InvariantCulture, $"Numero:{count}"),
|
||||||
|
},
|
||||||
|
ct);
|
||||||
|
|
||||||
|
public static async Task<bool> GetExactAsync(ISettingsStore store, long runId, CancellationToken ct) =>
|
||||||
|
string.Equals((await store.GetAsync(ExactKey(runId), ct).ConfigureAwait(false))?.Trim(), "1", StringComparison.Ordinal);
|
||||||
|
|
||||||
|
public static Task SetExactAsync(ISettingsStore store, long runId, CancellationToken ct) => store.SetAsync(ExactKey(runId), "1", ct);
|
||||||
|
|
||||||
/// <summary>«Copia di nuovo anche i tolti o superati» was chosen for this job (decision D9).</summary>
|
/// <summary>«Copia di nuovo anche i tolti o superati» was chosen for this job (decision D9).</summary>
|
||||||
public static async Task<bool> GetCopyAgainAsync(ISettingsStore store, long runId, CancellationToken ct)
|
public static async Task<bool> GetCopyAgainAsync(ISettingsStore store, long runId, CancellationToken ct)
|
||||||
{
|
{
|
||||||
@@ -21,6 +68,14 @@ internal static class ExportRunSettings
|
|||||||
public static Task SetCopyAgainAsync(ISettingsStore store, long runId, bool value, CancellationToken ct) =>
|
public static Task SetCopyAgainAsync(ISettingsStore store, long runId, bool value, CancellationToken ct) =>
|
||||||
store.SetAsync(CopyAgainKey(runId), value ? "1" : null, ct);
|
store.SetAsync(CopyAgainKey(runId), value ? "1" : null, ct);
|
||||||
|
|
||||||
|
/// <summary>Every key of the job, in one transaction (a run id can be used again after <c>DeleteRunAsync</c>).</summary>
|
||||||
public static Task ClearAsync(ISettingsStore store, long runId, CancellationToken ct) =>
|
public static Task ClearAsync(ISettingsStore store, long runId, CancellationToken ct) =>
|
||||||
store.SetAsync(CopyAgainKey(runId), null, ct);
|
store.SetManyAsync(
|
||||||
|
new Dictionary<string, string?>
|
||||||
|
{
|
||||||
|
[CopyAgainKey(runId)] = null,
|
||||||
|
[FramesKey(runId)] = null,
|
||||||
|
[ExactKey(runId)] = null,
|
||||||
|
},
|
||||||
|
ct);
|
||||||
}
|
}
|
||||||
@@ -15,6 +15,9 @@ namespace Febe.Core.Export;
|
|||||||
public sealed class ExportService : IAsyncDisposable
|
public sealed class ExportService : IAsyncDisposable
|
||||||
{
|
{
|
||||||
private const string BusyText = "C'è già una copia al lavoro: aspetta che finisca o interrompila.";
|
private const string BusyText = "C'è già una copia al lavoro: aspetta che finisca o interrompila.";
|
||||||
|
|
||||||
|
/// <summary>A frames request over <see cref="ExportFrames.MaxPerRequest"/>.</summary>
|
||||||
|
public const string TooManyFramesText = "Più di 20.000 fotogrammi in una richiesta: scegli meno video o un intervallo più lungo";
|
||||||
private const int ItemBatch = 2000;
|
private const int ItemBatch = 2000;
|
||||||
private static readonly TimeSpan ProgressInterval = TimeSpan.FromMilliseconds(250);
|
private static readonly TimeSpan ProgressInterval = TimeSpan.FromMilliseconds(250);
|
||||||
|
|
||||||
@@ -114,9 +117,13 @@ public sealed class ExportService : IAsyncDisposable
|
|||||||
/// recorded and nothing starts.
|
/// recorded and nothing starts.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <exception cref="InvalidOperationException">A copy, an import or a rebuild is running.</exception>
|
/// <exception cref="InvalidOperationException">A copy, an import or a rebuild is running.</exception>
|
||||||
|
/// <exception cref="ArgumentException">
|
||||||
|
/// The request is not valid, or a frames request asks more than 1.000 frames of a video or 20.000 in all (Italian message).
|
||||||
|
/// </exception>
|
||||||
public async Task<ExportStart> StartAsync(ExportJobRequest request, CancellationToken ct = default)
|
public async Task<ExportStart> StartAsync(ExportJobRequest request, CancellationToken ct = default)
|
||||||
{
|
{
|
||||||
ArgumentNullException.ThrowIfNull(request);
|
ArgumentNullException.ThrowIfNull(request);
|
||||||
|
ExportPlanner.Validate(request);
|
||||||
var held = new LeaseHolder();
|
var held = new LeaseHolder();
|
||||||
lock (_gate)
|
lock (_gate)
|
||||||
{
|
{
|
||||||
@@ -160,12 +167,48 @@ public sealed class ExportService : IAsyncDisposable
|
|||||||
var runs = new Dictionary<long, ExportRun>();
|
var runs = new Dictionary<long, ExportRun>();
|
||||||
var pending = new List<ExportItem>();
|
var pending = new List<ExportItem>();
|
||||||
var exports = _env.Storage.Exports;
|
var exports = _env.Storage.Exports;
|
||||||
|
// Frames job: the videos whose length the library does not know are measured once, in the first pass, so that
|
||||||
|
// their frames count against the caps; the recording pass reuses the lengths (they cannot disagree).
|
||||||
|
var lengths = new Dictionary<long, TimeSpan?>();
|
||||||
|
Func<ExportCandidate, CancellationToken, Task<TimeSpan?>>? lengthOf = request.Frames is null
|
||||||
|
? null
|
||||||
|
: async (candidate, token) =>
|
||||||
|
{
|
||||||
|
if (!lengths.TryGetValue(candidate.MediaId, out var length))
|
||||||
|
{
|
||||||
|
length = await ProbeLengthAsync(candidate, token).ConfigureAwait(false);
|
||||||
|
lengths[candidate.MediaId] = length;
|
||||||
|
}
|
||||||
|
|
||||||
|
return length;
|
||||||
|
};
|
||||||
|
if (request.Frames is not null)
|
||||||
|
{
|
||||||
|
// Refused before anything is recorded (D12 of tappa E3): a video over 1.000 frames, more than 20.000 in all.
|
||||||
|
var count = new PlanTally();
|
||||||
|
await foreach (var file in Planner.EnumerateAsync(request, effective, settings, ct, lengthOf).ConfigureAwait(false))
|
||||||
|
{
|
||||||
|
count.Add(file);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (count.OverCap > 0)
|
||||||
|
{
|
||||||
|
throw new ArgumentException(ExportFrames.OverCapMessage, nameof(request));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (count.Frames > ExportFrames.MaxPerRequest)
|
||||||
|
{
|
||||||
|
throw new ArgumentException(TooManyFramesText, nameof(request));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var frameItems = 0;
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
await foreach (var file in Planner.EnumerateAsync(request, effective, settings, ct).ConfigureAwait(false))
|
await foreach (var file in Planner.EnumerateAsync(request, effective, settings, ct, lengthOf).ConfigureAwait(false))
|
||||||
{
|
{
|
||||||
tally.Add(file);
|
tally.Add(file);
|
||||||
if (file.DestinationId is not { } destination || file.Action is PlannedCopy.Missing or PlannedCopy.NotExported)
|
if (file.DestinationId is not { } destination || file.Action is PlannedCopy.Missing or PlannedCopy.NotExported or PlannedCopy.PhotoSkipped or PlannedCopy.OverCap)
|
||||||
{
|
{
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
@@ -176,10 +219,14 @@ public sealed class ExportService : IAsyncDisposable
|
|||||||
new ExportRun { DestinationId = destination, Kind = ExportRunKind.Copy, Origin = request.Origin, State = ExportRunState.Running, StartedAt = _env.Clock.Now },
|
new ExportRun { DestinationId = destination, Kind = ExportRunKind.Copy, Origin = request.Origin, State = ExportRunState.Running, StartedAt = _env.Clock.Now },
|
||||||
CancellationToken.None).ConfigureAwait(false);
|
CancellationToken.None).ConfigureAwait(false);
|
||||||
runs[destination] = run;
|
runs[destination] = run;
|
||||||
if (request.CopyAgain)
|
await RecordRunSettingsAsync(run.Id, request).ConfigureAwait(false);
|
||||||
{
|
}
|
||||||
await ExportRunSettings.SetCopyAgainAsync(_env.Storage.Settings, run.Id, true, CancellationToken.None).ConfigureAwait(false);
|
|
||||||
}
|
// Frame items of one video are added together, in instant order (the copy takes them as one batch).
|
||||||
|
// The first pass already refused more than 20.000: this only guards that it saw the same files.
|
||||||
|
if (file.Variant == ExportVariant.Frame && file.Action == PlannedCopy.Write && ++frameItems > ExportFrames.MaxPerRequest)
|
||||||
|
{
|
||||||
|
throw new ArgumentException(TooManyFramesText, nameof(request));
|
||||||
}
|
}
|
||||||
|
|
||||||
pending.Add(new ExportItem
|
pending.Add(new ExportItem
|
||||||
@@ -188,10 +235,12 @@ public sealed class ExportService : IAsyncDisposable
|
|||||||
MediaId = file.Candidate.MediaId,
|
MediaId = file.Candidate.MediaId,
|
||||||
AccountId = file.Candidate.AccountId,
|
AccountId = file.Candidate.AccountId,
|
||||||
SourceSha256 = file.Candidate.Sha256,
|
SourceSha256 = file.Candidate.Sha256,
|
||||||
Variant = ExportVariant.Whole,
|
Variant = file.Variant,
|
||||||
Format = ExportFormat.Original,
|
Format = file.Format,
|
||||||
|
FrameAt = file.FrameAt,
|
||||||
State = ExportItemState.Pending,
|
State = ExportItemState.Pending,
|
||||||
});
|
});
|
||||||
|
|
||||||
if (pending.Count >= ItemBatch)
|
if (pending.Count >= ItemBatch)
|
||||||
{
|
{
|
||||||
await exports.AddItemsAsync(pending, CancellationToken.None).ConfigureAwait(false);
|
await exports.AddItemsAsync(pending, CancellationToken.None).ConfigureAwait(false);
|
||||||
@@ -235,6 +284,65 @@ public sealed class ExportService : IAsyncDisposable
|
|||||||
return new ExportStart(ordered, plan);
|
return new ExportStart(ordered, plan);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The keys of a new job: cleared first (a run id can be used again after <c>DeleteRunAsync</c>), then what a resume
|
||||||
|
/// needs to know (WP1.2 of tappa E3): «Copia di nuovo», the frames request, the exact identity of «Copia di nuovo»
|
||||||
|
/// of one copy.
|
||||||
|
/// </summary>
|
||||||
|
private async Task RecordRunSettingsAsync(long runId, ExportJobRequest request)
|
||||||
|
{
|
||||||
|
var store = _env.Storage.Settings;
|
||||||
|
var none = CancellationToken.None;
|
||||||
|
await ExportRunSettings.ClearAsync(store, runId, none).ConfigureAwait(false);
|
||||||
|
if (request.CopyAgain)
|
||||||
|
{
|
||||||
|
await ExportRunSettings.SetCopyAgainAsync(store, runId, true, none).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (request.Frames is { } frames)
|
||||||
|
{
|
||||||
|
await ExportRunSettings.SetFramesAsync(store, runId, frames.Mode, frames.Count ?? 0, none).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
else if (request.Exact is { Variant: ExportVariant.Frame })
|
||||||
|
{
|
||||||
|
await ExportRunSettings.SetFramesAsync(store, runId, FrameMode.At, 1, none).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (request.Exact is not null)
|
||||||
|
{
|
||||||
|
await ExportRunSettings.SetExactAsync(store, runId, none).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The length of a video the library does not know, from its headers (only the library file, never the
|
||||||
|
/// destination); null when it cannot be read now (the job then gives it one instant, and the copy tells).
|
||||||
|
/// </summary>
|
||||||
|
private async Task<TimeSpan?> ProbeLengthAsync(ExportCandidate candidate, CancellationToken ct)
|
||||||
|
{
|
||||||
|
var media = await _env.Storage.Media.GetAsync(candidate.MediaId, ct).ConfigureAwait(false);
|
||||||
|
var account = await _env.Storage.Accounts.GetAsync(candidate.AccountId, ct).ConfigureAwait(false);
|
||||||
|
if (media is null || account is null || _env.ResolveSourcePath(account, media) is not { } path)
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
return await Task.Run(
|
||||||
|
() =>
|
||||||
|
{
|
||||||
|
using var stream = _env.FileSystem.OpenRandomAccess(path);
|
||||||
|
return VideoFrameReader.ProbeDuration(stream);
|
||||||
|
},
|
||||||
|
ct).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||||
|
{
|
||||||
|
return null; // not readable now: one instant, the copy tells
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// «Riprendi»: continues unfinished jobs in the background, oldest first. Null: every interrupted or paused one (a
|
/// «Riprendi»: continues unfinished jobs in the background, oldest first. Null: every interrupted or paused one (a
|
||||||
/// paused one checks its destination first and pauses again if it still does not answer).
|
/// paused one checks its destination first and pauses again if it still does not answer).
|
||||||
|
|||||||
@@ -68,18 +68,19 @@ public sealed record ExportSettings(
|
|||||||
public Task SaveAsync(ISettingsStore store, CancellationToken ct = default)
|
public Task SaveAsync(ISettingsStore store, CancellationToken ct = default)
|
||||||
{
|
{
|
||||||
ArgumentNullException.ThrowIfNull(store);
|
ArgumentNullException.ThrowIfNull(store);
|
||||||
return store.SetManyAsync(
|
return store.SetManyAsync(Values(), ct);
|
||||||
new Dictionary<string, string?>
|
|
||||||
{
|
|
||||||
[ExportSettingKeys.PhotoFormat] = PhotoFormat.ToString(),
|
|
||||||
[ExportSettingKeys.VideoFormat] = VideoFormat.ToString(),
|
|
||||||
[ExportSettingKeys.LibraryPhotoFormat] = LibraryPhotoFormat.ToString(),
|
|
||||||
[ExportSettingKeys.LibraryVideoFormat] = LibraryVideoFormat.ToString(),
|
|
||||||
[ExportSettingKeys.SamePost] = SamePost.ToString(),
|
|
||||||
},
|
|
||||||
ct);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>The five keys with their stored values (for a write that stores more with them).</summary>
|
||||||
|
public Dictionary<string, string?> Values() => new(StringComparer.Ordinal)
|
||||||
|
{
|
||||||
|
[ExportSettingKeys.PhotoFormat] = PhotoFormat.ToString(),
|
||||||
|
[ExportSettingKeys.VideoFormat] = VideoFormat.ToString(),
|
||||||
|
[ExportSettingKeys.LibraryPhotoFormat] = LibraryPhotoFormat.ToString(),
|
||||||
|
[ExportSettingKeys.LibraryVideoFormat] = LibraryVideoFormat.ToString(),
|
||||||
|
[ExportSettingKeys.SamePost] = SamePost.ToString(),
|
||||||
|
};
|
||||||
|
|
||||||
/// <summary>The settings from stored values: exact, case-sensitive names; anything else gives the key's default.</summary>
|
/// <summary>The settings from stored values: exact, case-sensitive names; anything else gives the key's default.</summary>
|
||||||
internal static ExportSettings From(IReadOnlyDictionary<string, string> values)
|
internal static ExportSettings From(IReadOnlyDictionary<string, string> values)
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
using Febe.Core.Domain;
|
using Febe.Core.Domain;
|
||||||
|
using Febe.Core.Library.Conversion;
|
||||||
using Febe.Core.Storage;
|
using Febe.Core.Storage;
|
||||||
|
|
||||||
namespace Febe.Core.Export;
|
namespace Febe.Core.Export;
|
||||||
@@ -25,6 +26,7 @@ public static class ExportSupersession
|
|||||||
}
|
}
|
||||||
|
|
||||||
var old = oldSha256.ToLowerInvariant();
|
var old = oldSha256.ToLowerInvariant();
|
||||||
|
await LibraryConversionsChangedAsync(storage, accountId, old, newSha256.ToLowerInvariant(), at).ConfigureAwait(false);
|
||||||
var users = await storage.Media.FindBySha256Async(old, ct).ConfigureAwait(false);
|
var users = await storage.Media.FindBySha256Async(old, ct).ConfigureAwait(false);
|
||||||
if (users.Any(u => u.Entry.AccountId == accountId && EntryStateRules.IsPresent(u.Media.State)))
|
if (users.Any(u => u.Entry.AccountId == accountId && EntryStateRules.IsPresent(u.Media.State)))
|
||||||
{
|
{
|
||||||
@@ -33,4 +35,31 @@ public static class ExportSupersession
|
|||||||
|
|
||||||
return await storage.Exports.SupersedeCopiesAsync(accountId, old, newSha256.ToLowerInvariant(), at, CancellationToken.None).ConfigureAwait(false);
|
return await storage.Exports.SupersedeCopiesAsync(accountId, old, newSha256.ToLowerInvariant(), at, CancellationToken.None).ConfigureAwait(false);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The conversions for the library of the account's file that now has <paramref name="newSha256"/> (tappa E3,
|
||||||
|
/// WP2.4): a converted file of the old bytes is «Superato» (it stays), the queue and the failures take the new bytes,
|
||||||
|
/// and the file is queued again in the library formats set now.
|
||||||
|
/// </summary>
|
||||||
|
private static async Task LibraryConversionsChangedAsync(IFebeStorage storage, long accountId, string oldSha256, string newSha256, DateTimeOffset at)
|
||||||
|
{
|
||||||
|
var none = CancellationToken.None;
|
||||||
|
var changed = await storage.Conversions.SupersedeAsync(accountId, oldSha256, newSha256, at, none).ConfigureAwait(false);
|
||||||
|
if (changed.Count == 0)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
var media = new List<Media>();
|
||||||
|
foreach (var id in changed)
|
||||||
|
{
|
||||||
|
if (await storage.Media.GetAsync(id, none).ConfigureAwait(false) is { } m)
|
||||||
|
{
|
||||||
|
media.Add(m);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
await LibraryConversionQueue.EnqueueEntryAsync(storage, media, at, none).ConfigureAwait(false);
|
||||||
|
LibraryConversionQueue.Signal();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -1,5 +1,8 @@
|
|||||||
|
using Febe.Core.Codecs.Containers;
|
||||||
|
using Febe.Core.Codecs.Images;
|
||||||
using Febe.Core.Domain;
|
using Febe.Core.Domain;
|
||||||
using Febe.Core.Engine;
|
using Febe.Core.Engine;
|
||||||
|
using Febe.Core.Library.Conversion;
|
||||||
using Febe.Core.Storage;
|
using Febe.Core.Storage;
|
||||||
|
|
||||||
namespace Febe.Core.Export;
|
namespace Febe.Core.Export;
|
||||||
@@ -24,6 +27,22 @@ public static class ExportText
|
|||||||
public const string NameTaken = "NameTaken";
|
public const string NameTaken = "NameTaken";
|
||||||
public const string PathTaken = "PathTaken";
|
public const string PathTaken = "PathTaken";
|
||||||
public const string NotExported = "NotExported";
|
public const string NotExported = "NotExported";
|
||||||
|
|
||||||
|
// Tappa E3 (D19): an item's note is a list of codes separated by spaces, «Code» or «Code:Arg».
|
||||||
|
public const string AsIsHeif = ImageConversionLosses.AsIsHeif;
|
||||||
|
public const string AsIsAvif = ImageConversionLosses.AsIsAvif;
|
||||||
|
public const string AsIsRaw = ImageConversionLosses.AsIsRaw;
|
||||||
|
public const string AsIsAnimated = ImageConversionLosses.AsIsAnimated;
|
||||||
|
public const string AsIsNotDecodable = ImageConversionLosses.AsIsNotDecodable;
|
||||||
|
public const string AsIsDeepColor = ImageConversionLosses.AsIsDeepColor;
|
||||||
|
public const string AsIsCmyk = ImageConversionLosses.AsIsCmyk;
|
||||||
|
public const string AsIsTooLarge = ImageConversionLosses.AsIsTooLarge;
|
||||||
|
public const string AsIsNotRemuxable = MediaConversionResult.AsIsNotRemuxable;
|
||||||
|
public const string FrameNotAvailable = "FrameNotAvailable";
|
||||||
|
public const string TransparencyWhite = ImageConversionLosses.TransparencyWhite;
|
||||||
|
public const string CopiedInAnotherFormat = "CopiedInAnotherFormat";
|
||||||
|
public const string LostTracks = Mp4Remuxer.LostTracks;
|
||||||
|
public const string LostVideoMetadata = Mp4Remuxer.LostVideoMetadata;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>Name of the state of a file of a job.</summary>
|
/// <summary>Name of the state of a file of a job.</summary>
|
||||||
@@ -49,21 +68,95 @@ public static class ExportText
|
|||||||
_ => state.ToString(),
|
_ => state.ToString(),
|
||||||
};
|
};
|
||||||
|
|
||||||
/// <summary>The Italian text of a note code; null for none; an unknown code is shown as it is.</summary>
|
/// <summary>
|
||||||
public static string? Note(string? code) => code switch
|
/// The Italian text of a note: its codes (separated by spaces, D19 of tappa E3) each in Italian, joined with « · »;
|
||||||
|
/// null for none; an unknown code is shown as it is.
|
||||||
|
/// </summary>
|
||||||
|
public static string? Note(string? note)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(note))
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
var codes = note.Split(' ', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
|
||||||
|
return string.Join(" · ", codes.Select(One));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The codes as one note (D19 of tappa E3): the non-empty ones, without repeats, separated by spaces; null for none.</summary>
|
||||||
|
public static string? JoinNotes(IEnumerable<string?> codes)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(codes);
|
||||||
|
var list = codes.Where(c => !string.IsNullOrWhiteSpace(c)).Select(c => c!.Trim()).Distinct(StringComparer.Ordinal).ToList();
|
||||||
|
return list.Count == 0 ? null : string.Join(' ', list);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The reason of «non si porta in MP4», from the code of <see cref="RemuxRefusal"/>.</summary>
|
||||||
|
private static string RemuxReason(string reason) => reason switch
|
||||||
|
{
|
||||||
|
nameof(RemuxRefusal.NotAVideo) => "Febe non lo riconosce come video",
|
||||||
|
nameof(RemuxRefusal.ContainerNotRemuxable) => "contenitore",
|
||||||
|
nameof(RemuxRefusal.VideoCodec) => "codec video",
|
||||||
|
nameof(RemuxRefusal.AudioCodec) => "codec audio",
|
||||||
|
nameof(RemuxRefusal.MissingConfiguration) => "configurazione del codec mancante",
|
||||||
|
nameof(RemuxRefusal.EncodedTrack) => "tracce codificate",
|
||||||
|
nameof(RemuxRefusal.EditList) => "elenco di modifiche",
|
||||||
|
nameof(RemuxRefusal.NoSamples) => "nessun fotogramma",
|
||||||
|
nameof(RemuxRefusal.Unreadable) => "file rovinato",
|
||||||
|
_ => reason,
|
||||||
|
};
|
||||||
|
|
||||||
|
private static string One(string code)
|
||||||
|
{
|
||||||
|
var colon = code.IndexOf(':', StringComparison.Ordinal);
|
||||||
|
var name = colon < 0 ? code : code[..colon];
|
||||||
|
var arg = colon < 0 ? null : code[(colon + 1)..];
|
||||||
|
const string AsIsVideo = "Video copiato com'è: non si porta in MP4 senza ricodificarlo";
|
||||||
|
return name switch
|
||||||
|
{
|
||||||
|
Notes.AsIsNotRemuxable => arg is { Length: > 0 } ? $"{AsIsVideo} ({RemuxReason(arg)})" : AsIsVideo,
|
||||||
|
Notes.LostTracks => arg is { Length: > 0 } ? $"Tracce tolte: {arg}" : "Tracce tolte",
|
||||||
|
_ when arg is null => Note1(code) ?? code,
|
||||||
|
_ => code,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string? Note1(string code) => code switch
|
||||||
{
|
{
|
||||||
null or "" => null,
|
|
||||||
Notes.SourceMissing => "File non presente in libreria",
|
Notes.SourceMissing => "File non presente in libreria",
|
||||||
Notes.AccountRemoved => "L'account è stato rimosso",
|
Notes.AccountRemoved => "L'account è stato rimosso",
|
||||||
Notes.Removed => "Tolto dalla destinazione: non si ricopia da solo («Copia di nuovo»)",
|
Notes.Removed => "Tolto dalla destinazione: non si ricopia da solo («Copia di nuovo»)",
|
||||||
Notes.Superseded => "Superato da un file nuovo della libreria: non si ricopia da solo",
|
Notes.Superseded => "Superato da un file nuovo della libreria: non si ricopia da solo",
|
||||||
Notes.CopiedForAnotherAccount => "Già copiato per un altro account («Una copia sola»)",
|
Notes.CopiedForAnotherAccount => "Già copiato per un altro account («Una copia sola»)",
|
||||||
Notes.SourceChanged => "Il file della libreria non corrisponde a quello registrato",
|
Notes.SourceChanged => "Il file della libreria è cambiato durante la copia",
|
||||||
Notes.TooLargeForFileSystem => "Più grande di 4 GB: il disco FAT32 non lo accetta",
|
Notes.TooLargeForFileSystem => "Più grande di 4 GB: il disco FAT32 non lo accetta",
|
||||||
Notes.NameTaken => "Nome già occupato da un altro file: copiato con un nome libero",
|
Notes.NameTaken => "Nome già occupato da un altro file: copiato con un nome libero",
|
||||||
Notes.PathTaken => "Percorso preso nel frattempo: riprova",
|
Notes.PathTaken => "Percorso preso nel frattempo: riprova",
|
||||||
Notes.NotExported => "Non si copia qui: «Esporta questo account» è spento, o il file va in un'altra cartella",
|
Notes.NotExported => "Non si copia qui: «Esporta questo account» è spento, o il file va in un'altra cartella",
|
||||||
_ => code,
|
Notes.AsIsHeif => "HEIC copiato com'è",
|
||||||
|
Notes.AsIsAvif => "AVIF copiato com'è",
|
||||||
|
Notes.AsIsRaw => "Raw copiato com'è",
|
||||||
|
Notes.AsIsAnimated => "Immagine animata copiata com'è: convertita perderebbe i fotogrammi dopo il primo",
|
||||||
|
Notes.AsIsNotDecodable => "Copiato com'è: Febe non riesce a leggere l'immagine",
|
||||||
|
Notes.AsIsDeepColor => "Copiato com'è: più di 8 bit per colore",
|
||||||
|
Notes.AsIsCmyk => "Copiato com'è: immagine CMYK",
|
||||||
|
Notes.AsIsTooLarge => "Copiato com'è: troppo grande per il formato scelto",
|
||||||
|
Notes.FrameNotAvailable => "Fotogramma non disponibile per questo video",
|
||||||
|
Notes.TransparencyWhite => "La trasparenza è diventata bianco",
|
||||||
|
Notes.CopiedInAnotherFormat => "Già copiato in un altro formato",
|
||||||
|
ImageConversionLosses.LostTexts => "Non tenuti: testi",
|
||||||
|
ImageConversionLosses.LostColorChunks => "Non tenuti: dati del colore",
|
||||||
|
ImageConversionLosses.LostIcc => "Non tenuto: profilo ICC",
|
||||||
|
ImageConversionLosses.LostIccTooLarge => "Non tenuto: profilo ICC troppo grande",
|
||||||
|
ImageConversionLosses.LostExifTooLarge => "Non tenuto: EXIF troppo grande per JPG",
|
||||||
|
ImageConversionLosses.LostXmpTooLarge => "Non tenuto: XMP troppo grande",
|
||||||
|
ImageConversionLosses.LostExifUnreadable => "Non tenuto: EXIF rovinato",
|
||||||
|
ImageConversionLosses.LostIptc => "Non tenuti: IPTC",
|
||||||
|
ImageConversionLosses.LostOtherSegments => "Non tenuti: altri blocchi",
|
||||||
|
ImageConversionLosses.LostCommentTooLarge => "Non tenuto: commento troppo lungo",
|
||||||
|
ImageConversionLosses.LostExtendedXmp => "Non tenuto: XMP esteso",
|
||||||
|
Notes.LostVideoMetadata => "Non tenuti: metadati del video",
|
||||||
|
_ => null,
|
||||||
};
|
};
|
||||||
|
|
||||||
/// <summary>«1 file copiato», «1.204 file copiati».</summary>
|
/// <summary>«1 file copiato», «1.204 file copiati».</summary>
|
||||||
|
|||||||
@@ -7,6 +7,9 @@ namespace Febe.Core.Import;
|
|||||||
/// <summary>What the comparison decided for one file.</summary>
|
/// <summary>What the comparison decided for one file.</summary>
|
||||||
internal sealed record Comparison(ImportOutcome Outcome, long? MatchedMediaId, DuplicatePair? Pair, string? Note);
|
internal sealed record Comparison(ImportOutcome Outcome, long? MatchedMediaId, DuplicatePair? Pair, string? Note);
|
||||||
|
|
||||||
|
/// <summary>A file of the source that is a converted copy of a library file; its original when known.</summary>
|
||||||
|
internal sealed record ConvertedCopyMatch(long? MediaId);
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// The comparison with the library (spec §9.3), for one analysis session. In this order:
|
/// The comparison with the library (spec §9.3), for one analysis session. In this order:
|
||||||
/// <list type="number">
|
/// <list type="number">
|
||||||
@@ -39,6 +42,9 @@ internal sealed class ImportComparer
|
|||||||
private readonly Dictionary<string, long> _sourceIdentity = new(StringComparer.Ordinal);
|
private readonly Dictionary<string, long> _sourceIdentity = new(StringComparer.Ordinal);
|
||||||
private readonly PerceptualHashIndex _sourceHashes = new();
|
private readonly PerceptualHashIndex _sourceHashes = new();
|
||||||
|
|
||||||
|
// The SHA-256 of the converted copies and frames written in destinations (one read per run, tappa E3, Q37).
|
||||||
|
private IReadOnlySet<string> _copyShas = new HashSet<string>(StringComparer.Ordinal);
|
||||||
|
|
||||||
private ImportComparer(IFebeStorage storage, PerceptualHashIndex library, Func<DateTimeOffset> now)
|
private ImportComparer(IFebeStorage storage, PerceptualHashIndex library, Func<DateTimeOffset> now)
|
||||||
{
|
{
|
||||||
_storage = storage;
|
_storage = storage;
|
||||||
@@ -69,6 +75,7 @@ internal sealed class ImportComparer
|
|||||||
}
|
}
|
||||||
|
|
||||||
var comparer = new ImportComparer(storage, library, now);
|
var comparer = new ImportComparer(storage, library, now);
|
||||||
|
comparer._copyShas = await storage.Exports.LoadConvertedCopyShasAsync(ct).ConfigureAwait(false);
|
||||||
var identifiers = await storage.Imports.LoadLibraryIdentifiersAsync(ct).ConfigureAwait(false);
|
var identifiers = await storage.Imports.LoadLibraryIdentifiersAsync(ct).ConfigureAwait(false);
|
||||||
foreach (var entry in identifiers.Entries)
|
foreach (var entry in identifiers.Entries)
|
||||||
{
|
{
|
||||||
@@ -141,6 +148,13 @@ internal sealed class ImportComparer
|
|||||||
return new Comparison(ImportOutcome.AlreadyInLibrary, deleted.Media.Id, null, ImportText.NoteDeletedByAlberto);
|
return new Comparison(ImportOutcome.AlreadyInLibrary, deleted.Media.Id, null, ImportText.NoteDeletedByAlberto);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// A converted file of the library, or a converted copy or a frame of a destination: already in the library as
|
||||||
|
// its original, never a probable duplicate of it (tappa E3, Q37).
|
||||||
|
if (await IsConvertedCopyAsync(_storage, _copyShas, file.Sha256, ct).ConfigureAwait(false) is { } converted)
|
||||||
|
{
|
||||||
|
return new Comparison(ImportOutcome.AlreadyInLibrary, converted.MediaId, null, ImportText.NoteConvertedCopy);
|
||||||
|
}
|
||||||
|
|
||||||
// 2. Same bytes earlier in the source.
|
// 2. Same bytes earlier in the source.
|
||||||
if (_sourceSha.TryGetValue(file.Sha256, out var twin) && twin.Id != file.Id)
|
if (_sourceSha.TryGetValue(file.Sha256, out var twin) && twin.Id != file.Id)
|
||||||
{
|
{
|
||||||
@@ -177,6 +191,21 @@ internal sealed class ImportComparer
|
|||||||
return new Comparison(ImportOutcome.New, null, null, null);
|
return new Comparison(ImportOutcome.New, null, null, null);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Whether <paramref name="sha256"/> is the SHA-256 of a converted file of the library (with its original's media
|
||||||
|
/// id) or of a converted copy or frame written in a destination (media id null); null when it is neither.
|
||||||
|
/// </summary>
|
||||||
|
internal static async Task<ConvertedCopyMatch?> IsConvertedCopyAsync(IFebeStorage storage, IReadOnlySet<string> copyShas, string sha256, CancellationToken ct)
|
||||||
|
{
|
||||||
|
var conversions = await storage.Conversions.FindBySha256Async(sha256, ct).ConfigureAwait(false);
|
||||||
|
if (conversions.Count > 0)
|
||||||
|
{
|
||||||
|
return new ConvertedCopyMatch(conversions[0].MediaId);
|
||||||
|
}
|
||||||
|
|
||||||
|
return copyShas.Contains(sha256) ? new ConvertedCopyMatch(null) : null;
|
||||||
|
}
|
||||||
|
|
||||||
private async Task<Comparison?> MatchIdentityAsync(ImportFile file, FileHints hints, long? target, CancellationToken ct)
|
private async Task<Comparison?> MatchIdentityAsync(ImportFile file, FileHints hints, long? target, CancellationToken ct)
|
||||||
{
|
{
|
||||||
var candidates = new List<(EntryIdentity Entry, long? MediaId)>();
|
var candidates = new List<(EntryIdentity Entry, long? MediaId)>();
|
||||||
|
|||||||
@@ -258,6 +258,14 @@ public sealed class ImportCopier(ImportEnvironment env)
|
|||||||
return await SaveAsync(file with { State = ImportFileState.Skipped, MatchedMediaId = twin.Media.Id, LastError = ImportText.NoteAlreadyInLibrary }).ConfigureAwait(false);
|
return await SaveAsync(file with { State = ImportFileState.Skipped, MatchedMediaId = twin.Media.Id, LastError = ImportText.NoteAlreadyInLibrary }).ConfigureAwait(false);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// A converted copy of a library file written since the analysis (tappa E3, Q37): never imported as a new file.
|
||||||
|
context.CopyShas ??= await env.Storage.Exports.LoadConvertedCopyShasAsync(ct).ConfigureAwait(false);
|
||||||
|
if (file.EntryId is null && await ImportComparer.IsConvertedCopyAsync(env.Storage, context.CopyShas, file.Sha256!, ct).ConfigureAwait(false) is { } converted)
|
||||||
|
{
|
||||||
|
tally.Skipped++;
|
||||||
|
return await SaveAsync(file with { State = ImportFileState.Skipped, MatchedMediaId = converted.MediaId, LastError = ImportText.NoteConvertedCopy }).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
var account = await env.Storage.Accounts.GetAsync(file.TargetAccountId!.Value, ct).ConfigureAwait(false)
|
var account = await env.Storage.Accounts.GetAsync(file.TargetAccountId!.Value, ct).ConfigureAwait(false)
|
||||||
?? throw new InvalidOperationException("L'account di destinazione non esiste più: associa di nuovo la cartella.");
|
?? throw new InvalidOperationException("L'account di destinazione non esiste più: associa di nuovo la cartella.");
|
||||||
var hints = context.Recognizers.Recognize(new ImportFileContext(context.Layout, file.RelativePath));
|
var hints = context.Recognizers.Recognize(new ImportFileContext(context.Layout, file.RelativePath));
|
||||||
@@ -790,7 +798,11 @@ public sealed class ImportCopier(ImportEnvironment env)
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private sealed record CopyContext(ImportRun Run, SourceLayout Layout, ImportRecognizers Recognizers, LibraryIngest Ingest);
|
private sealed record CopyContext(ImportRun Run, SourceLayout Layout, ImportRecognizers Recognizers, LibraryIngest Ingest)
|
||||||
|
{
|
||||||
|
/// <summary>The SHA-256 of converted copies and frames in destinations, read once per run when first needed.</summary>
|
||||||
|
public IReadOnlySet<string>? CopyShas { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
private sealed class Tally
|
private sealed class Tally
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -139,6 +139,9 @@ public static class ImportText
|
|||||||
internal const string NoteLargerInSource = "Hai scelto di tenere il più grande: è un altro file della sorgente, che prende il posto di quello in libreria.";
|
internal const string NoteLargerInSource = "Hai scelto di tenere il più grande: è un altro file della sorgente, che prende il posto di quello in libreria.";
|
||||||
internal const string NoteNotRecognized = "Né foto né video: ignorato.";
|
internal const string NoteNotRecognized = "Né foto né video: ignorato.";
|
||||||
internal const string NoteAlreadyInLibrary = "Identico a un file già in libreria: saltato.";
|
internal const string NoteAlreadyInLibrary = "Identico a un file già in libreria: saltato.";
|
||||||
|
|
||||||
|
/// <summary>A converted file of the library, a converted copy or a frame written in a destination (tappa E3, Q37).</summary>
|
||||||
|
internal const string NoteConvertedCopy = "È una copia convertita (o un fotogramma) di un file già in libreria.";
|
||||||
internal const string NoteReplaced = "Ha sostituito il file più piccolo della libreria, come hai scelto.";
|
internal const string NoteReplaced = "Ha sostituito il file più piccolo della libreria, come hai scelto.";
|
||||||
internal const string NoteChanged = "Il file è cambiato dopo l'analisi: non è stato copiato. Per prenderlo avvia una nuova importazione della cartella.";
|
internal const string NoteChanged = "Il file è cambiato dopo l'analisi: non è stato copiato. Per prenderlo avvia una nuova importazione della cartella.";
|
||||||
internal const string NoteNotVerified = "La copia in libreria non corrisponde all'originale: l'originale resta al suo posto. Controlla il disco della libreria.";
|
internal const string NoteNotVerified = "La copia in libreria non corrisponde all'originale: l'originale resta al suo posto. Controlla il disco della libreria.";
|
||||||
|
|||||||
@@ -0,0 +1,29 @@
|
|||||||
|
namespace Febe.Core.Library.Conversion;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// One conversion at a time across the process (tappa E3, decision D16): a photo conversion holds a decoded picture
|
||||||
|
/// and its encoder state (up to about a gigabyte for 40 megapixels), so the export and the library conversion take
|
||||||
|
/// turns, each off the calling thread.
|
||||||
|
/// </summary>
|
||||||
|
public sealed class ConversionThrottle
|
||||||
|
{
|
||||||
|
private readonly SemaphoreSlim gate = new(1, 1);
|
||||||
|
|
||||||
|
/// <summary>The throttle every conversion of the process shares.</summary>
|
||||||
|
public static ConversionThrottle Shared { get; } = new();
|
||||||
|
|
||||||
|
/// <summary>Runs <paramref name="work"/> on the thread pool once no other conversion runs.</summary>
|
||||||
|
public async Task<T> RunAsync<T>(Func<CancellationToken, T> work, CancellationToken ct)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(work);
|
||||||
|
await gate.WaitAsync(ct).ConfigureAwait(false);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
return await Task.Run(() => work(ct), ct).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
gate.Release();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,242 @@
|
|||||||
|
using System.Globalization;
|
||||||
|
using Febe.Core.Abstractions;
|
||||||
|
using Febe.Core.Domain;
|
||||||
|
using Febe.Core.Export;
|
||||||
|
using Febe.Core.Storage;
|
||||||
|
|
||||||
|
namespace Febe.Core.Library.Conversion;
|
||||||
|
|
||||||
|
/// <summary>What «Anche i N già in libreria» would queue: files and the bytes of their originals («circa», D17).</summary>
|
||||||
|
public sealed record LibraryConversionPreview(int Files, long Bytes);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The queue of the conversion for the library (tappa E3, D15, WP2.2): what enters it and when. A new file enters after
|
||||||
|
/// its line of <c>_febe.jsonl</c> (<see cref="LibraryIngest.AppendJournalAsync"/>); the files already in the library
|
||||||
|
/// only when Alberto answers «Anche i N già in libreria» to the question asked when the conversion is turned on (Q29);
|
||||||
|
/// a format turned off or changed empties its queue, the converted files stay where they are.
|
||||||
|
/// </summary>
|
||||||
|
public sealed class LibraryConversionQueue(IFebeStorage storage, IClock clock)
|
||||||
|
{
|
||||||
|
/// <summary>«In pausa» (<c>1</c>): the worker converts nothing until it is resumed.</summary>
|
||||||
|
public const string PausedKey = "esportazione.libreria-sospesa";
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Since when (Unix milliseconds) the library format of photos is the one set now: «Solo i nuovi» means the files
|
||||||
|
/// stored in the library from then on (<see cref="Media.DownloadedAt"/>), the others only with «Anche i N».
|
||||||
|
/// </summary>
|
||||||
|
public const string PhotoSinceKey = "esportazione.libreria-formato-foto-dal";
|
||||||
|
|
||||||
|
/// <summary>As <see cref="PhotoSinceKey"/>, for videos.</summary>
|
||||||
|
public const string VideoSinceKey = "esportazione.libreria-formato-video-dal";
|
||||||
|
|
||||||
|
private static readonly Lock SignalGate = new();
|
||||||
|
private static TaskCompletionSource _signal = NewSignal();
|
||||||
|
|
||||||
|
/// <summary>The files «Anche i N già in libreria» would queue for the library formats of <paramref name="settings"/>.</summary>
|
||||||
|
public Task<LibraryConversionPreview> PreviewExistingAsync(ExportSettings settings, CancellationToken ct = default)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(settings);
|
||||||
|
return PreviewExistingAsync(LibraryConversionRules.FormatFor(MediaKind.Photo, settings), LibraryConversionRules.FormatFor(MediaKind.Video, settings), ct);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The files «Anche i N già in libreria» would queue in these formats, one per kind (null: that kind is not asked
|
||||||
|
/// about, as when only the other one is being turned on).
|
||||||
|
/// </summary>
|
||||||
|
public async Task<LibraryConversionPreview> PreviewExistingAsync(ExportFormat? photo, ExportFormat? video, CancellationToken ct = default)
|
||||||
|
{
|
||||||
|
var (files, bytes) = await storage.Conversions.CountExistingAsync(photo, video, ct).ConfigureAwait(false);
|
||||||
|
return new LibraryConversionPreview(files, bytes);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>«Anche i N già in libreria» for both library formats of <paramref name="settings"/>. Returns how many.</summary>
|
||||||
|
public Task<int> EnqueueExistingAsync(ExportSettings settings, CancellationToken ct = default)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(settings);
|
||||||
|
return EnqueueExistingAsync(LibraryConversionRules.FormatFor(MediaKind.Photo, settings), LibraryConversionRules.FormatFor(MediaKind.Video, settings), ct);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// «Anche i N già in libreria»: queues the present files that convert, in one statement per kind, only for the kinds
|
||||||
|
/// given (null: that kind keeps what was answered for it, «Solo i nuovi» included). Returns how many.
|
||||||
|
/// </summary>
|
||||||
|
public async Task<int> EnqueueExistingAsync(ExportFormat? photo, ExportFormat? video, CancellationToken ct = default)
|
||||||
|
{
|
||||||
|
var added = await storage.Conversions.EnqueueExistingAsync(photo, video, clock.Now, ct).ConfigureAwait(false);
|
||||||
|
if (added > 0)
|
||||||
|
{
|
||||||
|
Signal();
|
||||||
|
}
|
||||||
|
|
||||||
|
return added;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Saves the settings <paramref name="after"/> (they were <paramref name="before"/>) with what a change of a library
|
||||||
|
/// format brings, in one transaction: the format, since when it is set (<see cref="PhotoSinceKey"/>) and the
|
||||||
|
/// emptied queue of the format it replaces. A request aborted, a crash or a file stored at that moment never sees
|
||||||
|
/// the new format without its «dal» key, nor the old failures left behind (D17, Q29).
|
||||||
|
/// Turning one on queues nothing here: the interface asks, then calls <see cref="EnqueueExistingAsync"/> only for
|
||||||
|
/// «Anche i N già in libreria».
|
||||||
|
/// </summary>
|
||||||
|
public Task SaveSettingsAsync(ExportSettings before, ExportSettings after, CancellationToken ct = default)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(before);
|
||||||
|
ArgumentNullException.ThrowIfNull(after);
|
||||||
|
var values = after.Values();
|
||||||
|
var (since, formats) = Changes(before, after);
|
||||||
|
foreach (var (key, value) in since)
|
||||||
|
{
|
||||||
|
values[key] = value;
|
||||||
|
}
|
||||||
|
|
||||||
|
return storage.Conversions.SaveSettingsAndDeleteQueuesAsync(values, formats, ct);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The settings were saved by another way: a library format turned off or changed loses its queue and its failures
|
||||||
|
/// that «Riprova» would put back (its converted files and rows stay), and its «dal» key is set, in one transaction.
|
||||||
|
/// <see cref="SaveSettingsAsync"/> stores the settings with them.
|
||||||
|
/// </summary>
|
||||||
|
public Task OnSettingsChangedAsync(ExportSettings before, ExportSettings after, CancellationToken ct = default)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(before);
|
||||||
|
ArgumentNullException.ThrowIfNull(after);
|
||||||
|
var (since, formats) = Changes(before, after);
|
||||||
|
return since.Count == 0 ? Task.CompletedTask : storage.Conversions.SaveSettingsAndDeleteQueuesAsync(since, formats, ct);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// For each kind whose library format changes: its «dal» key (now, or removed when it goes back to «Originale») and
|
||||||
|
/// the format replaced, whose queue goes.
|
||||||
|
/// </summary>
|
||||||
|
private (Dictionary<string, string?> Since, List<ExportFormat> Formats) Changes(ExportSettings before, ExportSettings after)
|
||||||
|
{
|
||||||
|
var since = new Dictionary<string, string?>(StringComparer.Ordinal);
|
||||||
|
var formats = new List<ExportFormat>();
|
||||||
|
foreach (var kind in new[] { MediaKind.Photo, MediaKind.Video })
|
||||||
|
{
|
||||||
|
var old = LibraryConversionRules.FormatFor(kind, before);
|
||||||
|
var now = LibraryConversionRules.FormatFor(kind, after);
|
||||||
|
if (old == now)
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (old is { } format)
|
||||||
|
{
|
||||||
|
formats.Add(format);
|
||||||
|
}
|
||||||
|
|
||||||
|
// The files of the library before now are «già in libreria»: only «Anche i N» queues them.
|
||||||
|
since[SinceKey(kind)] = now is null ? null : clock.Now.ToUnixTimeMilliseconds().ToString(CultureInfo.InvariantCulture);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (since, formats);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// «Riprova»: the failed files of the library formats set now go back to the queue, except those that never convert
|
||||||
|
/// (<c>AsIs*</c>). Returns how many.
|
||||||
|
/// </summary>
|
||||||
|
public async Task<int> RetryFailedAsync(CancellationToken ct = default)
|
||||||
|
{
|
||||||
|
var settings = await ExportSettings.LoadAsync(storage.Settings, ct).ConfigureAwait(false);
|
||||||
|
var formats = new[] { MediaKind.Photo, MediaKind.Video }
|
||||||
|
.Select(kind => LibraryConversionRules.FormatFor(kind, settings))
|
||||||
|
.OfType<ExportFormat>()
|
||||||
|
.ToList();
|
||||||
|
var reset = await storage.Conversions.ResetFailedAsync(formats, clock.Now, ct).ConfigureAwait(false);
|
||||||
|
if (reset > 0)
|
||||||
|
{
|
||||||
|
Signal();
|
||||||
|
}
|
||||||
|
|
||||||
|
return reset;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>«In pausa» or not.</summary>
|
||||||
|
public static async Task<bool> IsPausedAsync(ISettingsStore settings, CancellationToken ct = default)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(settings);
|
||||||
|
return await settings.GetAsync(PausedKey, ct).ConfigureAwait(false) == "1";
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>«Sospendi» / «Riprendi» the conversion for the library.</summary>
|
||||||
|
public async Task SetPausedAsync(bool paused, CancellationToken ct = default)
|
||||||
|
{
|
||||||
|
await storage.Settings.SetAsync(PausedKey, paused ? "1" : "0", ct).ConfigureAwait(false);
|
||||||
|
if (!paused)
|
||||||
|
{
|
||||||
|
Signal();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Queues the new files of an entry by the library formats set now, after its journal line (the hook of
|
||||||
|
/// <see cref="LibraryIngest"/>): those stored in the library since the format was set (<see cref="PhotoSinceKey"/>),
|
||||||
|
/// not the files an old entry already had when a late one arrives (they had their answer, «Solo i nuovi» included).
|
||||||
|
/// Nothing when both formats are «Originale». Returns how many rows were added.
|
||||||
|
/// </summary>
|
||||||
|
public static async Task<int> EnqueueEntryAsync(IFebeStorage storage, IReadOnlyList<Media> media, DateTimeOffset at, CancellationToken ct)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(storage);
|
||||||
|
ArgumentNullException.ThrowIfNull(media);
|
||||||
|
// One read: the formats and their «dal» keys as one change stored them, never a format with an older key.
|
||||||
|
var values = await storage.Settings.GetAllAsync(ct).ConfigureAwait(false);
|
||||||
|
var settings = ExportSettings.From(values);
|
||||||
|
if (!settings.ConvertsLibrary)
|
||||||
|
{
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
var photoSince = Since(values, MediaKind.Photo);
|
||||||
|
var videoSince = Since(values, MediaKind.Video);
|
||||||
|
var requests = LibraryConversionRules.RequestsFor(
|
||||||
|
media.Where(m => (m.Kind == MediaKind.Video ? videoSince : photoSince) is not { } since
|
||||||
|
|| (m.DownloadedAt is { } stored && stored.ToUnixTimeMilliseconds() >= since)),
|
||||||
|
settings);
|
||||||
|
if (requests.Count == 0)
|
||||||
|
{
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
var added = await storage.Conversions.EnqueueAsync(requests, at, ct).ConfigureAwait(false);
|
||||||
|
if (added > 0)
|
||||||
|
{
|
||||||
|
Signal();
|
||||||
|
}
|
||||||
|
|
||||||
|
return added;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string SinceKey(MediaKind kind) => kind == MediaKind.Video ? VideoSinceKey : PhotoSinceKey;
|
||||||
|
|
||||||
|
/// <summary>Since when the library format of this kind is set (Unix ms); null: not recorded, every file is new.</summary>
|
||||||
|
private static long? Since(IReadOnlyDictionary<string, string> values, MediaKind kind) =>
|
||||||
|
long.TryParse(values.GetValueOrDefault(SinceKey(kind)), NumberStyles.Integer, CultureInfo.InvariantCulture, out var ms) ? ms : null;
|
||||||
|
|
||||||
|
/// <summary>Wakes the worker: something entered the queue (or the pause ended).</summary>
|
||||||
|
public static void Signal()
|
||||||
|
{
|
||||||
|
TaskCompletionSource fired;
|
||||||
|
lock (SignalGate)
|
||||||
|
{
|
||||||
|
fired = _signal;
|
||||||
|
_signal = NewSignal();
|
||||||
|
}
|
||||||
|
|
||||||
|
fired.TrySetResult();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>A task that completes at the next <see cref="Signal"/>.</summary>
|
||||||
|
internal static Task NextSignal()
|
||||||
|
{
|
||||||
|
lock (SignalGate)
|
||||||
|
{
|
||||||
|
return _signal.Task;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static TaskCompletionSource NewSignal() => new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||||
|
}
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
using Febe.Core.Domain;
|
||||||
|
using Febe.Core.Export;
|
||||||
|
using Febe.Core.Storage;
|
||||||
|
|
||||||
|
namespace Febe.Core.Library.Conversion;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Which library files the conversion for the library queues (tappa E3, D15, WP2.2): a present file whose extension
|
||||||
|
/// says it converts into the format chosen for its kind (<see cref="ExportConversions.Predict"/> is Converted). A file
|
||||||
|
/// already in that format, HEIC, HEIF, AVIF, raw, GIF and WebM are never queued. The same rule is written in SQL by the
|
||||||
|
/// store (<see cref="ExcludedExtensions"/>).
|
||||||
|
/// </summary>
|
||||||
|
public static class LibraryConversionRules
|
||||||
|
{
|
||||||
|
/// <summary>The format of the conversion for the library of a kind; null when it is off («Originale»).</summary>
|
||||||
|
public static ExportFormat? FormatFor(MediaKind kind, ExportSettings settings)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(settings);
|
||||||
|
var format = kind == MediaKind.Photo ? settings.LibraryPhotoFormat : settings.LibraryVideoFormat;
|
||||||
|
var fits = kind == MediaKind.Photo ? ExportFormats.IsPhotoFormat(format) : ExportFormats.IsVideoFormat(format);
|
||||||
|
return format != ExportFormat.Original && fits ? format : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>True when a file at <paramref name="relativePath"/> of <paramref name="kind"/> is queued for <paramref name="format"/>.</summary>
|
||||||
|
public static bool Converts(string relativePath, MediaKind kind, ExportFormat format)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(relativePath);
|
||||||
|
var fits = kind == MediaKind.Photo ? ExportFormats.IsPhotoFormat(format) : ExportFormats.IsVideoFormat(format);
|
||||||
|
return format != ExportFormat.Original && fits && ExportConversions.Predict(relativePath, kind, format) == ExportPrediction.Converted;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The extensions (with their dot, lower case) of the files that are not queued for <paramref name="format"/>: the
|
||||||
|
/// format's own and the ones copied as they are. Equivalent to <see cref="Converts"/> on the extension.
|
||||||
|
/// </summary>
|
||||||
|
public static IReadOnlyList<string> ExcludedExtensions(ExportFormat format)
|
||||||
|
{
|
||||||
|
var own = format switch
|
||||||
|
{
|
||||||
|
ExportFormat.Jpg => new[] { ".jpg", ".jpeg" },
|
||||||
|
ExportFormat.Png => [".png"],
|
||||||
|
ExportFormat.WebpLossless => [".webp"],
|
||||||
|
ExportFormat.Mp4 => [".mp4"],
|
||||||
|
_ => throw new ArgumentOutOfRangeException(nameof(format), "La conversione della libreria ha un formato diverso dall'originale."),
|
||||||
|
};
|
||||||
|
return [.. own, ".heic", ".heif", ".avif", ".gif", ".webm", .. MediaConverter.RawExtensionList.Select(e => e.ToLowerInvariant()).Order(StringComparer.Ordinal)];
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The conversions to queue for the present files of an entry, by the settings now.</summary>
|
||||||
|
public static IReadOnlyList<MediaConversionRequest> RequestsFor(IEnumerable<Media> media, ExportSettings settings)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(media);
|
||||||
|
ArgumentNullException.ThrowIfNull(settings);
|
||||||
|
var list = new List<MediaConversionRequest>();
|
||||||
|
foreach (var m in media)
|
||||||
|
{
|
||||||
|
if (EntryStateRules.IsPresent(m.State) && m.Sha256 is { Length: 64 } sha && m.RelativePath is { } path
|
||||||
|
&& FormatFor(m.Kind, settings) is { } format && Converts(path, m.Kind, format))
|
||||||
|
{
|
||||||
|
list.Add(new MediaConversionRequest(m.Id, format, sha));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return list;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,72 @@
|
|||||||
|
using Febe.Core.Codecs.Images;
|
||||||
|
using Febe.Core.Export;
|
||||||
|
|
||||||
|
namespace Febe.Core.Library.Conversion;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The codes of <c>media_conversion.last_error</c> (tappa E3, D19) and their Italian texts. A Failed row carries why it
|
||||||
|
/// failed (an <c>AsIs*</c> code first when the file never converts); a Converted row carries what was not kept.
|
||||||
|
/// </summary>
|
||||||
|
public static class LibraryConversionText
|
||||||
|
{
|
||||||
|
/// <summary>The original is not in the library folder.</summary>
|
||||||
|
public const string SourceMissing = ExportText.Notes.SourceMissing;
|
||||||
|
|
||||||
|
/// <summary>The original's bytes are not the ones recorded.</summary>
|
||||||
|
public const string SourceChanged = ExportText.Notes.SourceChanged;
|
||||||
|
|
||||||
|
/// <summary>The account folder is not there (an unplugged disk): it is never created.</summary>
|
||||||
|
public const string AccountFolderMissing = "AccountFolderMissing";
|
||||||
|
|
||||||
|
/// <summary>The prefix of an unexpected failure; the exception's type name follows the colon.</summary>
|
||||||
|
public const string Error = "Error";
|
||||||
|
|
||||||
|
/// <summary>The prefix of the codes of files that never convert.</summary>
|
||||||
|
public const string AsIsPrefix = "AsIs";
|
||||||
|
|
||||||
|
/// <summary>«In pausa» for low space (D17).</summary>
|
||||||
|
public const string LowSpace = "Spazio libero sotto la soglia: la conversione della libreria è in pausa";
|
||||||
|
|
||||||
|
/// <summary>Waiting for the end of an engine session.</summary>
|
||||||
|
public const string InSession = "Il motore è in sessione: la conversione della libreria riprende dopo";
|
||||||
|
|
||||||
|
/// <summary>Waiting for an import, a copy or a rebuild.</summary>
|
||||||
|
public const string LongWork = "Un'importazione, una copia o una ricostruzione è al lavoro: la conversione della libreria riprende dopo";
|
||||||
|
|
||||||
|
/// <summary>True when the codes of a Failed row say the file never converts.</summary>
|
||||||
|
public static bool IsAsIs(string? codes) => codes is not null && codes.TrimStart().StartsWith(AsIsPrefix, StringComparison.Ordinal);
|
||||||
|
|
||||||
|
/// <summary>The Italian text of a list of codes («·» between them); unknown codes are shown as they are.</summary>
|
||||||
|
public static string? Note(string? codes)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(codes))
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return string.Join(" · ", codes.Split(' ', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries).Select(One));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string One(string code)
|
||||||
|
{
|
||||||
|
var colon = code.IndexOf(':', StringComparison.Ordinal);
|
||||||
|
var name = colon < 0 ? code : code[..colon];
|
||||||
|
return name switch
|
||||||
|
{
|
||||||
|
SourceMissing => "File non presente in libreria",
|
||||||
|
SourceChanged => "Il file della libreria non è quello registrato",
|
||||||
|
AccountFolderMissing => "La cartella dell'account non c'è: ricollega il disco e riprova",
|
||||||
|
Error => "Conversione non riuscita: riprova",
|
||||||
|
ImageConversionLosses.AsIsHeif => "Non si converte: HEIC",
|
||||||
|
ImageConversionLosses.AsIsAvif => "Non si converte: AVIF",
|
||||||
|
ImageConversionLosses.AsIsRaw => "Non si converte: raw",
|
||||||
|
ImageConversionLosses.AsIsAnimated => "Non si converte: immagine animata (perderebbe i fotogrammi dopo il primo)",
|
||||||
|
ImageConversionLosses.AsIsNotDecodable => "Non si converte: Febe non riesce a leggere l'immagine",
|
||||||
|
ImageConversionLosses.AsIsDeepColor => "Non si converte: più di 8 bit per colore",
|
||||||
|
ImageConversionLosses.AsIsCmyk => "Non si converte: immagine CMYK",
|
||||||
|
ImageConversionLosses.AsIsTooLarge => "Non si converte: troppo grande per il formato scelto",
|
||||||
|
MediaConversionResult.AsIsNotRemuxable => "Non si porta in MP4 senza ricodificarlo" + (ExportText.Note(code) is { } t && t.IndexOf('(', StringComparison.Ordinal) is var i and >= 0 ? " " + t[i..] : string.Empty),
|
||||||
|
_ => ExportText.Note(code) ?? code,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,560 @@
|
|||||||
|
using System.Security.Cryptography;
|
||||||
|
using Febe.Core.Abstractions;
|
||||||
|
using Febe.Core.Alerts;
|
||||||
|
using Febe.Core.Domain;
|
||||||
|
using Febe.Core.Export;
|
||||||
|
using Febe.Core.Storage;
|
||||||
|
|
||||||
|
namespace Febe.Core.Library.Conversion;
|
||||||
|
|
||||||
|
/// <summary>What the conversion for the library needs from the rest of Febe (tappa E3, WP2.2).</summary>
|
||||||
|
public sealed record LibraryConversionEnvironment
|
||||||
|
{
|
||||||
|
public required IFebeStorage Storage { get; init; }
|
||||||
|
|
||||||
|
/// <summary>The library folder and account folders now (on Windows it can change while Febe runs).</summary>
|
||||||
|
public required Func<LibraryLayout> Layout { get; init; }
|
||||||
|
|
||||||
|
public required IClock Clock { get; init; }
|
||||||
|
|
||||||
|
/// <summary>Shared with import, export, rebuild and frame download, which pre-empt the conversion. Null: nothing to yield to (tests).</summary>
|
||||||
|
public LongWorkGate? Gate { get; init; }
|
||||||
|
|
||||||
|
/// <summary>The conversion never runs during an engine session.</summary>
|
||||||
|
public IEngineSessionState Session { get; init; } = NoEngineSession.Instance;
|
||||||
|
|
||||||
|
/// <summary>One conversion at a time in the process (D16): shared with the copies to external folders.</summary>
|
||||||
|
public ConversionThrottle Throttle { get; init; } = ConversionThrottle.Shared;
|
||||||
|
|
||||||
|
/// <summary>The free space of the disk of an account folder.</summary>
|
||||||
|
public IFreeSpaceProbe FreeSpace { get; init; } = new DriveFreeSpaceProbe();
|
||||||
|
|
||||||
|
/// <summary>Below this, once the file is written, the conversion pauses (D17): the alerts' «quasi pieno».</summary>
|
||||||
|
public DiskThresholds Thresholds { get; init; } = DiskThresholds.Default;
|
||||||
|
|
||||||
|
/// <summary>How long the worker sleeps when nothing wakes it.</summary>
|
||||||
|
public TimeSpan Idle { get; init; } = TimeSpan.FromSeconds(30);
|
||||||
|
|
||||||
|
/// <summary>How often it looks again while it waits for an engine session or a long work to end.</summary>
|
||||||
|
public TimeSpan Poll { get; init; } = TimeSpan.FromSeconds(5);
|
||||||
|
|
||||||
|
/// <summary>Rows read from the queue at a time.</summary>
|
||||||
|
public int BatchSize { get; init; } = 50;
|
||||||
|
|
||||||
|
/// <summary>One line for the log: only Italian text and exception type names, never paths or messages.</summary>
|
||||||
|
public Action<string>? Log { get; init; }
|
||||||
|
|
||||||
|
/// <summary>Test seam: runs once the converted file is on disk, before its record.</summary>
|
||||||
|
public Func<MediaConversion, CancellationToken, Task>? AfterWrite { get; init; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The conversion for the library as the interface shows it.</summary>
|
||||||
|
/// <param name="Pending">Files in the queue.</param>
|
||||||
|
/// <param name="Converted">Files converted.</param>
|
||||||
|
/// <param name="Failed">Files that failed and can be tried again («Riprova»).</param>
|
||||||
|
/// <param name="AsIs">Files that never convert («non si convertono»).</param>
|
||||||
|
/// <param name="Paused">«In pausa» by Alberto.</param>
|
||||||
|
/// <param name="Waiting">Why it waits now (an engine session, a long work, low space), or null.</param>
|
||||||
|
/// <param name="CurrentMediaId">The library file being converted now, or null.</param>
|
||||||
|
public sealed record LibraryConversionStatus(int Pending, int Converted, int Failed, int AsIs, bool Paused, string? Waiting, long? CurrentMediaId);
|
||||||
|
|
||||||
|
/// <summary>What one pass over the queue did.</summary>
|
||||||
|
/// <param name="Converted">Files converted (or adopted).</param>
|
||||||
|
/// <param name="Done">Rows settled: converted, dropped (already in the format), failed.</param>
|
||||||
|
/// <param name="Again">True when the pass stopped early and should look again soon (session, long work, pre-emption).</param>
|
||||||
|
public sealed record LibraryConversionPass(int Converted, int Done, bool Again);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The conversion for the library (tappa E3, spec §4.10, D15-D18): adds, next to an original, the same file in the
|
||||||
|
/// format chosen for its kind, as a new file with the same stem and a free name. The original, its record, its
|
||||||
|
/// thumbnail, perceptual hash and journal line stay as they are; the converted file is only a <c>media_conversion</c>
|
||||||
|
/// row. It runs in the background through <see cref="RunAsync"/> (started by the composition, never in the demo),
|
||||||
|
/// yields to import, export, rebuild and frame download (<see cref="LongWorkGate.BackgroundLease"/>), never runs during
|
||||||
|
/// an engine session and pauses when the disk is almost full.
|
||||||
|
/// </summary>
|
||||||
|
public sealed class LibraryConversionWorker(LibraryConversionEnvironment env)
|
||||||
|
{
|
||||||
|
private readonly LibraryConversionEnvironment _env = env ?? throw new ArgumentNullException(nameof(env));
|
||||||
|
private volatile string? _waiting;
|
||||||
|
private long _current;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The file that last paused the conversion for space, with the length its converted file needs: until the disk
|
||||||
|
/// has room for that too, the original is not read (hashed, decoded or remuxed) again at every wake-up (D17).
|
||||||
|
/// </summary>
|
||||||
|
private volatile LowSpaceMark? _lowSpace;
|
||||||
|
|
||||||
|
private sealed record LowSpaceMark(long RowId, string SourceSha256, long Needed);
|
||||||
|
|
||||||
|
/// <summary>The counts of the store with what the worker is doing now.</summary>
|
||||||
|
public async Task<LibraryConversionStatus> StatusAsync(CancellationToken ct = default)
|
||||||
|
{
|
||||||
|
var counts = await _env.Storage.Conversions.CountByStateAsync(ct).ConfigureAwait(false);
|
||||||
|
var paused = await LibraryConversionQueue.IsPausedAsync(_env.Storage.Settings, ct).ConfigureAwait(false);
|
||||||
|
var current = Interlocked.Read(ref _current);
|
||||||
|
return new LibraryConversionStatus(counts.Pending, counts.Converted, counts.Failed, counts.AsIs, paused, paused ? null : _waiting, current == 0 ? null : current);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The loop: a pass over the queue, then a wait for <see cref="LibraryConversionQueue.Signal"/> or
|
||||||
|
/// <see cref="LibraryConversionEnvironment.Idle"/>. A failure of a pass is logged by type and the loop goes on; it
|
||||||
|
/// ends with <paramref name="ct"/>.
|
||||||
|
/// </summary>
|
||||||
|
public async Task RunAsync(CancellationToken ct)
|
||||||
|
{
|
||||||
|
while (!ct.IsCancellationRequested)
|
||||||
|
{
|
||||||
|
var wait = _env.Idle;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var pass = await RunOnceAsync(ct).ConfigureAwait(false);
|
||||||
|
if (pass.Again)
|
||||||
|
{
|
||||||
|
wait = _env.Poll;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (OperationCanceledException) when (ct.IsCancellationRequested)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_env.Log?.Invoke($"La conversione della libreria si è fermata per un errore ({ex.GetType().Name}): riprova fra poco.");
|
||||||
|
}
|
||||||
|
|
||||||
|
using var stop = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
||||||
|
var signal = LibraryConversionQueue.NextSignal();
|
||||||
|
var delay = _env.Clock.Delay(wait, stop.Token);
|
||||||
|
await Task.WhenAny(signal, delay).ConfigureAwait(false);
|
||||||
|
await stop.CancelAsync().ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>One pass over the queue, in order, until it is empty or something stops it.</summary>
|
||||||
|
public async Task<LibraryConversionPass> RunOnceAsync(CancellationToken ct = default)
|
||||||
|
{
|
||||||
|
var storage = _env.Storage;
|
||||||
|
if (await LibraryConversionQueue.IsPausedAsync(storage.Settings, ct).ConfigureAwait(false))
|
||||||
|
{
|
||||||
|
_waiting = null;
|
||||||
|
return new LibraryConversionPass(0, 0, false);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (_env.Session.InSession)
|
||||||
|
{
|
||||||
|
_waiting = LibraryConversionText.InSession;
|
||||||
|
return new LibraryConversionPass(0, 0, true);
|
||||||
|
}
|
||||||
|
|
||||||
|
if ((await storage.Conversions.ListPendingAsync(0, 1, ct).ConfigureAwait(false)).Count == 0)
|
||||||
|
{
|
||||||
|
_waiting = null;
|
||||||
|
return new LibraryConversionPass(0, 0, false);
|
||||||
|
}
|
||||||
|
|
||||||
|
LongWorkGate.BackgroundLease? lease = null;
|
||||||
|
if (_env.Gate is { } gate && !gate.TryEnterBackground(out lease))
|
||||||
|
{
|
||||||
|
_waiting = LibraryConversionText.LongWork;
|
||||||
|
return new LibraryConversionPass(0, 0, true);
|
||||||
|
}
|
||||||
|
|
||||||
|
using (lease)
|
||||||
|
{
|
||||||
|
using var linked = CancellationTokenSource.CreateLinkedTokenSource(ct, lease?.Preempted ?? CancellationToken.None);
|
||||||
|
var token = linked.Token;
|
||||||
|
_waiting = null;
|
||||||
|
var converted = 0;
|
||||||
|
var done = 0;
|
||||||
|
var after = 0L;
|
||||||
|
while (true)
|
||||||
|
{
|
||||||
|
var rows = await storage.Conversions.ListPendingAsync(after, _env.BatchSize, ct).ConfigureAwait(false);
|
||||||
|
if (rows.Count == 0)
|
||||||
|
{
|
||||||
|
return new LibraryConversionPass(converted, done, false);
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach (var row in rows)
|
||||||
|
{
|
||||||
|
after = row.Id;
|
||||||
|
if (token.IsCancellationRequested || _env.Session.InSession
|
||||||
|
|| await LibraryConversionQueue.IsPausedAsync(storage.Settings, ct).ConfigureAwait(false))
|
||||||
|
{
|
||||||
|
ct.ThrowIfCancellationRequested();
|
||||||
|
return new LibraryConversionPass(converted, done, true);
|
||||||
|
}
|
||||||
|
|
||||||
|
var outcome = await ConvertOneAsync(row, lease, token, ct).ConfigureAwait(false);
|
||||||
|
switch (outcome)
|
||||||
|
{
|
||||||
|
case Outcome.Converted:
|
||||||
|
converted++;
|
||||||
|
done++;
|
||||||
|
break;
|
||||||
|
case Outcome.Settled:
|
||||||
|
done++;
|
||||||
|
break;
|
||||||
|
case Outcome.LowSpace:
|
||||||
|
_waiting = LibraryConversionText.LowSpace;
|
||||||
|
return new LibraryConversionPass(converted, done, false);
|
||||||
|
case Outcome.Stopped:
|
||||||
|
ct.ThrowIfCancellationRequested();
|
||||||
|
return new LibraryConversionPass(converted, done, true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private enum Outcome
|
||||||
|
{
|
||||||
|
Converted,
|
||||||
|
Settled,
|
||||||
|
Skipped,
|
||||||
|
LowSpace,
|
||||||
|
Stopped,
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task<Outcome> ConvertOneAsync(MediaConversion row, LongWorkGate.BackgroundLease? lease, CancellationToken token, CancellationToken ct)
|
||||||
|
{
|
||||||
|
Interlocked.Exchange(ref _current, row.MediaId);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
return await ConvertAsync(row, lease, token).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
catch (OperationCanceledException) when (token.IsCancellationRequested)
|
||||||
|
{
|
||||||
|
// Pre-empted, or Febe stops: our temporary file is gone, the row stays in the queue.
|
||||||
|
return Outcome.Stopped;
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
// One file never stops the queue: the reason goes to the row (codes, D19), the log gets the type only.
|
||||||
|
_env.Log?.Invoke($"Un file non si è convertito per la libreria ({ex.GetType().Name}).");
|
||||||
|
await FailAsync(row, $"{LibraryConversionText.Error}:{ex.GetType().Name}").ConfigureAwait(false);
|
||||||
|
ct.ThrowIfCancellationRequested();
|
||||||
|
return Outcome.Settled;
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Interlocked.Exchange(ref _current, 0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task<Outcome> ConvertAsync(MediaConversion row, LongWorkGate.BackgroundLease? lease, CancellationToken token)
|
||||||
|
{
|
||||||
|
var storage = _env.Storage;
|
||||||
|
var media = await storage.Media.GetAsync(row.MediaId, token).ConfigureAwait(false);
|
||||||
|
if (media is null || !EntryStateRules.IsPresent(media.State) || media.RelativePath is null || media.Sha256 is not { Length: 64 })
|
||||||
|
{
|
||||||
|
// Not in the library (deleted meanwhile, or never stored): nothing to convert.
|
||||||
|
await storage.Conversions.DeletePendingRowAsync(row.Id, CancellationToken.None).ConfigureAwait(false);
|
||||||
|
return Outcome.Skipped;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Only in the library format set now (§4.10, Q29): a row left in a format turned off or changed (put back by a
|
||||||
|
// supersession, say) is dropped, never converted.
|
||||||
|
var settings = await ExportSettings.LoadAsync(storage.Settings, token).ConfigureAwait(false);
|
||||||
|
if (LibraryConversionRules.FormatFor(media.Kind, settings) != row.Format)
|
||||||
|
{
|
||||||
|
await storage.Conversions.DeletePendingRowAsync(row.Id, CancellationToken.None).ConfigureAwait(false);
|
||||||
|
return Outcome.Skipped;
|
||||||
|
}
|
||||||
|
|
||||||
|
var entry = await storage.Entries.GetAsync(media.EntryId, token).ConfigureAwait(false);
|
||||||
|
var account = entry is null ? null : await storage.Accounts.GetAsync(entry.AccountId, token).ConfigureAwait(false);
|
||||||
|
if (entry is null || account is null)
|
||||||
|
{
|
||||||
|
await storage.Conversions.DeletePendingRowAsync(row.Id, CancellationToken.None).ConfigureAwait(false);
|
||||||
|
return Outcome.Skipped;
|
||||||
|
}
|
||||||
|
|
||||||
|
var layout = _env.Layout();
|
||||||
|
var folder = layout.AccountFolder(account);
|
||||||
|
if (!Directory.Exists(folder))
|
||||||
|
{
|
||||||
|
// An unplugged disk of an account folder outside the library: never created again here.
|
||||||
|
await FailAsync(row, LibraryConversionText.AccountFolderMissing).ConfigureAwait(false);
|
||||||
|
return Outcome.Settled;
|
||||||
|
}
|
||||||
|
|
||||||
|
var original = LibraryLayout.FullPath(folder, media.RelativePath);
|
||||||
|
if (!File.Exists(original))
|
||||||
|
{
|
||||||
|
await FailAsync(row, LibraryConversionText.SourceMissing).ConfigureAwait(false);
|
||||||
|
return Outcome.Settled;
|
||||||
|
}
|
||||||
|
|
||||||
|
// A disk already below the threshold stays below it with the file, and the file that paused the conversion last
|
||||||
|
// needs as much again: the pause holds before the original is read (hashed, decoded or remuxed) again at every
|
||||||
|
// wake-up (D17). The exact check with the file's length follows.
|
||||||
|
var source = media.Sha256.ToLowerInvariant();
|
||||||
|
var needed = _lowSpace is { } mark && mark.RowId == row.Id && string.Equals(mark.SourceSha256, source, StringComparison.Ordinal) ? mark.Needed : 0;
|
||||||
|
if (_env.FreeSpace.Measure(folder) is { } before && _env.Thresholds.IsLow(before with { AvailableBytes = before.AvailableBytes - needed }))
|
||||||
|
{
|
||||||
|
return Outcome.LowSpace;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!string.Equals(row.SourceSha256, source, StringComparison.Ordinal))
|
||||||
|
{
|
||||||
|
row = row with { SourceSha256 = source, StateChangedAt = _env.Clock.Now };
|
||||||
|
await storage.Conversions.UpdateAsync(row, CancellationToken.None).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (media.Kind == MediaKind.Video && !string.Equals(await HashAsync(original, token).ConfigureAwait(false), source, StringComparison.Ordinal))
|
||||||
|
{
|
||||||
|
// A remux reads the file in pieces: its bytes are checked first (a photo is checked by the converter).
|
||||||
|
await FailAsync(row, LibraryConversionText.SourceChanged).ConfigureAwait(false);
|
||||||
|
return Outcome.Settled;
|
||||||
|
}
|
||||||
|
|
||||||
|
MediaConversionResult result;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
result = await MediaConverter.PrepareAsync(() => OpenRead(original), media.RelativePath, media.Kind, row.Format, source, _env.Throttle, token)
|
||||||
|
.ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
catch (ContentChangedException)
|
||||||
|
{
|
||||||
|
await FailAsync(row, LibraryConversionText.SourceChanged).ConfigureAwait(false);
|
||||||
|
return Outcome.Settled;
|
||||||
|
}
|
||||||
|
|
||||||
|
using (result)
|
||||||
|
{
|
||||||
|
if (result.Variant == ExportVariant.Whole)
|
||||||
|
{
|
||||||
|
if (result.Notes.Count == 0)
|
||||||
|
{
|
||||||
|
// Already in the format by its bytes (a «.png» that is a JPEG, to JPG): there is no file to add.
|
||||||
|
await storage.Conversions.DeletePendingRowAsync(row.Id, CancellationToken.None).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
// Animated, not decodable, CMYK, too large, not remuxable…: it never converts (terminal).
|
||||||
|
await FailAsync(row, ExportText.JoinNotes(result.Notes)).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
return Outcome.Settled;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (_env.FreeSpace.Measure(folder) is { } space
|
||||||
|
&& _env.Thresholds.IsLow(space with { AvailableBytes = space.AvailableBytes - result.Length }))
|
||||||
|
{
|
||||||
|
_lowSpace = new LowSpaceMark(row.Id, source, result.Length);
|
||||||
|
return Outcome.LowSpace;
|
||||||
|
}
|
||||||
|
|
||||||
|
_lowSpace = null;
|
||||||
|
return await WriteAsync(row, media, entry, account, folder, layout, result, lease, token).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task<Outcome> WriteAsync(MediaConversion row, Media media, Entry entry, Account account, string folder, LibraryLayout layout,
|
||||||
|
MediaConversionResult result, LongWorkGate.BackgroundLease? lease, CancellationToken token)
|
||||||
|
{
|
||||||
|
var storage = _env.Storage;
|
||||||
|
var relative = LibraryLayout.ToStored(media.RelativePath!);
|
||||||
|
var slash = relative.LastIndexOf('/');
|
||||||
|
var directory = slash < 0 ? string.Empty : relative[..slash];
|
||||||
|
var stem = WindowsFileNames.SplitExtension(relative[(slash + 1)..]).Stem;
|
||||||
|
var setTime = await SetFileTimeAsync(token).ConfigureAwait(false);
|
||||||
|
|
||||||
|
FileDigest written = default;
|
||||||
|
string? adopted = null;
|
||||||
|
var preempted = false;
|
||||||
|
IDisposable? commit = null;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var writer = new SafeFileWriter(layout.MaxPathLength);
|
||||||
|
var saved = await writer.SaveAsync(
|
||||||
|
result.Produce,
|
||||||
|
folder,
|
||||||
|
directory,
|
||||||
|
async (digest, t) =>
|
||||||
|
{
|
||||||
|
written = digest;
|
||||||
|
adopted = await FindAdoptableAsync(account, folder, layout, directory, stem, result.Extension, digest, t).ConfigureAwait(false);
|
||||||
|
if (lease is not null && !lease.TryBeginCommit(out commit))
|
||||||
|
{
|
||||||
|
preempted = true;
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return adopted is null ? Join(directory, stem + result.Extension) : null;
|
||||||
|
},
|
||||||
|
new SafeWriteOptions
|
||||||
|
{
|
||||||
|
RequireExistingRoot = true,
|
||||||
|
VerifyFromDisk = true,
|
||||||
|
LastWriteTime = setTime ? entry.PublishedAt : null,
|
||||||
|
},
|
||||||
|
token).ConfigureAwait(false);
|
||||||
|
if (preempted)
|
||||||
|
{
|
||||||
|
return Outcome.Stopped;
|
||||||
|
}
|
||||||
|
|
||||||
|
var path = adopted ?? saved!.RelativePath;
|
||||||
|
if (_env.AfterWrite is { } after)
|
||||||
|
{
|
||||||
|
await after(row, CancellationToken.None).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
MediaConversionCommitOutcome outcome;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
outcome = await storage.Conversions.CommitAsync(
|
||||||
|
new MediaConversionCommit(row.Id, media.Id, row.Format, row.SourceSha256, path, written.Bytes, written.Sha256, _env.Clock.Now,
|
||||||
|
ExportText.JoinNotes(result.Notes)),
|
||||||
|
CancellationToken.None).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
catch when (adopted is null)
|
||||||
|
{
|
||||||
|
DiscardOwn(folder, path, written.Sha256);
|
||||||
|
throw;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (outcome is MediaConversionCommitOutcome.Recorded or MediaConversionCommitOutcome.Upserted)
|
||||||
|
{
|
||||||
|
return Outcome.Converted;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (adopted is null)
|
||||||
|
{
|
||||||
|
// The entry was deleted (or the original replaced) while the file was written: the file just written
|
||||||
|
// belongs to nothing. It is this operation's own file, never one of the library: it goes.
|
||||||
|
DiscardOwn(folder, path, written.Sha256);
|
||||||
|
}
|
||||||
|
|
||||||
|
return Outcome.Settled;
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
commit?.Dispose();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// A file already at the path (or at one of its free names) with the conversion's SHA-256 that no library file and
|
||||||
|
/// no other conversion records: a conversion of an earlier run (or of a lost database) whose record is missing. Null
|
||||||
|
/// when there is none: the file is written with the next free name. Never by size alone (D10).
|
||||||
|
/// </summary>
|
||||||
|
private async Task<string?> FindAdoptableAsync(Account account, string folder, LibraryLayout layout, string directory, string stem, string extension,
|
||||||
|
FileDigest digest, CancellationToken ct)
|
||||||
|
{
|
||||||
|
for (var attempt = 1; attempt <= 50; attempt++)
|
||||||
|
{
|
||||||
|
var name = attempt == 1 ? stem + extension : string.Create(System.Globalization.CultureInfo.InvariantCulture, $"{stem} ({attempt}){extension}");
|
||||||
|
var segments = Join(directory, WindowsFileNames.SanitizeSegment(name)).Split('/', StringSplitOptions.RemoveEmptyEntries);
|
||||||
|
var relative = string.Join('/', WindowsFileNames.FitPath(folder, segments, layout.MaxPathLength));
|
||||||
|
string full;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
full = LibraryLayout.FullPath(folder, relative);
|
||||||
|
}
|
||||||
|
catch (ArgumentException)
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
var info = new FileInfo(full);
|
||||||
|
if (!info.Exists)
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (info.Length == digest.Bytes
|
||||||
|
&& string.Equals(await HashAsync(full, ct).ConfigureAwait(false), digest.Sha256, StringComparison.Ordinal)
|
||||||
|
&& !await IsRecordedAsync(account, relative, digest.Sha256, ct).ConfigureAwait(false))
|
||||||
|
{
|
||||||
|
return relative;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>A library file of the account, or a live conversion of one, records this path (another entry's «x.jpg»).</summary>
|
||||||
|
private async Task<bool> IsRecordedAsync(Account account, string relative, string sha, CancellationToken ct)
|
||||||
|
{
|
||||||
|
var comparison = OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal;
|
||||||
|
var media = await _env.Storage.Media.FindBySha256Async(sha, ct).ConfigureAwait(false);
|
||||||
|
if (media.Any(m => m.Entry.AccountId == account.Id && m.Media.RelativePath is { } p && string.Equals(LibraryLayout.ToStored(p), relative, comparison)))
|
||||||
|
{
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach (var conversion in await _env.Storage.Conversions.FindBySha256Async(sha, ct).ConfigureAwait(false))
|
||||||
|
{
|
||||||
|
if (conversion.State is MediaConversionState.Converted or MediaConversionState.Superseded
|
||||||
|
&& conversion.RelativePath is { } path && string.Equals(path, relative, comparison))
|
||||||
|
{
|
||||||
|
var owner = await _env.Storage.Media.GetAsync(conversion.MediaId, ct).ConfigureAwait(false);
|
||||||
|
var entry = owner is null ? null : await _env.Storage.Entries.GetAsync(owner.EntryId, ct).ConfigureAwait(false);
|
||||||
|
if (entry?.AccountId == account.Id)
|
||||||
|
{
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Deletes the file this conversion just wrote, only if it still has the bytes written (precedent: LibraryIngest).</summary>
|
||||||
|
private void DiscardOwn(string folder, string relative, string sha)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var full = LibraryLayout.FullPath(folder, relative);
|
||||||
|
if (File.Exists(full) && string.Equals(HashFile(full), sha, StringComparison.Ordinal))
|
||||||
|
{
|
||||||
|
File.Delete(full);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException)
|
||||||
|
{
|
||||||
|
_env.Log?.Invoke($"Un file convertito per un elemento eliminato non si è potuto togliere ({ex.GetType().Name}).");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task FailAsync(MediaConversion row, string? codes)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await _env.Storage.Conversions.UpdateAsync(
|
||||||
|
row with { State = MediaConversionState.Failed, LastError = codes, StateChangedAt = _env.Clock.Now, RelativePath = null, Bytes = null, Sha256 = null, ConvertedAt = null },
|
||||||
|
CancellationToken.None).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
catch (Exception ex) when (ex is KeyNotFoundException or DuplicateRecordException)
|
||||||
|
{
|
||||||
|
// The row went or changed meanwhile (a deletion, the setting turned off): nothing to record.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task<bool> SetFileTimeAsync(CancellationToken ct)
|
||||||
|
{
|
||||||
|
var text = await _env.Storage.Settings.GetAsync(SettingKeys.SetFileTimeToPublication, ct).ConfigureAwait(false);
|
||||||
|
return text is null || !bool.TryParse(text, out var parsed) || parsed;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string Join(string directory, string name) => directory.Length == 0 ? name : directory + "/" + name;
|
||||||
|
|
||||||
|
private static FileStream OpenRead(string path) =>
|
||||||
|
new(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete, 128 * 1024, FileOptions.RandomAccess);
|
||||||
|
|
||||||
|
private static async Task<string> HashAsync(string path, CancellationToken ct)
|
||||||
|
{
|
||||||
|
await using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete, 128 * 1024,
|
||||||
|
FileOptions.Asynchronous | FileOptions.SequentialScan);
|
||||||
|
return Convert.ToHexStringLower(await SHA256.HashDataAsync(stream, ct).ConfigureAwait(false));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string HashFile(string path)
|
||||||
|
{
|
||||||
|
using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete, 128 * 1024, FileOptions.SequentialScan);
|
||||||
|
return Convert.ToHexStringLower(SHA256.HashData(stream));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,220 @@
|
|||||||
|
using System.Security.Cryptography;
|
||||||
|
using Febe.Core.Codecs.Containers;
|
||||||
|
using Febe.Core.Codecs.Images;
|
||||||
|
using Febe.Core.Domain;
|
||||||
|
|
||||||
|
namespace Febe.Core.Library.Conversion;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// A library file ready to be written in a format (tappa E3, spec §4.10 «Conversione del formato»): what will be
|
||||||
|
/// written and how. Dispose it once written or given up.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="Variant"><see cref="ExportVariant.Whole"/> (the file byte for byte) or <see cref="ExportVariant.Converted"/>.</param>
|
||||||
|
/// <param name="Format">The effective format: <see cref="ExportFormat.Original"/> for a whole file.</param>
|
||||||
|
/// <param name="Extension">The extension of the file written, with its dot («.jpg»; a whole file keeps its own).</param>
|
||||||
|
/// <param name="Length">The bytes <see cref="Produce"/> writes.</param>
|
||||||
|
/// <param name="Sha256">
|
||||||
|
/// The SHA-256 (lowercase hex) of what <see cref="Produce"/> writes; null for a remux, known once written.
|
||||||
|
/// </param>
|
||||||
|
/// <param name="Notes">Note codes: why the file is copied as it is, or what the conversion could not carry.</param>
|
||||||
|
/// <param name="Produce">Writes the file into the stream given.</param>
|
||||||
|
public sealed record MediaConversionResult(ExportVariant Variant, ExportFormat Format, string Extension,
|
||||||
|
long Length, string? Sha256, IReadOnlyList<string> Notes, Func<Stream, CancellationToken, Task> Produce) : IDisposable
|
||||||
|
{
|
||||||
|
/// <summary>The note prefix of a video that cannot be remuxed; the <see cref="RemuxRefusal"/> follows the colon.</summary>
|
||||||
|
public const string AsIsNotRemuxable = "AsIsNotRemuxable";
|
||||||
|
|
||||||
|
/// <summary>Converted bytes or a remux plan, released on <see cref="Dispose"/>.</summary>
|
||||||
|
internal object? Held { get; set; }
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
public void Dispose() => Held = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Prepares a library file in a target format, independent of where it goes (an export destination, the library):
|
||||||
|
/// photos are converted in memory under the <see cref="ConversionThrottle"/>, videos are remuxed into MP4 while being
|
||||||
|
/// written. The source is never changed.
|
||||||
|
/// </summary>
|
||||||
|
public static class MediaConverter
|
||||||
|
{
|
||||||
|
/// <summary>The raw camera formats, copied as they are (spec §4.10).</summary>
|
||||||
|
private static readonly HashSet<string> RawExtensions = new(StringComparer.OrdinalIgnoreCase)
|
||||||
|
{
|
||||||
|
".dng", ".cr2", ".cr3", ".nef", ".arw", ".raf", ".orf", ".rw2", ".pef", ".srw",
|
||||||
|
};
|
||||||
|
|
||||||
|
/// <summary>A raw camera format by its extension (with its dot), copied as it is.</summary>
|
||||||
|
public static bool IsRawExtension(string extension) => RawExtensions.Contains(extension);
|
||||||
|
|
||||||
|
/// <summary>The raw camera extensions (with their dot, lower case), for rules written in SQL.</summary>
|
||||||
|
public static IReadOnlyCollection<string> RawExtensionList => RawExtensions;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Prepares <paramref name="relativePath"/> (only its name is used) in <paramref name="target"/>.
|
||||||
|
/// <paramref name="openRandomAccess"/> opens the source for reading, seekable; it may be called more than once.
|
||||||
|
/// </summary>
|
||||||
|
/// <exception cref="ContentChangedException">A photo's bytes do not have <paramref name="expectedSourceSha256"/>.</exception>
|
||||||
|
/// <exception cref="ArgumentException">The target does not belong to the kind of file.</exception>
|
||||||
|
public static async Task<MediaConversionResult> PrepareAsync(Func<Stream> openRandomAccess, string relativePath,
|
||||||
|
MediaKind kind, ExportFormat target, string expectedSourceSha256, ConversionThrottle throttle, CancellationToken ct)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(openRandomAccess);
|
||||||
|
ArgumentException.ThrowIfNullOrEmpty(relativePath);
|
||||||
|
ArgumentException.ThrowIfNullOrEmpty(expectedSourceSha256);
|
||||||
|
ArgumentNullException.ThrowIfNull(throttle);
|
||||||
|
var valid = kind == MediaKind.Photo ? ExportFormats.IsPhotoFormat(target) : ExportFormats.IsVideoFormat(target);
|
||||||
|
if (!valid)
|
||||||
|
{
|
||||||
|
throw new ArgumentException("Il formato non è adatto a questo tipo di file.", nameof(target));
|
||||||
|
}
|
||||||
|
|
||||||
|
return kind == MediaKind.Photo
|
||||||
|
? await PreparePhotoAsync(openRandomAccess, relativePath, target, expectedSourceSha256.ToLowerInvariant(), throttle, ct).ConfigureAwait(false)
|
||||||
|
: await PrepareVideoAsync(openRandomAccess, relativePath, target, expectedSourceSha256.ToLowerInvariant(), throttle, ct).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The image format written for an export format; null for Original and MP4.</summary>
|
||||||
|
public static ImageFormat? ImageFormatOf(ExportFormat format) => format switch
|
||||||
|
{
|
||||||
|
ExportFormat.Jpg => ImageFormat.Jpeg,
|
||||||
|
ExportFormat.Png => ImageFormat.Png,
|
||||||
|
ExportFormat.WebpLossless => ImageFormat.WebP,
|
||||||
|
_ => null,
|
||||||
|
};
|
||||||
|
|
||||||
|
/// <summary>The extension of a converted file, with its dot.</summary>
|
||||||
|
public static string ExtensionOf(ExportFormat format) => format switch
|
||||||
|
{
|
||||||
|
ExportFormat.Jpg => ".jpg",
|
||||||
|
ExportFormat.Png => ".png",
|
||||||
|
ExportFormat.WebpLossless => ".webp",
|
||||||
|
ExportFormat.Mp4 => ".mp4",
|
||||||
|
_ => throw new ArgumentOutOfRangeException(nameof(format)),
|
||||||
|
};
|
||||||
|
|
||||||
|
private static async Task<MediaConversionResult> PreparePhotoAsync(Func<Stream> open, string relativePath,
|
||||||
|
ExportFormat target, string expected, ConversionThrottle throttle, CancellationToken ct)
|
||||||
|
{
|
||||||
|
var extension = Path.GetExtension(relativePath);
|
||||||
|
long length;
|
||||||
|
byte[]? bytes = null;
|
||||||
|
await using (var source = open())
|
||||||
|
{
|
||||||
|
length = source.Length;
|
||||||
|
if (target != ExportFormat.Original && length <= ImageConverter.MaxSourceBytes)
|
||||||
|
{
|
||||||
|
bytes = new byte[length];
|
||||||
|
await source.ReadExactlyAsync(bytes, ct).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (bytes is null)
|
||||||
|
{
|
||||||
|
// Original, or too large to hold: the file byte for byte, checked against its SHA while written.
|
||||||
|
return Whole(open, extension, length, expected, target == ExportFormat.Original ? [] : [ImageConversionLosses.AsIsTooLarge]);
|
||||||
|
}
|
||||||
|
|
||||||
|
var sha = Convert.ToHexStringLower(SHA256.HashData(bytes));
|
||||||
|
if (!string.Equals(sha, expected, StringComparison.Ordinal))
|
||||||
|
{
|
||||||
|
throw new ContentChangedException("Il file della libreria è cambiato durante la copia.");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (RawExtensions.Contains(extension))
|
||||||
|
{
|
||||||
|
return Whole(bytes, extension, sha, [ImageConversionLosses.AsIsRaw]);
|
||||||
|
}
|
||||||
|
|
||||||
|
var format = ImageFormatOf(target)!.Value;
|
||||||
|
var check = ImageConverter.Check(bytes, format);
|
||||||
|
switch (check.Action)
|
||||||
|
{
|
||||||
|
case ImageConversionAction.CopyAsIs:
|
||||||
|
return Whole(bytes, extension, sha, []);
|
||||||
|
case ImageConversionAction.CopyOriginal:
|
||||||
|
return Whole(bytes, extension, sha, check.NoteCode is { } note ? [note] : []);
|
||||||
|
}
|
||||||
|
|
||||||
|
var (converted, refusal) = await throttle.RunAsync((ImageConversionResult? Result, string? Refusal) (CancellationToken token) =>
|
||||||
|
{
|
||||||
|
token.ThrowIfCancellationRequested();
|
||||||
|
try
|
||||||
|
{
|
||||||
|
return (ImageConverter.Convert(bytes, format), null);
|
||||||
|
}
|
||||||
|
catch (ImageLimitException)
|
||||||
|
{
|
||||||
|
// Readable, but over what the decoder or the target allows: «troppo grande», never «non si legge».
|
||||||
|
return (null, ImageConversionLosses.AsIsTooLarge);
|
||||||
|
}
|
||||||
|
catch (ImageDecodeException)
|
||||||
|
{
|
||||||
|
return (null, ImageConversionLosses.AsIsNotDecodable);
|
||||||
|
}
|
||||||
|
}, ct).ConfigureAwait(false);
|
||||||
|
if (converted is null)
|
||||||
|
{
|
||||||
|
return Whole(bytes, extension, sha, [refusal!]);
|
||||||
|
}
|
||||||
|
|
||||||
|
var data = converted.Data;
|
||||||
|
return new MediaConversionResult(ExportVariant.Converted, target, ExtensionOf(target), data.Length,
|
||||||
|
Convert.ToHexStringLower(SHA256.HashData(data)), converted.Losses, Writer(data))
|
||||||
|
{
|
||||||
|
Held = data,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private static async Task<MediaConversionResult> PrepareVideoAsync(Func<Stream> open, string relativePath,
|
||||||
|
ExportFormat target, string expected, ConversionThrottle throttle, CancellationToken ct)
|
||||||
|
{
|
||||||
|
var extension = Path.GetExtension(relativePath);
|
||||||
|
var fileName = Path.GetFileName(relativePath);
|
||||||
|
var (length, refusal, plan) = await throttle.RunAsync(token =>
|
||||||
|
{
|
||||||
|
using var source = open();
|
||||||
|
var size = source.Length;
|
||||||
|
if (target == ExportFormat.Original)
|
||||||
|
{
|
||||||
|
return (size, RemuxRefusal.AlreadyMp4, (RemuxPlan?)null);
|
||||||
|
}
|
||||||
|
|
||||||
|
var outcome = Mp4Remuxer.Check(source, fileName, out var made, token);
|
||||||
|
return (size, outcome, made);
|
||||||
|
}, ct).ConfigureAwait(false);
|
||||||
|
|
||||||
|
if (refusal == RemuxRefusal.None && plan is not null)
|
||||||
|
{
|
||||||
|
return new MediaConversionResult(ExportVariant.Converted, ExportFormat.Mp4, ".mp4", plan.OutputLength, null,
|
||||||
|
plan.Losses, (output, token) => Task.Run(
|
||||||
|
() =>
|
||||||
|
{
|
||||||
|
using var source = open();
|
||||||
|
Mp4Remuxer.Write(plan, source, output, token);
|
||||||
|
},
|
||||||
|
token))
|
||||||
|
{
|
||||||
|
Held = plan,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
string[] notes = refusal == RemuxRefusal.AlreadyMp4 ? [] : [$"{MediaConversionResult.AsIsNotRemuxable}:{refusal}"];
|
||||||
|
return Whole(open, extension, length, expected, notes);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>A whole file streamed from the source (a video, or a photo not read into memory).</summary>
|
||||||
|
private static MediaConversionResult Whole(Func<Stream> open, string extension, long length, string sha, IReadOnlyList<string> notes) =>
|
||||||
|
new(ExportVariant.Whole, ExportFormat.Original, extension, length, sha, notes, async (output, token) =>
|
||||||
|
{
|
||||||
|
await using var source = open();
|
||||||
|
await source.CopyToAsync(output, token).ConfigureAwait(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
/// <summary>A whole photo from the bytes already read and checked.</summary>
|
||||||
|
private static MediaConversionResult Whole(byte[] bytes, string extension, string sha, IReadOnlyList<string> notes) =>
|
||||||
|
new(ExportVariant.Whole, ExportFormat.Original, extension, bytes.Length, sha, notes, Writer(bytes)) { Held = bytes };
|
||||||
|
|
||||||
|
private static Func<Stream, CancellationToken, Task> Writer(byte[] data) =>
|
||||||
|
(output, token) => output.WriteAsync(data, token).AsTask();
|
||||||
|
}
|
||||||
@@ -282,7 +282,12 @@ public sealed class DownloadDuplicateReview(
|
|||||||
}
|
}
|
||||||
|
|
||||||
var folder = layout.AccountFolder(account);
|
var folder = layout.AccountFolder(account);
|
||||||
await storage.Media.UpdateAsync(media with { State = MediaState.Deleted }, ct).ConfigureAwait(false);
|
|
||||||
|
// Its converted files of the library (tappa E3) go with it, in the transaction that deletes the file: the queue
|
||||||
|
// and the failures are dropped, the rows with a file become «Tolto» and their files are deleted below (one the
|
||||||
|
// worker records meanwhile is among them). No supersession for the loser.
|
||||||
|
var removed = await storage.Conversions.ForgetDeletedMediaAsync(media.Id, clock.Now, ct).ConfigureAwait(false);
|
||||||
|
var withFiles = removed.Where(LibraryDeletion.HasFile).ToList();
|
||||||
await storage.Entries.RecomputeStateAsync(stored.Entry.Id, ct).ConfigureAwait(false);
|
await storage.Entries.RecomputeStateAsync(stored.Entry.Id, ct).ConfigureAwait(false);
|
||||||
hashIndex?.Remove(media.Id);
|
hashIndex?.Remove(media.Id);
|
||||||
var remaining = stored.Media.Select(m => m.Id == media.Id ? m with { State = MediaState.Deleted } : m).ToList();
|
var remaining = stored.Media.Select(m => m.Id == media.Id ? m with { State = MediaState.Deleted } : m).ToList();
|
||||||
@@ -312,6 +317,14 @@ public sealed class DownloadDuplicateReview(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var failedConverted = new List<string>();
|
||||||
|
await LibraryDeletion.DeleteConvertedFilesAsync(storage, account.Id, folder, withFiles, [], [], failedConverted, ct).ConfigureAwait(false);
|
||||||
|
if (failedConverted.Count > 0)
|
||||||
|
{
|
||||||
|
var more = $"@{side.Username}, file convertiti: {string.Join("; ", failedConverted)}.";
|
||||||
|
problem = problem is null ? more : problem + " " + more;
|
||||||
|
}
|
||||||
|
|
||||||
if (thumbnails is not null && media.Sha256 is { } sha)
|
if (thumbnails is not null && media.Sha256 is { } sha)
|
||||||
{
|
{
|
||||||
var users = await storage.Media.FindBySha256Async(sha, ct).ConfigureAwait(false);
|
var users = await storage.Media.FindBySha256Async(sha, ct).ConfigureAwait(false);
|
||||||
|
|||||||
@@ -31,6 +31,9 @@ public sealed record DeletionResult(
|
|||||||
IReadOnlyList<string> FailedFiles)
|
IReadOnlyList<string> FailedFiles)
|
||||||
{
|
{
|
||||||
public bool Complete => Found && FailedFiles.Count == 0;
|
public bool Complete => Found && FailedFiles.Count == 0;
|
||||||
|
|
||||||
|
/// <summary>Converted files of the library (tappa E3) deleted with the originals; they are in <see cref="DeletedFiles"/> too.</summary>
|
||||||
|
public int ConvertedFiles { get; init; }
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -69,14 +72,12 @@ public sealed class LibraryDeletion(
|
|||||||
await journal.AppendDeletedAsync(folder, account, stored.Entry, present.Select(m => m.RelativePath!).ToList(), mode == DeletionMode.Remember, none)
|
await journal.AppendDeletedAsync(folder, account, stored.Entry, present.Select(m => m.RelativePath!).ToList(), mode == DeletionMode.Remember, none)
|
||||||
.ConfigureAwait(false);
|
.ConfigureAwait(false);
|
||||||
|
|
||||||
if (mode == DeletionMode.Remember)
|
// The converted files of the library (tappa E3) go with their originals; only the explicit choice deletes them.
|
||||||
{
|
// Their rows are chosen in the transaction that deletes the entry: one the worker records meanwhile is among them.
|
||||||
await storage.Entries.MarkDeletedAsync(entryId, clock.Now, none).ConfigureAwait(false);
|
var removed = mode == DeletionMode.Remember
|
||||||
}
|
? await storage.Entries.MarkDeletedWithConversionsAsync(entryId, clock.Now, none).ConfigureAwait(false)
|
||||||
else
|
: await storage.Entries.RemoveWithConversionsAsync(entryId, none).ConfigureAwait(false);
|
||||||
{
|
IReadOnlyList<MediaConversion> withFiles = removed.Where(HasFile).ToList();
|
||||||
await storage.Entries.RemoveAsync(entryId, none).ConfigureAwait(false);
|
|
||||||
}
|
|
||||||
|
|
||||||
foreach (var media in stored.Media)
|
foreach (var media in stored.Media)
|
||||||
{
|
{
|
||||||
@@ -108,6 +109,8 @@ public sealed class LibraryDeletion(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var converted = await DeleteConvertedFilesAsync(storage, account.Id, folder, withFiles, deleted, missing, failed, none).ConfigureAwait(false);
|
||||||
|
|
||||||
if (thumbnails is not null)
|
if (thumbnails is not null)
|
||||||
{
|
{
|
||||||
foreach (var sha in stored.Media.Select(m => m.Sha256).OfType<string>().Distinct(StringComparer.Ordinal))
|
foreach (var sha in stored.Media.Select(m => m.Sha256).OfType<string>().Distinct(StringComparer.Ordinal))
|
||||||
@@ -127,7 +130,89 @@ public sealed class LibraryDeletion(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return new DeletionResult(entryId, true, deleted, missing, failed);
|
return new DeletionResult(entryId, true, deleted, missing, failed) { ConvertedFiles = converted };
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>A conversion whose file is (or was last known to be) on disk.</summary>
|
||||||
|
internal static bool HasFile(MediaConversion c) =>
|
||||||
|
c.State is MediaConversionState.Converted or MediaConversionState.Superseded && c.RelativePath is not null && c.Sha256 is not null;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Deletes the converted files of conversions just removed or marked «Tolto», each only if no library file and no
|
||||||
|
/// live conversion still records its path and it still has the bytes recorded: a file replaced by Alberto stays and
|
||||||
|
/// is listed among the failures with its reason. Returns how many were deleted.
|
||||||
|
/// </summary>
|
||||||
|
internal static async Task<int> DeleteConvertedFilesAsync(IFebeStorage storage, long accountId, string folder, IReadOnlyList<MediaConversion> conversions,
|
||||||
|
List<string> deleted, List<string> missing, List<string> failed, CancellationToken ct)
|
||||||
|
{
|
||||||
|
var count = 0;
|
||||||
|
foreach (var conversion in conversions)
|
||||||
|
{
|
||||||
|
var relative = conversion.RelativePath!;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var path = LibraryLayout.FullPath(folder, relative);
|
||||||
|
if (!File.Exists(path))
|
||||||
|
{
|
||||||
|
missing.Add(relative);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (await IsStillRecordedAsync(storage, accountId, conversion, ct).ConfigureAwait(false))
|
||||||
|
{
|
||||||
|
continue; // another file of the library has that name now: it is not this conversion's to delete
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!string.Equals(HashFile(path), conversion.Sha256, StringComparison.OrdinalIgnoreCase))
|
||||||
|
{
|
||||||
|
failed.Add($"{relative}: il file convertito è cambiato dopo la conversione, quindi resta dov'è.");
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
File.Delete(path);
|
||||||
|
deleted.Add(relative);
|
||||||
|
count++;
|
||||||
|
}
|
||||||
|
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException)
|
||||||
|
{
|
||||||
|
failed.Add($"{relative}: {ex.Message}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return count;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static async Task<bool> IsStillRecordedAsync(IFebeStorage storage, long accountId, MediaConversion conversion, CancellationToken ct)
|
||||||
|
{
|
||||||
|
var comparison = OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal;
|
||||||
|
var sha = conversion.Sha256!;
|
||||||
|
foreach (var m in await storage.Media.FindBySha256Async(sha, ct).ConfigureAwait(false))
|
||||||
|
{
|
||||||
|
if (m.Entry.AccountId == accountId && EntryStateRules.IsPresent(m.Media.State) && m.Media.RelativePath is { } p
|
||||||
|
&& string.Equals(LibraryLayout.ToStored(p), conversion.RelativePath, comparison))
|
||||||
|
{
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach (var other in await storage.Conversions.FindBySha256Async(sha, ct).ConfigureAwait(false))
|
||||||
|
{
|
||||||
|
if (other.Id != conversion.Id && other.State is MediaConversionState.Converted or MediaConversionState.Superseded
|
||||||
|
&& string.Equals(other.RelativePath, conversion.RelativePath, comparison)
|
||||||
|
&& await storage.Media.GetAsync(other.MediaId, ct).ConfigureAwait(false) is { } owner
|
||||||
|
&& (await storage.Entries.GetAsync(owner.EntryId, ct).ConfigureAwait(false))?.AccountId == accountId)
|
||||||
|
{
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string HashFile(string path)
|
||||||
|
{
|
||||||
|
using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, 128 * 1024, FileOptions.SequentialScan);
|
||||||
|
return Convert.ToHexStringLower(System.Security.Cryptography.SHA256.HashData(stream));
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>Multiple selection: deletes each entry in turn.</summary>
|
/// <summary>Multiple selection: deletes each entry in turn.</summary>
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ using System.Globalization;
|
|||||||
using Febe.Core.Abstractions;
|
using Febe.Core.Abstractions;
|
||||||
using Febe.Core.Domain;
|
using Febe.Core.Domain;
|
||||||
using Febe.Core.Export;
|
using Febe.Core.Export;
|
||||||
|
using Febe.Core.Library.Conversion;
|
||||||
using Febe.Core.Storage;
|
using Febe.Core.Storage;
|
||||||
|
|
||||||
namespace Febe.Core.Library;
|
namespace Febe.Core.Library;
|
||||||
@@ -371,6 +372,10 @@ public sealed class LibraryIngest(
|
|||||||
stored.Media,
|
stored.Media,
|
||||||
highlights.Select(h => new JournalHighlight(h.InstagramId, h.Title, h.Position)).ToList(),
|
highlights.Select(h => new JournalHighlight(h.InstagramId, h.Title, h.Position)).ToList(),
|
||||||
ct).ConfigureAwait(false);
|
ct).ConfigureAwait(false);
|
||||||
|
|
||||||
|
// The conversion for the library (tappa E3, Q29): a new file enters its queue after its journal line; the
|
||||||
|
// files the entry already had before the format was set wait for «Anche i N» (EnqueueEntryAsync).
|
||||||
|
await LibraryConversionQueue.EnqueueEntryAsync(storage, stored.Media, clock.Now, CancellationToken.None).ConfigureAwait(false);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
|
|||||||
@@ -1,7 +1,9 @@
|
|||||||
|
using System.Globalization;
|
||||||
using System.Security.Cryptography;
|
using System.Security.Cryptography;
|
||||||
using Febe.Core.Abstractions;
|
using Febe.Core.Abstractions;
|
||||||
using Febe.Core.Domain;
|
using Febe.Core.Domain;
|
||||||
using Febe.Core.Export;
|
using Febe.Core.Export;
|
||||||
|
using Febe.Core.Library.Conversion;
|
||||||
using Febe.Core.Storage;
|
using Febe.Core.Storage;
|
||||||
|
|
||||||
namespace Febe.Core.Library;
|
namespace Febe.Core.Library;
|
||||||
@@ -61,6 +63,15 @@ public sealed record RebuildReport
|
|||||||
/// <summary>Files in account folders that no journal line mentions: left untouched, not added.</summary>
|
/// <summary>Files in account folders that no journal line mentions: left untouched, not added.</summary>
|
||||||
public int UntrackedFiles { get; init; }
|
public int UntrackedFiles { get; init; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Converted files of the library without a record (tappa E3): next to a file of the journal, with its name and in a
|
||||||
|
/// target format. Left untouched; queued again when the conversion for their kind is on with that format.
|
||||||
|
/// </summary>
|
||||||
|
public int ConversionsFound { get; init; }
|
||||||
|
|
||||||
|
/// <summary>Converted files of the library still on disk for entries deleted «ricordando la scelta»: left untouched.</summary>
|
||||||
|
public int ConversionsOfDeletedEntries { get; init; }
|
||||||
|
|
||||||
public int InvalidLines { get; init; }
|
public int InvalidLines { get; init; }
|
||||||
|
|
||||||
/// <summary>A few examples of what needs attention (Italian), for the report screen.</summary>
|
/// <summary>A few examples of what needs attention (Italian), for the report screen.</summary>
|
||||||
@@ -152,7 +163,7 @@ public sealed class LibraryRebuilder(
|
|||||||
var allItems = Fold(journal.Lines, report);
|
var allItems = Fold(journal.Lines, report);
|
||||||
|
|
||||||
// Entries already in the database are left as they are (deletions excepted): no hashing, no change.
|
// Entries already in the database are left as they are (deletions excepted): no hashing, no change.
|
||||||
var items = await SplitPresentAsync(account, allItems, report, ct).ConfigureAwait(false);
|
var items = await SplitPresentAsync(account, folder, allItems, report, ct).ConfigureAwait(false);
|
||||||
|
|
||||||
// Verify files in parallel: hashing dominates the time.
|
// Verify files in parallel: hashing dominates the time.
|
||||||
var live = items.Where(i => !i.Deleted).ToList();
|
var live = items.Where(i => !i.Deleted).ToList();
|
||||||
@@ -198,11 +209,11 @@ public sealed class LibraryRebuilder(
|
|||||||
batch.Add((item, new NewEntry(entry, media)));
|
batch.Add((item, new NewEntry(entry, media)));
|
||||||
if (batch.Count >= BatchSize)
|
if (batch.Count >= BatchSize)
|
||||||
{
|
{
|
||||||
await FlushAsync(account, batch, report, ct).ConfigureAwait(false);
|
await FlushAsync(account, folder, batch, report, ct).ConfigureAwait(false);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
await FlushAsync(account, batch, report, ct).ConfigureAwait(false);
|
await FlushAsync(account, folder, batch, report, ct).ConfigureAwait(false);
|
||||||
|
|
||||||
// Files whose bytes on disk differ from the journal: their copies in external folders are «Superato» (spec §4.10).
|
// Files whose bytes on disk differ from the journal: their copies in external folders are «Superato» (spec §4.10).
|
||||||
foreach (var (old, now) in report.Changed)
|
foreach (var (old, now) in report.Changed)
|
||||||
@@ -211,14 +222,14 @@ public sealed class LibraryRebuilder(
|
|||||||
}
|
}
|
||||||
|
|
||||||
report.Changed.Clear();
|
report.Changed.Clear();
|
||||||
CountUntracked(folder, allItems, report);
|
await CountUntrackedAsync(account, folder, allItems, report, ct).ConfigureAwait(false);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Returns the items that are not in the database yet. Items already present are counted; a remembered deletion
|
/// Returns the items that are not in the database yet. Items already present are counted; a remembered deletion
|
||||||
/// is applied to them if the database still shows them.
|
/// is applied to them if the database still shows them.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
private async Task<List<Item>> SplitPresentAsync(Account account, List<Item> items, Accumulator report, CancellationToken ct)
|
private async Task<List<Item>> SplitPresentAsync(Account account, string folder, List<Item> items, Accumulator report, CancellationToken ct)
|
||||||
{
|
{
|
||||||
var paths = await storage.Media.MapPathsAsync(account.Id, ct).ConfigureAwait(false);
|
var paths = await storage.Media.MapPathsAsync(account.Id, ct).ConfigureAwait(false);
|
||||||
var known = new HashSet<(EntryKind, string)>();
|
var known = new HashSet<(EntryKind, string)>();
|
||||||
@@ -253,7 +264,7 @@ public sealed class LibraryRebuilder(
|
|||||||
: null;
|
: null;
|
||||||
if (existing is not null && existing.State != EntryState.Deleted)
|
if (existing is not null && existing.State != EntryState.Deleted)
|
||||||
{
|
{
|
||||||
await storage.Entries.MarkDeletedAsync(existing.Id, item.DeletedAt ?? clock.Now, ct).ConfigureAwait(false);
|
await MarkDeletedAsync(folder, existing.Id, item.DeletedAt ?? clock.Now, report, ct).ConfigureAwait(false);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -582,7 +593,7 @@ public sealed class LibraryRebuilder(
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
private async Task FlushAsync(Account account, List<(Item Item, NewEntry Entry)> batch, Accumulator report, CancellationToken ct)
|
private async Task FlushAsync(Account account, string folder, List<(Item Item, NewEntry Entry)> batch, Accumulator report, CancellationToken ct)
|
||||||
{
|
{
|
||||||
if (batch.Count == 0)
|
if (batch.Count == 0)
|
||||||
{
|
{
|
||||||
@@ -604,7 +615,7 @@ public sealed class LibraryRebuilder(
|
|||||||
report.EntriesAlreadyPresent++;
|
report.EntriesAlreadyPresent++;
|
||||||
if (item.Deleted && stored.Entry.State != EntryState.Deleted)
|
if (item.Deleted && stored.Entry.State != EntryState.Deleted)
|
||||||
{
|
{
|
||||||
await storage.Entries.MarkDeletedAsync(stored.Entry.Id, item.DeletedAt ?? clock.Now, ct).ConfigureAwait(false);
|
await MarkDeletedAsync(folder, stored.Entry.Id, item.DeletedAt ?? clock.Now, report, ct).ConfigureAwait(false);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -661,11 +672,98 @@ public sealed class LibraryRebuilder(
|
|||||||
State = MediaState.Deleted,
|
State = MediaState.Deleted,
|
||||||
};
|
};
|
||||||
|
|
||||||
private static void CountUntracked(string folder, List<Item> items, Accumulator report)
|
/// <summary>
|
||||||
|
/// A remembered deletion found by the rebuild (tappa E3, WP2.4): the entry's conversions whose converted file is
|
||||||
|
/// missing become «Tolto»; those whose file is still on disk stay as they are (the rebuild never deletes a file) and
|
||||||
|
/// are counted.
|
||||||
|
/// </summary>
|
||||||
|
private async Task MarkDeletedAsync(string folder, long entryId, DateTimeOffset at, Accumulator report, CancellationToken ct)
|
||||||
{
|
{
|
||||||
|
var missing = new List<long>();
|
||||||
|
foreach (var conversion in await storage.Conversions.ListByEntryAsync(entryId, ct).ConfigureAwait(false))
|
||||||
|
{
|
||||||
|
if (conversion.State is not (MediaConversionState.Converted or MediaConversionState.Superseded) || conversion.RelativePath is not { } relative)
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (ExistsIn(folder, relative))
|
||||||
|
{
|
||||||
|
report.ConversionsOfDeletedEntries++;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
missing.Add(conversion.Id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
await storage.Entries.MarkDeletedAsync(entryId, at, missing, ct).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool ExistsIn(string folder, string relative)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
return File.Exists(LibraryLayout.FullPath(folder, relative));
|
||||||
|
}
|
||||||
|
catch (ArgumentException)
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The format a converted file of the library has, by its extension; null for any other file.</summary>
|
||||||
|
private static ExportFormat? ConvertedFormatOf(string extension) => extension.ToLowerInvariant() switch
|
||||||
|
{
|
||||||
|
".jpg" or ".jpeg" => ExportFormat.Jpg,
|
||||||
|
".png" => ExportFormat.Png,
|
||||||
|
".webp" => ExportFormat.WebpLossless,
|
||||||
|
".mp4" => ExportFormat.Mp4,
|
||||||
|
_ => null,
|
||||||
|
};
|
||||||
|
|
||||||
|
/// <summary>«nome (2)» → «nome»: the free names the conversion for the library gives.</summary>
|
||||||
|
private static string WithoutNumber(string stem)
|
||||||
|
{
|
||||||
|
var open = stem.LastIndexOf(" (", StringComparison.Ordinal);
|
||||||
|
if (open > 0 && stem.EndsWith(')')
|
||||||
|
&& int.TryParse(stem.AsSpan(open + 2, stem.Length - open - 3), NumberStyles.None, CultureInfo.InvariantCulture, out _))
|
||||||
|
{
|
||||||
|
return stem[..open];
|
||||||
|
}
|
||||||
|
|
||||||
|
return stem;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Counts the files of the account folder that no journal line mentions (left untouched). The converted files of the
|
||||||
|
/// library (tappa E3) are not unknown: those with a row are skipped; one without a row, next to a file of the
|
||||||
|
/// journal with its stem and in a target format, is counted apart and, when the conversion for that kind is on with
|
||||||
|
/// that format, its file is queued again (a Pending row: the worker adopts the file by its SHA-256). Nothing is
|
||||||
|
/// converted during the rebuild.
|
||||||
|
/// </summary>
|
||||||
|
private async Task CountUntrackedAsync(Account account, string folder, List<Item> items, Accumulator report, CancellationToken ct)
|
||||||
|
{
|
||||||
|
var comparer = OperatingSystem.IsWindows() ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal;
|
||||||
var known = new HashSet<string>(
|
var known = new HashSet<string>(
|
||||||
items.SelectMany(i => i.Files.Values.Concat(i.Removed.Values)).Select(f => LibraryLayout.ToStored(f.Path)),
|
items.SelectMany(i => i.Files.Values.Concat(i.Removed.Values)).Select(f => LibraryLayout.ToStored(f.Path)),
|
||||||
OperatingSystem.IsWindows() ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal);
|
comparer);
|
||||||
|
foreach (var path in await storage.Conversions.ListPathsByAccountAsync(account.Id, ct).ConfigureAwait(false))
|
||||||
|
{
|
||||||
|
known.Add(path);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Files of the journal by folder and stem, for the converted files next to them.
|
||||||
|
var byStem = new Dictionary<string, JournalFile>(comparer);
|
||||||
|
foreach (var file in items.Where(i => !i.Deleted).SelectMany(i => i.Files.Values))
|
||||||
|
{
|
||||||
|
var stored = LibraryLayout.ToStored(file.Path);
|
||||||
|
var slash = stored.LastIndexOf('/');
|
||||||
|
byStem.TryAdd((slash < 0 ? string.Empty : stored[..(slash + 1)]) + WindowsFileNames.SplitExtension(stored[(slash + 1)..]).Stem, file);
|
||||||
|
}
|
||||||
|
|
||||||
|
ExportSettings? settings = null;
|
||||||
|
IReadOnlyDictionary<string, long>? paths = null;
|
||||||
foreach (var file in Directory.EnumerateFiles(folder, "*", new EnumerationOptions { RecurseSubdirectories = true, IgnoreInaccessible = true }))
|
foreach (var file in Directory.EnumerateFiles(folder, "*", new EnumerationOptions { RecurseSubdirectories = true, IgnoreInaccessible = true }))
|
||||||
{
|
{
|
||||||
var name = Path.GetFileName(file);
|
var name = Path.GetFileName(file);
|
||||||
@@ -675,11 +773,56 @@ public sealed class LibraryRebuilder(
|
|||||||
}
|
}
|
||||||
|
|
||||||
var relative = LibraryLayout.ToStored(Path.GetRelativePath(folder, file));
|
var relative = LibraryLayout.ToStored(Path.GetRelativePath(folder, file));
|
||||||
if (!known.Contains(relative))
|
if (known.Contains(relative))
|
||||||
{
|
{
|
||||||
report.UntrackedFiles++;
|
continue;
|
||||||
report.Note($"File non registrato in _febe.jsonl (lasciato dov'è): {Path.GetFileName(folder)}/{relative}");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var slash = relative.LastIndexOf('/');
|
||||||
|
var (stem, extension) = WindowsFileNames.SplitExtension(relative[(slash + 1)..]);
|
||||||
|
var key = (slash < 0 ? string.Empty : relative[..(slash + 1)]) + WithoutNumber(stem);
|
||||||
|
if (ConvertedFormatOf(extension) is { } format && byStem.TryGetValue(key, out var original))
|
||||||
|
{
|
||||||
|
report.ConversionsFound++;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
settings ??= await ExportSettings.LoadAsync(storage.Settings, ct).ConfigureAwait(false);
|
||||||
|
paths ??= await storage.Media.MapPathsAsync(account.Id, ct).ConfigureAwait(false);
|
||||||
|
await QueueFoundAsync(original, format, settings, paths, ct).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
catch (Exception ex) when (ex is DuplicateRecordException or KeyNotFoundException or ArgumentException)
|
||||||
|
{
|
||||||
|
// Counted, never thrown: the worker or a later rebuild finds it again.
|
||||||
|
}
|
||||||
|
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
report.UntrackedFiles++;
|
||||||
|
report.Note($"File non registrato in _febe.jsonl (lasciato dov'è): {Path.GetFileName(folder)}/{relative}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Queues the journal file <paramref name="original"/> in <paramref name="format"/> when its conversion is on with that format.</summary>
|
||||||
|
private async Task QueueFoundAsync(JournalFile original, ExportFormat format, ExportSettings settings, IReadOnlyDictionary<string, long> paths, CancellationToken ct)
|
||||||
|
{
|
||||||
|
var stored = LibraryLayout.ToStored(original.Path);
|
||||||
|
if (!paths.TryGetValue(stored, out var entryId))
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
var media = (await storage.Media.ListByEntryAsync(entryId, ct).ConfigureAwait(false))
|
||||||
|
.FirstOrDefault(m => m.RelativePath is { } p && string.Equals(LibraryLayout.ToStored(p), stored, StringComparison.Ordinal));
|
||||||
|
if (media is null || LibraryConversionRules.FormatFor(media.Kind, settings) != format)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
var requests = LibraryConversionRules.RequestsFor([media], settings);
|
||||||
|
if (requests.Count > 0)
|
||||||
|
{
|
||||||
|
await storage.Conversions.EnqueueAsync(requests, clock.Now, ct).ConfigureAwait(false);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -746,6 +889,10 @@ public sealed class LibraryRebuilder(
|
|||||||
|
|
||||||
public int UntrackedFiles { get; set; }
|
public int UntrackedFiles { get; set; }
|
||||||
|
|
||||||
|
public int ConversionsFound { get; set; }
|
||||||
|
|
||||||
|
public int ConversionsOfDeletedEntries { get; set; }
|
||||||
|
|
||||||
public int InvalidLines { get; set; }
|
public int InvalidLines { get; set; }
|
||||||
|
|
||||||
/// <summary>(journal SHA-256, SHA-256 on disk) of the folder being rebuilt, for the copies to mark «Superato».</summary>
|
/// <summary>(journal SHA-256, SHA-256 on disk) of the folder being rebuilt, for the copies to mark «Superato».</summary>
|
||||||
@@ -773,6 +920,8 @@ public sealed class LibraryRebuilder(
|
|||||||
FilesUnreadable = FilesUnreadable,
|
FilesUnreadable = FilesUnreadable,
|
||||||
HashMismatches = HashMismatches,
|
HashMismatches = HashMismatches,
|
||||||
UntrackedFiles = UntrackedFiles,
|
UntrackedFiles = UntrackedFiles,
|
||||||
|
ConversionsFound = ConversionsFound,
|
||||||
|
ConversionsOfDeletedEntries = ConversionsOfDeletedEntries,
|
||||||
InvalidLines = InvalidLines,
|
InvalidLines = InvalidLines,
|
||||||
Notes = _notes,
|
Notes = _notes,
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -42,6 +42,12 @@ public sealed record SafeWriteOptions
|
|||||||
/// is removed and an <see cref="IOException"/> says so.
|
/// is removed and an <see cref="IOException"/> says so.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public bool VerifyFromDisk { get; init; }
|
public bool VerifyFromDisk { get; init; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The end of the stem of the file name that a shortening or a free name never cuts (the frame suffix of tappa
|
||||||
|
/// E3, «_t0m12s340»): a free name is «nome_t0m12s340 (2).png», as <c>ExportPaths.NumberedName</c> gives it.
|
||||||
|
/// </summary>
|
||||||
|
public string? KeepSuffix { get; init; }
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>The content exceeded <see cref="SafeWriteOptions.MaxBytes"/>; nothing was kept.</summary>
|
/// <summary>The content exceeded <see cref="SafeWriteOptions.MaxBytes"/>; nothing was kept.</summary>
|
||||||
@@ -164,6 +170,38 @@ public sealed class SafeFileWriter(int maxPathLength = WindowsFileNames.MaxPathL
|
|||||||
CancellationToken ct = default)
|
CancellationToken ct = default)
|
||||||
{
|
{
|
||||||
ArgumentNullException.ThrowIfNull(source);
|
ArgumentNullException.ThrowIfNull(source);
|
||||||
|
return await SaveCoreAsync((path, o, token) => WriteTempAsync(source, path, o, token), rootFolder, tempDirectory, decide, options, ct)
|
||||||
|
.ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// As <see cref="SaveAsync(Stream, string, string, Func{FileDigest, CancellationToken, ValueTask{string}}, SafeWriteOptions, CancellationToken)"/>,
|
||||||
|
/// for content that is made while it is written (a converted photo, a remuxed video, a frame): <paramref name="produce"/>
|
||||||
|
/// writes it into the temporary file, through a stream that hashes and counts it (and honours
|
||||||
|
/// <see cref="SafeWriteOptions.MaxBytes"/> and <see cref="SafeWriteOptions.Progress"/>); then the same checks,
|
||||||
|
/// <paramref name="decide"/> and the free-name rename. Our own temporary file is removed on any failure.
|
||||||
|
/// </summary>
|
||||||
|
public async Task<SavedFile?> SaveAsync(
|
||||||
|
Func<Stream, CancellationToken, Task> produce,
|
||||||
|
string rootFolder,
|
||||||
|
string tempDirectory,
|
||||||
|
Func<FileDigest, CancellationToken, ValueTask<string?>> decide,
|
||||||
|
SafeWriteOptions? options = null,
|
||||||
|
CancellationToken ct = default)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(produce);
|
||||||
|
return await SaveCoreAsync((path, o, token) => ProduceTempAsync(produce, path, o, token), rootFolder, tempDirectory, decide, options, ct)
|
||||||
|
.ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task<SavedFile?> SaveCoreAsync(
|
||||||
|
Func<string, SafeWriteOptions, CancellationToken, Task<FileDigest>> write,
|
||||||
|
string rootFolder,
|
||||||
|
string tempDirectory,
|
||||||
|
Func<FileDigest, CancellationToken, ValueTask<string?>> decide,
|
||||||
|
SafeWriteOptions? options,
|
||||||
|
CancellationToken ct)
|
||||||
|
{
|
||||||
ArgumentException.ThrowIfNullOrWhiteSpace(rootFolder);
|
ArgumentException.ThrowIfNullOrWhiteSpace(rootFolder);
|
||||||
ArgumentNullException.ThrowIfNull(decide);
|
ArgumentNullException.ThrowIfNull(decide);
|
||||||
options ??= new SafeWriteOptions();
|
options ??= new SafeWriteOptions();
|
||||||
@@ -180,7 +218,7 @@ public sealed class SafeFileWriter(int maxPathLength = WindowsFileNames.MaxPathL
|
|||||||
|
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
var digest = await WriteTempAsync(source, tempPath, options, ct).ConfigureAwait(false);
|
var digest = await write(tempPath, options, ct).ConfigureAwait(false);
|
||||||
ct.ThrowIfCancellationRequested();
|
ct.ThrowIfCancellationRequested();
|
||||||
if (options.VerifyFromDisk)
|
if (options.VerifyFromDisk)
|
||||||
{
|
{
|
||||||
@@ -194,7 +232,7 @@ public sealed class SafeFileWriter(int maxPathLength = WindowsFileNames.MaxPathL
|
|||||||
}
|
}
|
||||||
|
|
||||||
ct.ThrowIfCancellationRequested();
|
ct.ThrowIfCancellationRequested();
|
||||||
var finalPath = MoveToFreeName(tempPath, root, desired, out var relative);
|
var finalPath = MoveToFreeName(tempPath, root, desired, options.KeepSuffix, out var relative);
|
||||||
var timeSet = true;
|
var timeSet = true;
|
||||||
if (options.LastWriteTime is { } time)
|
if (options.LastWriteTime is { } time)
|
||||||
{
|
{
|
||||||
@@ -289,6 +327,93 @@ public sealed class SafeFileWriter(int maxPathLength = WindowsFileNames.MaxPathL
|
|||||||
return new FileDigest(total, Convert.ToHexStringLower(hash.GetHashAndReset()));
|
return new FileDigest(total, Convert.ToHexStringLower(hash.GetHashAndReset()));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static async Task<FileDigest> ProduceTempAsync(Func<Stream, CancellationToken, Task> produce, string tempPath, SafeWriteOptions options, CancellationToken ct)
|
||||||
|
{
|
||||||
|
await using var target = new FileStream(tempPath, FileMode.CreateNew, FileAccess.Write, FileShare.None, BufferSize, FileOptions.Asynchronous);
|
||||||
|
using var hashing = new HashingStream(target, options);
|
||||||
|
await produce(hashing, ct).ConfigureAwait(false);
|
||||||
|
ct.ThrowIfCancellationRequested();
|
||||||
|
await target.FlushAsync(ct).ConfigureAwait(false);
|
||||||
|
target.Flush(flushToDisk: true);
|
||||||
|
return hashing.Digest();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>A write-only stream that hashes and counts what goes through it into the temporary file.</summary>
|
||||||
|
private sealed class HashingStream(Stream inner, SafeWriteOptions options) : Stream
|
||||||
|
{
|
||||||
|
private readonly IncrementalHash hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256);
|
||||||
|
private long total;
|
||||||
|
|
||||||
|
public override bool CanRead => false;
|
||||||
|
|
||||||
|
public override bool CanSeek => false;
|
||||||
|
|
||||||
|
public override bool CanWrite => true;
|
||||||
|
|
||||||
|
public override long Length => total;
|
||||||
|
|
||||||
|
public override long Position
|
||||||
|
{
|
||||||
|
get => total;
|
||||||
|
set => throw new NotSupportedException();
|
||||||
|
}
|
||||||
|
|
||||||
|
public FileDigest Digest() => new(total, Convert.ToHexStringLower(hash.GetHashAndReset()));
|
||||||
|
|
||||||
|
public override void Flush() => inner.Flush();
|
||||||
|
|
||||||
|
public override Task FlushAsync(CancellationToken cancellationToken) => inner.FlushAsync(cancellationToken);
|
||||||
|
|
||||||
|
public override int Read(byte[] buffer, int offset, int count) => throw new NotSupportedException();
|
||||||
|
|
||||||
|
public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException();
|
||||||
|
|
||||||
|
public override void SetLength(long value) => throw new NotSupportedException();
|
||||||
|
|
||||||
|
public override void Write(byte[] buffer, int offset, int count) => Write(buffer.AsSpan(offset, count));
|
||||||
|
|
||||||
|
public override void Write(ReadOnlySpan<byte> buffer)
|
||||||
|
{
|
||||||
|
Count(buffer);
|
||||||
|
inner.Write(buffer);
|
||||||
|
options.Progress?.Report(total);
|
||||||
|
}
|
||||||
|
|
||||||
|
public override void WriteByte(byte value) => Write([value]);
|
||||||
|
|
||||||
|
public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) =>
|
||||||
|
WriteAsync(buffer.AsMemory(offset, count), cancellationToken).AsTask();
|
||||||
|
|
||||||
|
public override async ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
Count(buffer.Span);
|
||||||
|
await inner.WriteAsync(buffer, cancellationToken).ConfigureAwait(false);
|
||||||
|
options.Progress?.Report(total);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected override void Dispose(bool disposing)
|
||||||
|
{
|
||||||
|
if (disposing)
|
||||||
|
{
|
||||||
|
hash.Dispose();
|
||||||
|
}
|
||||||
|
|
||||||
|
base.Dispose(disposing);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void Count(ReadOnlySpan<byte> buffer)
|
||||||
|
{
|
||||||
|
total += buffer.Length;
|
||||||
|
if (options.MaxBytes is { } max && total > max)
|
||||||
|
{
|
||||||
|
throw new FileTooLargeException(
|
||||||
|
string.Create(CultureInfo.InvariantCulture, $"Il file supera il limite di {max} byte: non viene salvato."));
|
||||||
|
}
|
||||||
|
|
||||||
|
hash.AppendData(buffer);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>Reads the temporary file back and compares its SHA-256 with the one computed while writing.</summary>
|
/// <summary>Reads the temporary file back and compares its SHA-256 with the one computed while writing.</summary>
|
||||||
private static async Task VerifyFromDiskAsync(string tempPath, FileDigest digest, CancellationToken ct)
|
private static async Task VerifyFromDiskAsync(string tempPath, FileDigest digest, CancellationToken ct)
|
||||||
{
|
{
|
||||||
@@ -316,7 +441,7 @@ public sealed class SafeFileWriter(int maxPathLength = WindowsFileNames.MaxPathL
|
|||||||
return segments.Count == 0 ? throw new ArgumentException("Il nome del file è vuoto.", nameof(relativePath)) : segments;
|
return segments.Count == 0 ? throw new ArgumentException("Il nome del file è vuoto.", nameof(relativePath)) : segments;
|
||||||
}
|
}
|
||||||
|
|
||||||
private string MoveToFreeName(string tempPath, string root, string desiredRelativePath, out string relative)
|
private string MoveToFreeName(string tempPath, string root, string desiredRelativePath, string? keepSuffix, out string relative)
|
||||||
{
|
{
|
||||||
var segments = Segments(desiredRelativePath);
|
var segments = Segments(desiredRelativePath);
|
||||||
var (stem, extension) = WindowsFileNames.SplitExtension(segments[^1]);
|
var (stem, extension) = WindowsFileNames.SplitExtension(segments[^1]);
|
||||||
@@ -324,7 +449,8 @@ public sealed class SafeFileWriter(int maxPathLength = WindowsFileNames.MaxPathL
|
|||||||
{
|
{
|
||||||
var name = attempt == 1 ? segments[^1] : string.Create(CultureInfo.InvariantCulture, $"{stem} ({attempt}){extension}");
|
var name = attempt == 1 ? segments[^1] : string.Create(CultureInfo.InvariantCulture, $"{stem} ({attempt}){extension}");
|
||||||
var candidate = segments.Take(segments.Count - 1).Append(WindowsFileNames.SanitizeSegment(name)).ToList();
|
var candidate = segments.Take(segments.Count - 1).Append(WindowsFileNames.SanitizeSegment(name)).ToList();
|
||||||
var fitted = WindowsFileNames.FitPath(root, candidate, maxPathLength);
|
var keep = keepSuffix is null ? null : attempt == 1 ? keepSuffix : string.Create(CultureInfo.InvariantCulture, $"{keepSuffix} ({attempt})");
|
||||||
|
var fitted = WindowsFileNames.FitPath(root, candidate, maxPathLength, keep);
|
||||||
relative = string.Join('/', fitted);
|
relative = string.Join('/', fitted);
|
||||||
var finalPath = LibraryLayout.FullPath(root, relative);
|
var finalPath = LibraryLayout.FullPath(root, relative);
|
||||||
Directory.CreateDirectory(Path.GetDirectoryName(finalPath)!);
|
Directory.CreateDirectory(Path.GetDirectoryName(finalPath)!);
|
||||||
|
|||||||
@@ -58,7 +58,7 @@ public sealed record VideoStillness(bool IsStill, int SampledFrames, double Diff
|
|||||||
/// (<see cref="H264Decoder"/>, <see cref="H265Decoder"/>). Videos in other codecs (VP9, AV1, ...) give no frame: the
|
/// (<see cref="H264Decoder"/>, <see cref="H265Decoder"/>). Videos in other codecs (VP9, AV1, ...) give no frame: the
|
||||||
/// interface shows the neutral tile.
|
/// interface shows the neutral tile.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public sealed class VideoFrameDecoder
|
public sealed partial class VideoFrameDecoder
|
||||||
{
|
{
|
||||||
/// <summary>Differences up to this value (0–255) count as compression noise of a still picture.</summary>
|
/// <summary>Differences up to this value (0–255) count as compression noise of a still picture.</summary>
|
||||||
public const double StillThreshold = 3.0;
|
public const double StillThreshold = 3.0;
|
||||||
@@ -77,8 +77,6 @@ public sealed class VideoFrameDecoder
|
|||||||
/// <summary>How far back from a sample flagged as key the decoder looks for one it can really start from.</summary>
|
/// <summary>How far back from a sample flagged as key the decoder looks for one it can really start from.</summary>
|
||||||
private const int MaxRunStartSearch = 2000;
|
private const int MaxRunStartSearch = 2000;
|
||||||
|
|
||||||
private static readonly DateTimeOffset AnyDate = new(9000, 1, 1, 0, 0, 0, TimeSpan.Zero);
|
|
||||||
|
|
||||||
private readonly TimeSpan budget;
|
private readonly TimeSpan budget;
|
||||||
private readonly int maxRun;
|
private readonly int maxRun;
|
||||||
|
|
||||||
@@ -184,10 +182,10 @@ public sealed class VideoFrameDecoder
|
|||||||
|
|
||||||
// The frame where the run starts comes along: it stands for a target that gives no picture (a RASL picture
|
// The frame where the run starts comes along: it stands for a target that gives no picture (a RASL picture
|
||||||
// of the HEVC CRA picture decoding starts from, a damaged sample).
|
// of the HEVC CRA picture decoding starts from, a damaged sample).
|
||||||
var frames = decoding.Decode(start < target ? [start, target] : [target], ct);
|
var frames = decoding.DecodeAll(start < target ? [start, target] : [target], ct);
|
||||||
if (!frames.TryGetValue(target, out var frame) && !frames.TryGetValue(start, out frame) && target != 0)
|
if (!frames.TryGetValue(target, out var frame) && !frames.TryGetValue(start, out frame) && target != 0)
|
||||||
{
|
{
|
||||||
frames = new Decoding(stream, video, maxRun).Decode([0], ct);
|
frames = new Decoding(stream, video, maxRun).DecodeAll([0], ct);
|
||||||
frames.TryGetValue(0, out frame);
|
frames.TryGetValue(0, out frame);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -248,7 +246,7 @@ public sealed class VideoFrameDecoder
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
var frames = decoding.Decode([.. targets], ct);
|
var frames = decoding.DecodeAll([.. targets], ct);
|
||||||
if (frames.Count < 2)
|
if (frames.Count < 2)
|
||||||
{
|
{
|
||||||
return null;
|
return null;
|
||||||
@@ -295,7 +293,7 @@ public sealed class VideoFrameDecoder
|
|||||||
private static VideoTrack? Open(Stream stream)
|
private static VideoTrack? Open(Stream stream)
|
||||||
{
|
{
|
||||||
// The creation time does not matter here: any date is accepted (the readers add a day to «now»).
|
// The creation time does not matter here: any date is accepted (the readers add a day to «now»).
|
||||||
var container = ContainerReader.Read(stream, AnyDate, samples: true);
|
var container = ContainerReader.Read(stream, ContainerReader.AnyDate, samples: true);
|
||||||
return container?.Video is { Samples.Count: > 0 } video && video.Codec switch
|
return container?.Video is { Samples.Count: > 0 } video && video.Codec switch
|
||||||
{
|
{
|
||||||
VideoCodec.H264 => video.AnnexB || video.AvcConfiguration is not null,
|
VideoCodec.H264 => video.AnnexB || video.AvcConfiguration is not null,
|
||||||
@@ -362,6 +360,13 @@ public sealed class VideoFrameDecoder
|
|||||||
|
|
||||||
/// <summary>Exact: an H.264 IDR picture, an HEVC IDR or BLA picture.</summary>
|
/// <summary>Exact: an H.264 IDR picture, an HEVC IDR or BLA picture.</summary>
|
||||||
Idr,
|
Idr,
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Exact for the pictures shown from it on: an HEVC CRA picture (only its RASL pictures, shown before it, are
|
||||||
|
/// lost), an H.264 I picture with a recovery point SEI whose recovery_frame_cnt is 0. Elsewhere close, as
|
||||||
|
/// <see cref="Intra"/>.
|
||||||
|
/// </summary>
|
||||||
|
Recovery,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>Size of the NAL length fields of the samples (0: Annex B), from the configuration record.</summary>
|
/// <summary>Size of the NAL length fields of the samples (0: Annex B), from the configuration record.</summary>
|
||||||
@@ -436,9 +441,11 @@ public sealed class VideoFrameDecoder
|
|||||||
/// <summary>
|
/// <summary>
|
||||||
/// Decodes chosen samples, each from the random access point before it, reusing a run when the targets share it.
|
/// Decodes chosen samples, each from the random access point before it, reusing a run when the targets share it.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
private sealed class Decoding(Stream stream, VideoTrack video, int maxRun)
|
private sealed class Decoding(Stream stream, VideoTrack video, int maxRun, bool exact = false)
|
||||||
{
|
{
|
||||||
private readonly Dictionary<int, Frame> found = [];
|
private readonly Dictionary<int, Frame> found = [];
|
||||||
|
private readonly HashSet<int> produced = [];
|
||||||
|
private readonly List<(int Sample, Frame Frame)> pending = [];
|
||||||
private readonly HashSet<int> wanted = [];
|
private readonly HashSet<int> wanted = [];
|
||||||
private readonly int[] keys = KeyIndices(video);
|
private readonly int[] keys = KeyIndices(video);
|
||||||
private readonly Dictionary<int, StartPoint> accessPoints = [];
|
private readonly Dictionary<int, StartPoint> accessPoints = [];
|
||||||
@@ -458,6 +465,11 @@ public sealed class VideoFrameDecoder
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
internal int RunStart(int index)
|
internal int RunStart(int index)
|
||||||
{
|
{
|
||||||
|
if (exact)
|
||||||
|
{
|
||||||
|
return ExactStart(index);
|
||||||
|
}
|
||||||
|
|
||||||
var position = Array.BinarySearch(keys, index);
|
var position = Array.BinarySearch(keys, index);
|
||||||
position = position >= 0 ? position : Math.Max(0, ~position - 1);
|
position = position >= 0 ? position : Math.Max(0, ~position - 1);
|
||||||
var intra = -1;
|
var intra = -1;
|
||||||
@@ -475,7 +487,7 @@ public sealed class VideoFrameDecoder
|
|||||||
return index - candidate <= maxRun || intra < 0 ? candidate : intra;
|
return index - candidate <= maxRun || intra < 0 ? candidate : intra;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (point == StartPoint.Intra && intra < 0)
|
if (point is StartPoint.Intra or StartPoint.Recovery && intra < 0)
|
||||||
{
|
{
|
||||||
intra = candidate;
|
intra = candidate;
|
||||||
}
|
}
|
||||||
@@ -490,6 +502,34 @@ public sealed class VideoFrameDecoder
|
|||||||
return index <= maxRun || intra < 0 ? 0 : intra;
|
return index <= maxRun || intra < 0 ? 0 : intra;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The nearest start from which <paramref name="index"/> comes out exact, however far: an IDR picture, or a
|
||||||
|
/// recovery point shown no later than it; otherwise the first sample.
|
||||||
|
/// </summary>
|
||||||
|
private int ExactStart(int index)
|
||||||
|
{
|
||||||
|
var position = Array.BinarySearch(keys, index);
|
||||||
|
position = position >= 0 ? position : Math.Max(0, ~position - 1);
|
||||||
|
var shown = video.Samples[index].PresentationTime;
|
||||||
|
for (var tried = 0; position > 0 && tried < MaxRunStartSearch; position--, tried++)
|
||||||
|
{
|
||||||
|
var candidate = keys[position];
|
||||||
|
if (!accessPoints.TryGetValue(candidate, out var point))
|
||||||
|
{
|
||||||
|
point = AccessPointOf(candidate);
|
||||||
|
accessPoints[candidate] = point;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (point == StartPoint.Idr
|
||||||
|
|| (point == StartPoint.Recovery && shown >= video.Samples[candidate].PresentationTime))
|
||||||
|
{
|
||||||
|
return candidate;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
private StartPoint AccessPointOf(int index)
|
private StartPoint AccessPointOf(int index)
|
||||||
{
|
{
|
||||||
try
|
try
|
||||||
@@ -500,7 +540,7 @@ public sealed class VideoFrameDecoder
|
|||||||
return H265Decoder.AccessPoint(sample, lengthSize) switch
|
return H265Decoder.AccessPoint(sample, lengthSize) switch
|
||||||
{
|
{
|
||||||
H265AccessPoint.Idr => StartPoint.Idr,
|
H265AccessPoint.Idr => StartPoint.Idr,
|
||||||
H265AccessPoint.Cra => StartPoint.Intra,
|
H265AccessPoint.Cra => StartPoint.Recovery,
|
||||||
_ => StartPoint.None,
|
_ => StartPoint.None,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -508,6 +548,7 @@ public sealed class VideoFrameDecoder
|
|||||||
return H264Decoder.AccessPoint(sample, lengthSize) switch
|
return H264Decoder.AccessPoint(sample, lengthSize) switch
|
||||||
{
|
{
|
||||||
H264AccessPoint.Idr => StartPoint.Idr,
|
H264AccessPoint.Idr => StartPoint.Idr,
|
||||||
|
H264AccessPoint.IntraPicture when H264Decoder.HasExactRecoveryPoint(sample, lengthSize) => StartPoint.Recovery,
|
||||||
H264AccessPoint.IntraPicture => StartPoint.Intra,
|
H264AccessPoint.IntraPicture => StartPoint.Intra,
|
||||||
_ => StartPoint.None,
|
_ => StartPoint.None,
|
||||||
};
|
};
|
||||||
@@ -518,7 +559,25 @@ public sealed class VideoFrameDecoder
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
internal Dictionary<int, Frame> Decode(int[] targets, CancellationToken ct)
|
/// <summary>
|
||||||
|
/// Decodes the targets (sample indices in ascending order) and keeps every frame: the few a thumbnail or a
|
||||||
|
/// stillness check asks for.
|
||||||
|
/// </summary>
|
||||||
|
internal Dictionary<int, Frame> DecodeAll(int[] targets, CancellationToken ct)
|
||||||
|
{
|
||||||
|
foreach (var (sample, frame) in Decode(targets, ct))
|
||||||
|
{
|
||||||
|
found.TryAdd(sample, frame);
|
||||||
|
}
|
||||||
|
|
||||||
|
return found;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Decodes the targets (sample indices in ascending order) and hands out each frame as soon as the sample that
|
||||||
|
/// finishes it is decoded, in decoding order, once per sample; a target that gives no picture is left out.
|
||||||
|
/// </summary>
|
||||||
|
internal IEnumerable<(int Sample, Frame Frame)> Decode(int[] targets, CancellationToken ct)
|
||||||
{
|
{
|
||||||
foreach (var t in targets)
|
foreach (var t in targets)
|
||||||
{
|
{
|
||||||
@@ -536,29 +595,56 @@ public sealed class VideoFrameDecoder
|
|||||||
next = key;
|
next = key;
|
||||||
}
|
}
|
||||||
|
|
||||||
try
|
for (; next <= target; next++)
|
||||||
{
|
{
|
||||||
// Frames are matched to samples by the sample being decoded, not by the decoder's own count: a
|
ct.ThrowIfCancellationRequested();
|
||||||
// sample without a picture (only parameter sets, a skipped RASL picture, or damaged) must not shift
|
if (!Step(ref runner, next))
|
||||||
// the frames after it.
|
|
||||||
runner ??= new Runner(video, () => wanted.Contains(current), frame => found.TryAdd(current, frame));
|
|
||||||
for (; next <= target; next++)
|
|
||||||
{
|
{
|
||||||
ct.ThrowIfCancellationRequested();
|
// This run is damaged (or its samples lie past the end of a truncated file): the next target
|
||||||
current = next;
|
// starts again from its own key frame, and what was decoded so far stands.
|
||||||
runner.Decode(ContainerReader.ReadSample(stream, video.Samples[next], ref buffer));
|
runner = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach (var item in pending)
|
||||||
|
{
|
||||||
|
yield return item;
|
||||||
|
}
|
||||||
|
|
||||||
|
pending.Clear();
|
||||||
|
if (runner is null)
|
||||||
|
{
|
||||||
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
catch (Exception ex) when (ex is H264Exception or H265Exception or ContainerException or EndOfStreamException
|
|
||||||
or IndexOutOfRangeException or ArgumentException or InvalidOperationException)
|
|
||||||
{
|
|
||||||
// This run is damaged (or its samples lie past the end of a truncated file): the next target starts
|
|
||||||
// again from its own key frame, and what was decoded so far stands.
|
|
||||||
runner = null;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return found;
|
/// <summary>Decodes one sample; false when the stream is damaged there.</summary>
|
||||||
|
private bool Step(ref Runner? runner, int sample)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
// Frames are matched to samples by the sample being decoded, not by the decoder's own count: a sample
|
||||||
|
// without a picture (only parameter sets, a skipped RASL picture, or damaged) must not shift the frames
|
||||||
|
// after it.
|
||||||
|
runner ??= new Runner(video, () => wanted.Contains(current), Found);
|
||||||
|
current = sample;
|
||||||
|
runner.Decode(ContainerReader.ReadSample(stream, video.Samples[sample], ref buffer));
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
catch (Exception ex) when (ex is H264Exception or H265Exception or ContainerException or EndOfStreamException
|
||||||
|
or IndexOutOfRangeException or ArgumentException or InvalidOperationException)
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void Found(Frame frame)
|
||||||
|
{
|
||||||
|
if (produced.Add(current))
|
||||||
|
{
|
||||||
|
pending.Add((current, frame));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,348 @@
|
|||||||
|
using Febe.Core.Codecs;
|
||||||
|
using Febe.Core.Codecs.Containers;
|
||||||
|
using Febe.Core.Codecs.Images;
|
||||||
|
using YuvToRgb = Febe.Core.Codecs.YuvToRgb;
|
||||||
|
|
||||||
|
namespace Febe.Core.Library;
|
||||||
|
|
||||||
|
/// <summary>What <see cref="VideoFrameReader.Open"/> found about a video.</summary>
|
||||||
|
/// <param name="Available">False when no frame can be taken from it: <paramref name="Unavailable"/> says why.</param>
|
||||||
|
/// <param name="Unavailable">The Italian message shown when frames are not available; null otherwise.</param>
|
||||||
|
/// <param name="Duration">The presentation length (zero when unknown).</param>
|
||||||
|
/// <param name="Width">Width of a frame as shown (rotation applied).</param>
|
||||||
|
/// <param name="Height">Height of a frame as shown (rotation applied).</param>
|
||||||
|
/// <param name="Rotation">Clockwise rotation of the track: 0, 90, 180 or 270.</param>
|
||||||
|
/// <param name="Codec">The video codec («H264», «Hevc»), or the container's codec tag of one Febe does not decode.</param>
|
||||||
|
/// <param name="FrameDuration">The mean time between two frames (zero when unknown).</param>
|
||||||
|
/// <param name="HasAudio">Whether the container has an audio track.</param>
|
||||||
|
/// <param name="SampleCount">Samples of the video track.</param>
|
||||||
|
public sealed record VideoFrameInfo(bool Available, string? Unavailable, TimeSpan Duration, int Width, int Height,
|
||||||
|
int Rotation, string Codec, TimeSpan FrameDuration, bool HasAudio, int SampleCount);
|
||||||
|
|
||||||
|
/// <summary>A frame to take: the instant asked for and the sample really shown then (spec §4.10 «Fotogrammi»).</summary>
|
||||||
|
/// <param name="Index">Position of the instant in the request (0-based), which names the file.</param>
|
||||||
|
/// <param name="Requested">The instant asked for.</param>
|
||||||
|
/// <param name="Actual">
|
||||||
|
/// When the sample is shown, rounded up to the next 100 ns tick: what the frame's identity and name carry.
|
||||||
|
/// </param>
|
||||||
|
/// <param name="Sample">The sample index in decoding order.</param>
|
||||||
|
public sealed record VideoFrameTarget(int Index, TimeSpan Requested, TimeSpan Actual, int Sample);
|
||||||
|
|
||||||
|
/// <summary>A decoded frame, upright, in 8-bit RGBA (alpha 255). Dispose it to give the pixels back.</summary>
|
||||||
|
public sealed class VideoFrame(int index, TimeSpan requested, TimeSpan actual, RgbaImage image) : IDisposable
|
||||||
|
{
|
||||||
|
/// <summary>Position of the instant in the request.</summary>
|
||||||
|
public int Index { get; } = index;
|
||||||
|
|
||||||
|
/// <summary>The instant asked for.</summary>
|
||||||
|
public TimeSpan Requested { get; } = requested;
|
||||||
|
|
||||||
|
/// <summary>When the frame is shown.</summary>
|
||||||
|
public TimeSpan Actual { get; } = actual;
|
||||||
|
|
||||||
|
/// <summary>The pixels, rotated as the video is shown.</summary>
|
||||||
|
public RgbaImage Image { get; } = image;
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
public void Dispose() => Image.Dispose();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Frames of a video at chosen instants, at full resolution and exact (spec §4.10 «Fotogrammi»): instants are the
|
||||||
|
/// presentation times as a player shows them (ISO edit lists included), each frame decoded from a point the decoder can
|
||||||
|
/// start from exactly, and turned upright. One frame lives in memory at a time; the stream must stay open and seekable
|
||||||
|
/// while the reader is used.
|
||||||
|
/// </summary>
|
||||||
|
public sealed class VideoFrameReader : IDisposable
|
||||||
|
{
|
||||||
|
/// <summary>The message for a video whose frames Febe cannot take.</summary>
|
||||||
|
public const string NotAvailableMessage = "Fotogramma non disponibile per questo video";
|
||||||
|
|
||||||
|
private readonly Stream? stream;
|
||||||
|
private readonly VideoTrack? video;
|
||||||
|
|
||||||
|
/// <summary>Shown time of each sample in track units (presentation time plus the empty edits).</summary>
|
||||||
|
private readonly long[] shown = [];
|
||||||
|
|
||||||
|
/// <summary>The samples that can be chosen, by shown time then decoding order.</summary>
|
||||||
|
private readonly int[] order = [];
|
||||||
|
|
||||||
|
private VideoFrameReader(Stream? stream, VideoTrack? video)
|
||||||
|
{
|
||||||
|
this.stream = stream;
|
||||||
|
this.video = video;
|
||||||
|
if (video is null)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
var samples = video.Samples;
|
||||||
|
shown = new long[samples.Count];
|
||||||
|
for (var i = 0; i < samples.Count; i++)
|
||||||
|
{
|
||||||
|
shown[i] = samples[i].PresentationTime + video.EmptyEditDuration;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Samples shown before the start or from the end of the edit on (cut by the edit list) are not chosen, unless
|
||||||
|
// nothing else is.
|
||||||
|
var end = video.EditSegmentDuration is { } segment && segment > 0 ? video.EmptyEditDuration + segment : long.MaxValue;
|
||||||
|
var visible = Enumerable.Range(0, samples.Count).Where(i => shown[i] >= 0 && shown[i] < end).ToArray();
|
||||||
|
order = visible.Length > 0 ? visible : [.. Enumerable.Range(0, samples.Count)];
|
||||||
|
Array.Sort(order, (a, b) => shown[a] != shown[b] ? shown[a].CompareTo(shown[b]) : a.CompareTo(b));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Opens the video in <paramref name="seekable"/> (left open: the caller disposes it after the reader). Never
|
||||||
|
/// throws for a video it cannot read: <paramref name="info"/> is then not available, and the reader gives no frame.
|
||||||
|
/// </summary>
|
||||||
|
public static VideoFrameReader Open(Stream seekable, out VideoFrameInfo info)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(seekable);
|
||||||
|
MediaContainer? container;
|
||||||
|
VideoTrack? video;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
seekable.Position = 0;
|
||||||
|
container = ContainerReader.Read(seekable, ContainerReader.AnyDate, samples: true);
|
||||||
|
video = container is null ? null : VideoFrameDecoder.FrameTrack(container);
|
||||||
|
}
|
||||||
|
catch (Exception ex) when (VideoFrameDecoder.IsUnreadableFile(ex))
|
||||||
|
{
|
||||||
|
container = null;
|
||||||
|
video = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (container?.Video is not { } track || video is null)
|
||||||
|
{
|
||||||
|
var v = container?.Video;
|
||||||
|
info = new VideoFrameInfo(false, NotAvailableMessage, container?.Duration ?? TimeSpan.Zero,
|
||||||
|
v?.DisplayWidth ?? 0, v?.DisplayHeight ?? 0, v?.Rotation ?? 0, v is null ? string.Empty : Codec(v),
|
||||||
|
TimeSpan.Zero, container?.Audio is not null, v?.Samples.Count ?? 0);
|
||||||
|
return new VideoFrameReader(null, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
var reader = new VideoFrameReader(seekable, video);
|
||||||
|
info = new VideoFrameInfo(true, null, reader.Duration(container), track.DisplayWidth, track.DisplayHeight,
|
||||||
|
Rotation(track.Rotation), Codec(track), reader.FrameDuration(), container.Audio is not null, track.Samples.Count);
|
||||||
|
return reader;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The length of the video from its headers only (no sample table walked through); null when unreadable.</summary>
|
||||||
|
public static TimeSpan? ProbeDuration(Stream seekable)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(seekable);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
seekable.Position = 0;
|
||||||
|
return ContainerReader.Read(seekable, ContainerReader.AnyDate, samples: false)?.Duration;
|
||||||
|
}
|
||||||
|
catch (Exception ex) when (VideoFrameDecoder.IsUnreadableFile(ex))
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The sample shown at each instant: the one with the greatest shown time not after it; the first one for an
|
||||||
|
/// instant before it, the last one for an instant past the end. Empty when the video is not available.
|
||||||
|
/// </summary>
|
||||||
|
public IReadOnlyList<VideoFrameTarget> Locate(IReadOnlyList<TimeSpan> instants)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(instants);
|
||||||
|
if (video is null || order.Length == 0)
|
||||||
|
{
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
var targets = new VideoFrameTarget[instants.Count];
|
||||||
|
for (var i = 0; i < instants.Count; i++)
|
||||||
|
{
|
||||||
|
var sample = SampleAt(instants[i]);
|
||||||
|
targets[i] = new VideoFrameTarget(i, instants[i], ShownAt(sample), sample);
|
||||||
|
}
|
||||||
|
|
||||||
|
return targets;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Decodes the targets lazily, in decoding order (not the order of the instants): each frame comes out as soon as it
|
||||||
|
/// is decoded and must be disposed by the caller. A target whose sample gives no picture (a damaged stream) is left
|
||||||
|
/// out; targets on the same sample each get their own copy.
|
||||||
|
/// </summary>
|
||||||
|
public IEnumerable<VideoFrame> Decode(IReadOnlyList<VideoFrameTarget> targets, CancellationToken ct)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(targets);
|
||||||
|
return video is null || stream is null || targets.Count == 0 ? [] : DecodeCore(targets, ct);
|
||||||
|
}
|
||||||
|
|
||||||
|
private IEnumerable<VideoFrame> DecodeCore(IReadOnlyList<VideoFrameTarget> targets, CancellationToken ct)
|
||||||
|
{
|
||||||
|
var bySample = targets.Where(t => t.Sample >= 0 && t.Sample < shown.Length)
|
||||||
|
.GroupBy(t => t.Sample)
|
||||||
|
.ToDictionary(g => g.Key, g => g.OrderBy(t => t.Index).ToArray());
|
||||||
|
int[] samples = [.. bySample.Keys.Order()];
|
||||||
|
foreach (var (sample, image) in VideoFrameDecoder.DecodeExact(stream!, video!, samples, ct))
|
||||||
|
{
|
||||||
|
var wanted = bySample[sample];
|
||||||
|
for (var i = 0; i < wanted.Length; i++)
|
||||||
|
{
|
||||||
|
var copy = i == wanted.Length - 1 ? image : new RgbaImage(image.Width, image.Height, image.ToArray());
|
||||||
|
yield return new VideoFrame(wanted[i].Index, wanted[i].Requested, wanted[i].Actual, copy);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
public void Dispose()
|
||||||
|
{
|
||||||
|
// The stream belongs to the caller; nothing else is held.
|
||||||
|
}
|
||||||
|
|
||||||
|
private int SampleAt(TimeSpan at)
|
||||||
|
{
|
||||||
|
// Exact comparison of at (100 ns ticks) with a shown time (track units): at·timescale against shown·10⁷.
|
||||||
|
var timescale = (Int128)video!.Timescale;
|
||||||
|
var wanted = (Int128)at.Ticks * timescale;
|
||||||
|
int low = 0, high = order.Length - 1, best = -1;
|
||||||
|
while (low <= high)
|
||||||
|
{
|
||||||
|
var middle = (low + high) / 2;
|
||||||
|
if ((Int128)shown[order[middle]] * TimeSpan.TicksPerSecond <= wanted)
|
||||||
|
{
|
||||||
|
best = middle;
|
||||||
|
low = middle + 1;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
high = middle - 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (best < 0)
|
||||||
|
{
|
||||||
|
return order[0];
|
||||||
|
}
|
||||||
|
|
||||||
|
// Among samples shown at the same time, the first in decoding order.
|
||||||
|
while (best > 0 && shown[order[best - 1]] == shown[order[best]])
|
||||||
|
{
|
||||||
|
best--;
|
||||||
|
}
|
||||||
|
|
||||||
|
return order[best];
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The shown time of a sample as a TimeSpan, rounded up to the tick (never before it is shown).</summary>
|
||||||
|
private TimeSpan ShownAt(int sample)
|
||||||
|
{
|
||||||
|
var timescale = (Int128)Math.Max(1, video!.Timescale);
|
||||||
|
var units = (Int128)Math.Max(0, shown[sample]);
|
||||||
|
var ticks = ((units * TimeSpan.TicksPerSecond) + timescale - 1) / timescale;
|
||||||
|
return TimeSpan.FromTicks((long)Int128.Min(ticks, TimeSpan.MaxValue.Ticks));
|
||||||
|
}
|
||||||
|
|
||||||
|
private TimeSpan Duration(MediaContainer container)
|
||||||
|
{
|
||||||
|
if (container.Duration is { } d && d > TimeSpan.Zero)
|
||||||
|
{
|
||||||
|
return d;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (video!.Duration > 0 && video.Timescale > 0)
|
||||||
|
{
|
||||||
|
return TimeSpan.FromTicks((long)((Int128)video.Duration * TimeSpan.TicksPerSecond / video.Timescale));
|
||||||
|
}
|
||||||
|
|
||||||
|
return order.Length == 0 ? TimeSpan.Zero : ShownAt(order[^1]) + FrameDuration();
|
||||||
|
}
|
||||||
|
|
||||||
|
private TimeSpan FrameDuration()
|
||||||
|
{
|
||||||
|
if (order.Length < 2 || video!.Timescale <= 0)
|
||||||
|
{
|
||||||
|
return TimeSpan.Zero;
|
||||||
|
}
|
||||||
|
|
||||||
|
var span = (Int128)(shown[order[^1]] - shown[order[0]]) * TimeSpan.TicksPerSecond;
|
||||||
|
return TimeSpan.FromTicks((long)(span / video.Timescale / (order.Length - 1)));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int Rotation(int rotation) => ((rotation % 360) + 360) % 360 is var r && r is 90 or 180 or 270 ? r : 0;
|
||||||
|
|
||||||
|
private static string Codec(VideoTrack video) =>
|
||||||
|
video.Codec is VideoCodec.H264 or VideoCodec.Hevc ? video.Codec.ToString() : video.CodecTag;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The frames part of the decoder: what <see cref="VideoFrameReader"/> needs of its private machinery.</summary>
|
||||||
|
public sealed partial class VideoFrameDecoder
|
||||||
|
{
|
||||||
|
/// <summary>The track frames can be taken from: H.264 or HEVC with its samples and configuration; else null.</summary>
|
||||||
|
internal static VideoTrack? FrameTrack(MediaContainer container) =>
|
||||||
|
container.Video is { Samples.Count: > 0, Encoded: false } video && video.Codec switch
|
||||||
|
{
|
||||||
|
VideoCodec.H264 => video.AnnexB || video.AvcConfiguration is not null,
|
||||||
|
VideoCodec.Hevc => video.AnnexB || video.HevcConfiguration is not null,
|
||||||
|
_ => false,
|
||||||
|
}
|
||||||
|
? video
|
||||||
|
: null;
|
||||||
|
|
||||||
|
/// <summary>Whether an exception while reading a video means a file that cannot be read (not a bug).</summary>
|
||||||
|
internal static bool IsUnreadableFile(Exception ex) => IsUnreadable(ex);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Decodes the samples (ascending indices) exactly, each from an IDR picture or a recovery point shown no later than
|
||||||
|
/// it (else from the first sample), and gives each frame in RGBA, rotated upright, in decoding order.
|
||||||
|
/// </summary>
|
||||||
|
internal static IEnumerable<(int Sample, RgbaImage Image)> DecodeExact(Stream stream, VideoTrack video, int[] samples,
|
||||||
|
CancellationToken ct)
|
||||||
|
{
|
||||||
|
var decoding = new Decoding(stream, video, int.MaxValue, exact: true);
|
||||||
|
foreach (var (sample, frame) in decoding.Decode(samples, ct))
|
||||||
|
{
|
||||||
|
yield return (sample, ToRgba(frame, video.Rotation));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>A frame at full size in RGBA (alpha 255), brought to 8 bits, then turned as the video is shown.</summary>
|
||||||
|
private static RgbaImage ToRgba(Frame frame, int rotation)
|
||||||
|
{
|
||||||
|
RgbaImage image;
|
||||||
|
if (frame.Hevc is { } h)
|
||||||
|
{
|
||||||
|
image = ToRgba(Planes(h), h.MatrixCoefficients, h.FullRange);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
var a = frame.Avc!;
|
||||||
|
image = a.BytesPerSample == 2
|
||||||
|
? ToRgba(WidePlanes(a), a.MatrixCoefficients, a.FullRange)
|
||||||
|
: ToRgba(Planes(a), a.MatrixCoefficients, a.FullRange);
|
||||||
|
}
|
||||||
|
|
||||||
|
var orientation = (((rotation % 360) + 360) % 360) switch
|
||||||
|
{
|
||||||
|
90 => 6,
|
||||||
|
180 => 3,
|
||||||
|
270 => 8,
|
||||||
|
_ => 1,
|
||||||
|
};
|
||||||
|
var upright = ImageOrientation.Apply(image, orientation);
|
||||||
|
if (!ReferenceEquals(upright, image))
|
||||||
|
{
|
||||||
|
image.Dispose();
|
||||||
|
}
|
||||||
|
|
||||||
|
return upright;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static RgbaImage ToRgba<T>(in YuvPlanes<T> planes, int matrix, bool fullRange)
|
||||||
|
where T : unmanaged, System.Numerics.IBinaryInteger<T>
|
||||||
|
{
|
||||||
|
var image = new RgbaImage(planes.Width, planes.Height);
|
||||||
|
var k = YuvToRgb.For(matrix, fullRange, planes.BitDepthY, planes.BitDepthC, planes.Height);
|
||||||
|
YuvToRgb.Convert(planes, k, 1, image.Pixels, planes.Width * RgbaImage.BytesPerPixel, RgbaImage.BytesPerPixel,
|
||||||
|
planes.Width, planes.Height);
|
||||||
|
return image;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -89,8 +89,15 @@ public static class WindowsFileNames
|
|||||||
/// keeping its extension; then the longest folder segments. A shortened part ends with <c>~</c> and eight hex digits
|
/// keeping its extension; then the longest folder segments. A shortened part ends with <c>~</c> and eight hex digits
|
||||||
/// of the SHA-256 of the original, so different names stay different (for example <c>_1</c> and <c>_2</c>).
|
/// of the SHA-256 of the original, so different names stay different (for example <c>_1</c> and <c>_2</c>).
|
||||||
/// </summary>
|
/// </summary>
|
||||||
|
/// <param name="baseFolder">The folder the path is below.</param>
|
||||||
|
/// <param name="segments">The segments.</param>
|
||||||
|
/// <param name="maxLength">The longest full path.</param>
|
||||||
|
/// <param name="keepSuffix">
|
||||||
|
/// When the stem of the file name ends with it (a frame suffix, «_t0m12s340»), the part before it is shortened and the
|
||||||
|
/// hash goes before it: «nome~1a2b3c4d_t0m12s340.png». Null: the whole stem may be cut, as before tappa E3.
|
||||||
|
/// </param>
|
||||||
/// <exception cref="PathTooLongException">Even shortened, the path does not fit (the base folder is too long).</exception>
|
/// <exception cref="PathTooLongException">Even shortened, the path does not fit (the base folder is too long).</exception>
|
||||||
public static IReadOnlyList<string> FitPath(string baseFolder, IReadOnlyList<string> segments, int maxLength = MaxPathLength)
|
public static IReadOnlyList<string> FitPath(string baseFolder, IReadOnlyList<string> segments, int maxLength = MaxPathLength, string? keepSuffix = null)
|
||||||
{
|
{
|
||||||
ArgumentNullException.ThrowIfNull(baseFolder);
|
ArgumentNullException.ThrowIfNull(baseFolder);
|
||||||
ArgumentNullException.ThrowIfNull(segments);
|
ArgumentNullException.ThrowIfNull(segments);
|
||||||
@@ -111,11 +118,11 @@ public static class WindowsFileNames
|
|||||||
|
|
||||||
// 1. The file name, keeping its extension.
|
// 1. The file name, keeping its extension.
|
||||||
var last = parts.Length - 1;
|
var last = parts.Length - 1;
|
||||||
var (stem, extension) = SplitExtension(parts[last]);
|
var (stem, extension) = SplitKept(parts[last], keepSuffix);
|
||||||
var stemTarget = Math.Max(stem.Length - excess, Math.Min(stem.Length, MinimumStem + HashSuffixLength));
|
var stemTarget = Math.Max(stem.Length - excess, Math.Min(stem.Length, MinimumStem + HashSuffixLength));
|
||||||
if (stemTarget < stem.Length)
|
if (stemTarget < stem.Length)
|
||||||
{
|
{
|
||||||
parts[last] = Shorten(parts[last], stemTarget + extension.Length, keepExtension: true);
|
parts[last] = Shorten(parts[last], stemTarget + extension.Length, keepExtension: true, keepSuffix);
|
||||||
excess = Total() - maxLength;
|
excess = Total() - maxLength;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -156,10 +163,22 @@ public static class WindowsFileNames
|
|||||||
: (fileName[..dot], fileName[dot..]);
|
: (fileName[..dot], fileName[dot..]);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>Shortens a name to at most <paramref name="maxLength"/> characters with a hash suffix of the original.</summary>
|
/// <summary>
|
||||||
private static string Shorten(string name, int maxLength, bool keepExtension)
|
/// The stem and the end that is kept of a file name: the extension, preceded by <paramref name="keepSuffix"/> when
|
||||||
|
/// the stem ends with it.
|
||||||
|
/// </summary>
|
||||||
|
private static (string Stem, string Kept) SplitKept(string fileName, string? keepSuffix)
|
||||||
{
|
{
|
||||||
var (stem, extension) = keepExtension ? SplitExtension(name) : (name, string.Empty);
|
var (stem, extension) = SplitExtension(fileName);
|
||||||
|
return keepSuffix is { Length: > 0 } && stem.Length > keepSuffix.Length && stem.EndsWith(keepSuffix, StringComparison.Ordinal)
|
||||||
|
? (stem[..^keepSuffix.Length], keepSuffix + extension)
|
||||||
|
: (stem, extension);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Shortens a name to at most <paramref name="maxLength"/> characters with a hash suffix of the original.</summary>
|
||||||
|
private static string Shorten(string name, int maxLength, bool keepExtension, string? keepSuffix = null)
|
||||||
|
{
|
||||||
|
var (stem, extension) = keepExtension ? SplitKept(name, keepSuffix) : (name, string.Empty);
|
||||||
var room = maxLength - extension.Length - HashSuffixLength;
|
var room = maxLength - extension.Length - HashSuffixLength;
|
||||||
if (room < 1)
|
if (room < 1)
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -58,11 +58,36 @@ public interface IEntryStore
|
|||||||
/// «Eliminato»: the entry stays without files so it is not downloaded again (spec §4.6). Its files become
|
/// «Eliminato»: the entry stays without files so it is not downloaded again (spec §4.6). Its files become
|
||||||
/// <see cref="MediaState.Deleted"/> and lose their path and perceptual hash; SHA-256 and size are kept. Deleting files on disk is the caller's job.
|
/// <see cref="MediaState.Deleted"/> and lose their path and perceptual hash; SHA-256 and size are kept. Deleting files on disk is the caller's job.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
Task MarkDeletedAsync(long entryId, DateTimeOffset at, CancellationToken ct = default);
|
Task MarkDeletedAsync(long entryId, DateTimeOffset at, CancellationToken ct = default) => MarkDeletedAsync(entryId, at, [], ct);
|
||||||
|
|
||||||
/// <summary>«Eliminalo e lascia che torni»: removes the record (files records and highlight links by cascade).</summary>
|
/// <summary>
|
||||||
|
/// As <see cref="MarkDeletedAsync(long, DateTimeOffset, CancellationToken)"/>, and in the same transaction the
|
||||||
|
/// conversions for the library of its files: the queue and the failures (Pending, Failed) go, and the rows of
|
||||||
|
/// <paramref name="removedConversionIds"/> (whose converted file goes or is gone) become «Tolto». Other converted rows stay.
|
||||||
|
/// </summary>
|
||||||
|
Task MarkDeletedAsync(long entryId, DateTimeOffset at, IReadOnlyCollection<long> removedConversionIds, CancellationToken ct = default);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// «Elimina dalla libreria» with memory: as <see cref="MarkDeletedAsync(long, DateTimeOffset, CancellationToken)"/>,
|
||||||
|
/// and in the same transaction every conversion of its files with a file (Converted, Superseded) becomes «Tolto»
|
||||||
|
/// and is returned as it was: chosen inside the transaction, so a conversion recorded just before is among them
|
||||||
|
/// (its file is the caller's to delete) and none can be recorded after. The queue and the failures go.
|
||||||
|
/// </summary>
|
||||||
|
Task<IReadOnlyList<MediaConversion>> MarkDeletedWithConversionsAsync(long entryId, DateTimeOffset at, CancellationToken ct = default);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// «Eliminalo e lascia che torni»: removes the record (files records and highlight links by cascade). Conversions
|
||||||
|
/// without a file left (Pending, Failed, Removed) go with it; a Converted or Superseded one makes it fail with
|
||||||
|
/// <see cref="InvalidOperationException"/> (its file would be forgotten): use <see cref="RemoveWithConversionsAsync"/>.
|
||||||
|
/// </summary>
|
||||||
Task RemoveAsync(long entryId, CancellationToken ct = default);
|
Task RemoveAsync(long entryId, CancellationToken ct = default);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// «Eliminalo e lascia che torni» from «Elimina dalla libreria»: removes the record and every conversion of its files
|
||||||
|
/// in one transaction, and returns the conversions removed (their converted files are the caller's to delete).
|
||||||
|
/// </summary>
|
||||||
|
Task<IReadOnlyList<MediaConversion>> RemoveWithConversionsAsync(long entryId, CancellationToken ct = default);
|
||||||
|
|
||||||
/// <summary>Entries of an account ordered by publication time, newest first (account tabs, collection pipeline).</summary>
|
/// <summary>Entries of an account ordered by publication time, newest first (account tabs, collection pipeline).</summary>
|
||||||
Task<IReadOnlyList<Entry>> ListByAccountAsync(long accountId, EntryListOptions? options = null, CancellationToken ct = default);
|
Task<IReadOnlyList<Entry>> ListByAccountAsync(long accountId, EntryListOptions? options = null, CancellationToken ct = default);
|
||||||
|
|
||||||
|
|||||||
@@ -162,6 +162,12 @@ public interface IExportStore
|
|||||||
|
|
||||||
Task<ExportItem?> GetItemAsync(long itemId, CancellationToken ct = default);
|
Task<ExportItem?> GetItemAsync(long itemId, CancellationToken ct = default);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The first item of a library file in a job with this variant and format, any state; null when none. The frames of
|
||||||
|
/// a video are added together in instant order, so an item's position among them is its id minus this one.
|
||||||
|
/// </summary>
|
||||||
|
Task<long?> FirstItemIdAsync(long runId, long mediaId, ExportVariant variant, ExportFormat format, CancellationToken ct = default);
|
||||||
|
|
||||||
/// <summary>Items of a job, by key, with an optional state.</summary>
|
/// <summary>Items of a job, by key, with an optional state.</summary>
|
||||||
Task<IReadOnlyList<ExportItem>> ListItemsAsync(ExportItemQuery query, CancellationToken ct = default);
|
Task<IReadOnlyList<ExportItem>> ListItemsAsync(ExportItemQuery query, CancellationToken ct = default);
|
||||||
|
|
||||||
@@ -177,22 +183,47 @@ public interface IExportStore
|
|||||||
Task<IReadOnlyDictionary<long, bool>> ListAccountExportSwitchesAsync(CancellationToken ct = default);
|
Task<IReadOnlyDictionary<long, bool>> ListAccountExportSwitchesAsync(CancellationToken ct = default);
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// The newest Superseded or Removed row of (destination, account) whose <see cref="ExportCopy.SupersededBySha256"/> is
|
/// The newest Superseded or Removed row, not a frame, of (destination, account) whose
|
||||||
/// this SHA-256: the library file that took the place of a copied one, never copied again by itself.
|
/// <see cref="ExportCopy.SupersededBySha256"/> is this SHA-256: the library file that took the place of a copied one,
|
||||||
|
/// never copied again by itself (a superseded frame never makes the file «Superato»).
|
||||||
/// </summary>
|
/// </summary>
|
||||||
Task<ExportCopy?> FindReplacedCopyAsync(long destinationId, long accountId, string sha256, CancellationToken ct = default);
|
Task<ExportCopy?> FindReplacedCopyAsync(long destinationId, long accountId, string sha256, CancellationToken ct = default);
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// «Una copia sola»: the newest Copied row of this original, variant and format in a destination in use (the general
|
/// «Una copia sola»: the newest Copied row of this original, in any form but a frame (whole or converted, decision D3
|
||||||
/// folder or the own folder of an account still in Febe), of an account still in Febe; with
|
/// of tappa E3), in a destination in use (the general folder or the own folder of an account still in Febe), of an
|
||||||
/// <paramref name="exceptAccountId"/>, of an account other than that one, so a newer row of the account itself never
|
/// account still in Febe; with <paramref name="exceptAccountId"/>, of an account other than that one, so a newer row
|
||||||
/// hides the copy of another account (decision of 2026-11-27: «una copia altrove conta solo se è di un altro account»).
|
/// of the account itself never hides the copy of another account (decision of 2026-11-27: «una copia altrove conta
|
||||||
|
/// solo se è di un altro account»).
|
||||||
/// </summary>
|
/// </summary>
|
||||||
Task<ExportCopy?> FindCopiedElsewhereAsync(string sha256, ExportVariant variant, ExportFormat format, long? exceptAccountId = null, CancellationToken ct = default);
|
Task<ExportCopy?> FindCopiedElsewhereAsync(string sha256, long? exceptAccountId = null, CancellationToken ct = default);
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// The state of whole copies (<see cref="ExportVariant.Whole"/>, <see cref="ExportFormat.Original"/>) of (account,
|
/// The SHA-256 of every file written converted or as a frame in a destination (any state, any destination): an
|
||||||
/// SHA-256) pairs in one destination, for the plan: the current row (Copied or Failed) first, else the newest row
|
/// import recognises them as copies of library files (tappa E3, Q37). No index on <c>copy_sha256</c>: one read per
|
||||||
|
/// import run, bounded by the converted copies.
|
||||||
|
/// </summary>
|
||||||
|
Task<IReadOnlySet<string>> LoadConvertedCopyShasAsync(CancellationToken ct = default);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The current (Copied or Failed) rows of an original for an account in a destination, in any form but a frame,
|
||||||
|
/// newest first: «già copiato» looks at the file, not at its format (decision D3 of tappa E3).
|
||||||
|
/// </summary>
|
||||||
|
Task<IReadOnlyList<ExportCopy>> ListCurrentCopiesAnyFormAsync(long destinationId, long accountId, string sha256, CancellationToken ct = default);
|
||||||
|
|
||||||
|
/// <summary>The newest row, in any state and any form but a frame, of an original for an account in a destination (D3 of tappa E3).</summary>
|
||||||
|
Task<ExportCopy?> FindLatestCopyAnyFormAsync(long destinationId, long accountId, string sha256, CancellationToken ct = default);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// After a copy of an original succeeded: its other current «Non riuscito» rows in any form but a frame, for the
|
||||||
|
/// account in the destination, are deleted (they have no file; the identity <paramref name="except"/> is kept).
|
||||||
|
/// Returns the rows deleted.
|
||||||
|
/// </summary>
|
||||||
|
Task<int> ClearFailedAsync(long destinationId, long accountId, string sha256, ExportCopyIdentity except, CancellationToken ct = default);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The state of the copies of (account, SHA-256) pairs in one destination, in any form but a frame (decision D3 of
|
||||||
|
/// tappa E3), for the plan: Copied when a current row is Copied, else Failed when one is Failed, else the newest row
|
||||||
/// when Removed or Superseded, else Removed or Superseded when a row was replaced by this SHA-256
|
/// when Removed or Superseded, else Removed or Superseded when a row was replaced by this SHA-256
|
||||||
/// (<see cref="FindReplacedCopyAsync"/>). Pairs without any are absent.
|
/// (<see cref="FindReplacedCopyAsync"/>). Pairs without any are absent.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
@@ -227,7 +258,7 @@ public interface IExportStore
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
Task<IReadOnlyDictionary<long, ExportEntryCopies>> GetEntryCopyCountsAsync(IReadOnlyList<long> entryIds, CancellationToken ct = default);
|
Task<IReadOnlyDictionary<long, ExportEntryCopies>> GetEntryCopyCountsAsync(IReadOnlyList<long> entryIds, CancellationToken ct = default);
|
||||||
|
|
||||||
/// <summary>The mark of single files («Tutte le foto»): Copied or None; files that are not due are absent.</summary>
|
/// <summary>The mark of single files («Tutte le foto»): Copied, FrameOnly or None; files that are not due are absent.</summary>
|
||||||
Task<IReadOnlyDictionary<long, ExportMark>> GetFileMarksAsync(IReadOnlyList<long> mediaIds, CancellationToken ct = default);
|
Task<IReadOnlyDictionary<long, ExportMark>> GetFileMarksAsync(IReadOnlyList<long> mediaIds, CancellationToken ct = default);
|
||||||
|
|
||||||
/// <summary>The counts of the account card: «312 su 1.204 non ancora copiati» (decision D3 of tappa E2).</summary>
|
/// <summary>The counts of the account card: «312 su 1.204 non ancora copiati» (decision D3 of tappa E2).</summary>
|
||||||
@@ -246,7 +277,8 @@ public sealed record ExportCandidate(
|
|||||||
long? Bytes,
|
long? Bytes,
|
||||||
string? RelativePath,
|
string? RelativePath,
|
||||||
int Position,
|
int Position,
|
||||||
bool InHighlight);
|
bool InHighlight,
|
||||||
|
TimeSpan? Duration = null);
|
||||||
|
|
||||||
/// <summary>The copy mark of a tile (spec §4.10): «Non ancora copiato», «Copiato in parte», «Copiato».</summary>
|
/// <summary>The copy mark of a tile (spec §4.10): «Non ancora copiato», «Copiato in parte», «Copiato».</summary>
|
||||||
public enum ExportMark
|
public enum ExportMark
|
||||||
@@ -254,13 +286,21 @@ public enum ExportMark
|
|||||||
None,
|
None,
|
||||||
Partly,
|
Partly,
|
||||||
Copied,
|
Copied,
|
||||||
|
|
||||||
|
/// <summary>«Solo fotogrammi»: no due file is copied, at least one has a frame copied (decision D4 of tappa E3).</summary>
|
||||||
|
FrameOnly,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>The due files of an entry and how many are copied (decision D3 of tappa E2).</summary>
|
/// <summary>
|
||||||
public sealed record ExportEntryCopies(int Due, int Copied)
|
/// The due files of an entry and how many are copied (decision D3 of tappa E2): a frame never makes a file copied; a
|
||||||
|
/// file with only frames copied counts in <paramref name="FrameOnly"/> (decision D4 of tappa E3).
|
||||||
|
/// </summary>
|
||||||
|
public sealed record ExportEntryCopies(int Due, int Copied, int FrameOnly = 0)
|
||||||
{
|
{
|
||||||
/// <summary>«Non ancora copiato» (none), «Copiato in parte», «Copiato».</summary>
|
/// <summary>«Non ancora copiato» (none), «Solo fotogrammi», «Copiato in parte», «Copiato».</summary>
|
||||||
public ExportMark Mark => Copied <= 0 ? ExportMark.None : Copied >= Due ? ExportMark.Copied : ExportMark.Partly;
|
public ExportMark Mark => Copied <= 0
|
||||||
|
? FrameOnly > 0 ? ExportMark.FrameOnly : ExportMark.None
|
||||||
|
: Copied >= Due ? ExportMark.Copied : ExportMark.Partly;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>Counts of the due files of an account (decision D3 of tappa E2).</summary>
|
/// <summary>Counts of the due files of an account (decision D3 of tappa E2).</summary>
|
||||||
|
|||||||
@@ -25,9 +25,134 @@ public interface IMediaConversionStore
|
|||||||
/// <summary>The conversions of one library file, in creation order.</summary>
|
/// <summary>The conversions of one library file, in creation order.</summary>
|
||||||
Task<IReadOnlyList<MediaConversion>> ListByMediaAsync(long mediaId, CancellationToken ct = default);
|
Task<IReadOnlyList<MediaConversion>> ListByMediaAsync(long mediaId, CancellationToken ct = default);
|
||||||
|
|
||||||
|
/// <summary>The conversions of the files of one entry, by file and creation order.</summary>
|
||||||
|
Task<IReadOnlyList<MediaConversion>> ListByEntryAsync(long entryId, CancellationToken ct = default);
|
||||||
|
|
||||||
|
/// <summary>The conversions of these library files, by file and creation order.</summary>
|
||||||
|
Task<IReadOnlyList<MediaConversion>> ListByMediaIdsAsync(IReadOnlyCollection<long> mediaIds, CancellationToken ct = default);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The paths (relative to the account folder) that conversions of the account's files record: Converted,
|
||||||
|
/// Superseded and Removed rows (a rebuild does not count them as unknown files).
|
||||||
|
/// </summary>
|
||||||
|
Task<IReadOnlyList<string>> ListPathsByAccountAsync(long accountId, CancellationToken ct = default);
|
||||||
|
|
||||||
|
/// <summary>The conversions of the account's files that record this path (any state with a path), by key.</summary>
|
||||||
|
Task<IReadOnlyList<MediaConversion>> FindByPathAsync(long accountId, string relativePath, CancellationToken ct = default);
|
||||||
|
|
||||||
/// <summary>Conversions whose converted file has this SHA-256 (a converted file found again is never a duplicate).</summary>
|
/// <summary>Conversions whose converted file has this SHA-256 (a converted file found again is never a duplicate).</summary>
|
||||||
Task<IReadOnlyList<MediaConversion>> FindBySha256Async(string sha256, CancellationToken ct = default);
|
Task<IReadOnlyList<MediaConversion>> FindBySha256Async(string sha256, CancellationToken ct = default);
|
||||||
|
|
||||||
/// <summary>The queue of the conversion, in order, by key.</summary>
|
/// <summary>The queue of the conversion, in order, by key.</summary>
|
||||||
Task<IReadOnlyList<MediaConversion>> ListPendingAsync(long afterId = 0, int limit = 500, CancellationToken ct = default);
|
Task<IReadOnlyList<MediaConversion>> ListPendingAsync(long afterId = 0, int limit = 500, CancellationToken ct = default);
|
||||||
|
|
||||||
|
/// <summary>«Tolto»: these Converted or Superseded rows lost their file with their entry. Returns the rows changed.</summary>
|
||||||
|
Task<int> MarkRemovedAsync(IReadOnlyCollection<long> ids, DateTimeOffset at, CancellationToken ct = default);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// A library file leaves its entry («Tieni il più grande» on a file of a series), in one transaction: the file
|
||||||
|
/// becomes <see cref="MediaState.Deleted"/>, its queue and failures go, its rows with a file become «Tolto». Returns
|
||||||
|
/// those rows as they were (chosen inside the transaction: their files are the caller's to delete). The state of
|
||||||
|
/// the entry is the caller's to recompute.
|
||||||
|
/// </summary>
|
||||||
|
Task<IReadOnlyList<MediaConversion>> ForgetDeletedMediaAsync(long mediaId, DateTimeOffset at, CancellationToken ct = default);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The account's file changed from <paramref name="oldSha256"/> to <paramref name="newSha256"/> (spec §4.10
|
||||||
|
/// «Superato»): the conversions made from the old bytes of the account's files that now have the new ones become
|
||||||
|
/// Superseded (their files stay); Pending and retryable Failed rows take the new SHA-256. Returns the media ids of the
|
||||||
|
/// files concerned (to queue them again).
|
||||||
|
/// </summary>
|
||||||
|
Task<IReadOnlyList<long>> SupersedeAsync(long accountId, string oldSha256, string newSha256, DateTimeOffset at, CancellationToken ct = default);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The setting of a format went off or changed: its queue is emptied, with its failures that «Riprova» would put
|
||||||
|
/// back (Converted rows and their files stay, and so do the <c>AsIs*</c> verdicts). Returns how many rows went.
|
||||||
|
/// </summary>
|
||||||
|
Task<int> DeleteQueueAsync(ExportFormat format, CancellationToken ct = default);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// A change of the library formats: stores <paramref name="settings"/> (null values remove their key) and empties
|
||||||
|
/// the queues of <paramref name="formats"/> as <see cref="DeleteQueueAsync"/> does, in one transaction, so that the
|
||||||
|
/// formats, the keys that go with them and the queues are stored whole or not at all. Returns how many rows went.
|
||||||
|
/// </summary>
|
||||||
|
Task<int> SaveSettingsAndDeleteQueuesAsync(IReadOnlyDictionary<string, string?> settings, IReadOnlyCollection<ExportFormat> formats, CancellationToken ct = default);
|
||||||
|
|
||||||
|
/// <summary>Drops one Pending row (a file already in the format by its bytes: nothing to record). False when it is not Pending.</summary>
|
||||||
|
Task<bool> DeletePendingRowAsync(long id, CancellationToken ct = default);
|
||||||
|
|
||||||
|
/// <summary>How many rows are in each state; Failed rows with an <c>AsIs*</c> code are counted apart.</summary>
|
||||||
|
Task<MediaConversionCounts> CountByStateAsync(CancellationToken ct = default);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Queues these files in these formats (Pending, <c>source_sha256</c> = the given SHA-256). A file that already has a
|
||||||
|
/// current conversion in the format (Pending, Converted, or Failed, which holds the slot) is left as it is. Returns
|
||||||
|
/// how many rows were added.
|
||||||
|
/// </summary>
|
||||||
|
Task<int> EnqueueAsync(IReadOnlyList<MediaConversionRequest> requests, DateTimeOffset at, CancellationToken ct = default);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// «Anche i N già in libreria»: queues, in one statement, every present library file of each kind whose extension
|
||||||
|
/// says it converts into the format given for its kind (null: that kind is not queued). Returns how many were added.
|
||||||
|
/// </summary>
|
||||||
|
Task<int> EnqueueExistingAsync(ExportFormat? photo, ExportFormat? video, DateTimeOffset at, CancellationToken ct = default);
|
||||||
|
|
||||||
|
/// <summary>What <see cref="EnqueueExistingAsync"/> would queue: files and their bytes.</summary>
|
||||||
|
Task<(int Files, long Bytes)> CountExistingAsync(ExportFormat? photo, ExportFormat? video, CancellationToken ct = default);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Records a converted file just written (or adopted) for a Pending row, in one transaction (WP2.2 step 4): the row
|
||||||
|
/// becomes Converted only if it is still Pending with <paramref name="sourceSha256"/> and its library file is still
|
||||||
|
/// present with that SHA-256. Otherwise, with the file still present and unchanged, the current conversion of that
|
||||||
|
/// file and format becomes Converted with this file, or a new row is added; with the file gone or changed nothing is
|
||||||
|
/// recorded.
|
||||||
|
/// </summary>
|
||||||
|
Task<MediaConversionCommitOutcome> CommitAsync(MediaConversionCommit commit, CancellationToken ct = default);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// «Riprova»: Failed rows in <paramref name="formats"/> (the library formats set now) go back to Pending, except those
|
||||||
|
/// with an <c>AsIs*</c> code (they never convert). Returns how many.
|
||||||
|
/// </summary>
|
||||||
|
Task<int> ResetFailedAsync(IReadOnlyCollection<ExportFormat> formats, DateTimeOffset at, CancellationToken ct = default);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>One file to queue in one format, made from these bytes.</summary>
|
||||||
|
public sealed record MediaConversionRequest(long MediaId, ExportFormat Format, string SourceSha256);
|
||||||
|
|
||||||
|
/// <summary>The rows of the conversion for the library, by state.</summary>
|
||||||
|
/// <param name="Pending">In the queue.</param>
|
||||||
|
/// <param name="Converted">Converted files.</param>
|
||||||
|
/// <param name="Failed">Failed, to try again («Riprova»).</param>
|
||||||
|
/// <param name="AsIs">Failed for good: animated, not decodable, CMYK… («non si convertono»).</param>
|
||||||
|
/// <param name="Superseded">Converted from bytes the library no longer has.</param>
|
||||||
|
/// <param name="Removed">Their file went with the entry.</param>
|
||||||
|
public sealed record MediaConversionCounts(int Pending, int Converted, int Failed, int AsIs, int Superseded, int Removed);
|
||||||
|
|
||||||
|
/// <summary>A converted file written for <paramref name="ConversionId"/>.</summary>
|
||||||
|
/// <param name="ConversionId">The Pending row it was written for.</param>
|
||||||
|
/// <param name="MediaId">Its library file.</param>
|
||||||
|
/// <param name="Format">The format.</param>
|
||||||
|
/// <param name="SourceSha256">The SHA-256 of the original it was made from.</param>
|
||||||
|
/// <param name="RelativePath">Path relative to the account folder.</param>
|
||||||
|
/// <param name="Bytes">Its size.</param>
|
||||||
|
/// <param name="Sha256">Its SHA-256.</param>
|
||||||
|
/// <param name="At">When it was converted.</param>
|
||||||
|
/// <param name="Notes">What the conversion could not keep (loss codes, D19), or null.</param>
|
||||||
|
public sealed record MediaConversionCommit(long ConversionId, long MediaId, ExportFormat Format, string SourceSha256,
|
||||||
|
string RelativePath, long Bytes, string Sha256, DateTimeOffset At, string? Notes);
|
||||||
|
|
||||||
|
/// <summary>What <see cref="IMediaConversionStore.CommitAsync"/> did.</summary>
|
||||||
|
public enum MediaConversionCommitOutcome
|
||||||
|
{
|
||||||
|
/// <summary>The Pending row is now Converted.</summary>
|
||||||
|
Recorded,
|
||||||
|
|
||||||
|
/// <summary>The row had changed meanwhile; the file is recorded in the current row of its format, or a new one.</summary>
|
||||||
|
Upserted,
|
||||||
|
|
||||||
|
/// <summary>Nothing recorded: the library file was deleted or changed meanwhile.</summary>
|
||||||
|
SourceGone,
|
||||||
|
|
||||||
|
/// <summary>Nothing recorded: another converted file already holds the format of this library file.</summary>
|
||||||
|
SlotTaken,
|
||||||
}
|
}
|
||||||
@@ -623,7 +623,8 @@ internal sealed class SettingsStore(FebeDatabase db) : ISettingsStore
|
|||||||
},
|
},
|
||||||
ct);
|
ct);
|
||||||
|
|
||||||
private static void Set(WriteContext w, string key, string? value)
|
/// <summary>Stores one value inside a write (null removes the key): also for stores that save settings with their rows.</summary>
|
||||||
|
internal static void Set(WriteContext w, string key, string? value)
|
||||||
{
|
{
|
||||||
if (value is null)
|
if (value is null)
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -148,26 +148,119 @@ internal sealed class EntryStore(FebeDatabase db) : IEntryStore
|
|||||||
public Task<EntryState> RecomputeStateAsync(long entryId, CancellationToken ct = default) =>
|
public Task<EntryState> RecomputeStateAsync(long entryId, CancellationToken ct = default) =>
|
||||||
db.WriteAsync(w => RecomputeState(w, entryId), ct);
|
db.WriteAsync(w => RecomputeState(w, entryId), ct);
|
||||||
|
|
||||||
public Task MarkDeletedAsync(long entryId, DateTimeOffset at, CancellationToken ct = default) =>
|
public Task MarkDeletedAsync(long entryId, DateTimeOffset at, CancellationToken ct = default) => MarkDeletedAsync(entryId, at, [], ct);
|
||||||
db.WriteAsync(
|
|
||||||
|
/// <summary>
|
||||||
|
/// «Eliminato» inside the caller's transaction: the entry, its files without path, and the conversions for the
|
||||||
|
/// library of its files (tappa E3) with nothing left to convert or retry (Pending, Failed) go.
|
||||||
|
/// </summary>
|
||||||
|
private static void MarkDeleted(WriteContext w, long entryId, DateTimeOffset at)
|
||||||
|
{
|
||||||
|
var rows = w.Command("UPDATE entry SET state = 'Deleted', deleted_at = @at WHERE id = @id")
|
||||||
|
.With("@at", Sql.Time(at)).With("@id", entryId).ExecuteNonQuery();
|
||||||
|
if (rows == 0)
|
||||||
|
{
|
||||||
|
throw new KeyNotFoundException($"Elemento {entryId} non trovato.");
|
||||||
|
}
|
||||||
|
|
||||||
|
w.Command("""
|
||||||
|
UPDATE media SET state = 'Deleted', relative_path = NULL, has_thumbnail = 0, phash = NULL, source_url = NULL, cover_url = NULL
|
||||||
|
WHERE entry_id = @id
|
||||||
|
""").With("@id", entryId).ExecuteNonQuery();
|
||||||
|
w.Command("""
|
||||||
|
DELETE FROM media_conversion WHERE state IN ('Pending', 'Failed') AND media_id IN (SELECT id FROM media WHERE entry_id = @id)
|
||||||
|
""").With("@id", entryId).ExecuteNonQuery();
|
||||||
|
}
|
||||||
|
|
||||||
|
public Task MarkDeletedAsync(long entryId, DateTimeOffset at, IReadOnlyCollection<long> removedConversionIds, CancellationToken ct = default)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(removedConversionIds);
|
||||||
|
var removed = removedConversionIds.Distinct().ToList();
|
||||||
|
return db.WriteAsync(
|
||||||
w =>
|
w =>
|
||||||
{
|
{
|
||||||
var rows = w.Command("UPDATE entry SET state = 'Deleted', deleted_at = @at WHERE id = @id")
|
MarkDeleted(w, entryId, at);
|
||||||
.With("@at", Sql.Time(at)).With("@id", entryId).ExecuteNonQuery();
|
|
||||||
if (rows == 0)
|
// The converted files that go (or are gone) are «Tolto», the others stay as they are.
|
||||||
|
if (removed.Count > 0)
|
||||||
{
|
{
|
||||||
throw new KeyNotFoundException($"Elemento {entryId} non trovato.");
|
var own = new HashSet<long>();
|
||||||
|
using (var r = w.Command("SELECT mc.id FROM media_conversion mc JOIN media m ON m.id = mc.media_id WHERE m.entry_id = @id")
|
||||||
|
.With("@id", entryId).ExecuteReader())
|
||||||
|
{
|
||||||
|
while (r.Read())
|
||||||
|
{
|
||||||
|
own.Add(r.GetInt64(0));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
MediaConversionStore.MarkRemoved(w, removed.Where(own.Contains).ToList(), at);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
ct);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Task<IReadOnlyList<MediaConversion>> MarkDeletedWithConversionsAsync(long entryId, DateTimeOffset at, CancellationToken ct = default) =>
|
||||||
|
db.WriteAsync<IReadOnlyList<MediaConversion>>(
|
||||||
|
w =>
|
||||||
|
{
|
||||||
|
var withFiles = new List<MediaConversion>();
|
||||||
|
using (var r = w.Command($"""
|
||||||
|
SELECT {MediaConversionStore.JoinedColumnList} FROM media_conversion mc JOIN media m ON m.id = mc.media_id
|
||||||
|
WHERE m.entry_id = @id AND mc.state IN ('Converted', 'Superseded') ORDER BY mc.media_id, mc.id
|
||||||
|
""").With("@id", entryId).ExecuteReader())
|
||||||
|
{
|
||||||
|
while (r.Read())
|
||||||
|
{
|
||||||
|
withFiles.Add(MediaConversionStore.ReadRow(r));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
w.Command("""
|
MarkDeleted(w, entryId, at);
|
||||||
UPDATE media SET state = 'Deleted', relative_path = NULL, has_thumbnail = 0, phash = NULL, source_url = NULL, cover_url = NULL
|
MediaConversionStore.MarkRemoved(w, withFiles.Select(c => c.Id).ToList(), at);
|
||||||
WHERE entry_id = @id
|
return withFiles;
|
||||||
""").With("@id", entryId).ExecuteNonQuery();
|
|
||||||
},
|
},
|
||||||
ct);
|
ct);
|
||||||
|
|
||||||
public Task RemoveAsync(long entryId, CancellationToken ct = default) =>
|
public Task RemoveAsync(long entryId, CancellationToken ct = default) =>
|
||||||
db.WriteAsync(w => w.Command("DELETE FROM entry WHERE id = @id").With("@id", entryId).ExecuteNonQuery(), ct);
|
db.WriteAsync(
|
||||||
|
w =>
|
||||||
|
{
|
||||||
|
MediaConversionStore.DeleteRowsWithoutFile(w, entryId);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
w.Command("DELETE FROM entry WHERE id = @id").With("@id", entryId).ExecuteNonQuery();
|
||||||
|
}
|
||||||
|
catch (SqliteException ex) when (ex.IsConstraintViolation())
|
||||||
|
{
|
||||||
|
// ON DELETE RESTRICT of media_conversion: a converted file of the library would lose its record.
|
||||||
|
throw new InvalidOperationException(
|
||||||
|
"L'elemento ha file convertiti nella libreria: eliminalo con «Elimina dalla libreria», che toglie anche quelli.", ex);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
ct);
|
||||||
|
|
||||||
|
public Task<IReadOnlyList<MediaConversion>> RemoveWithConversionsAsync(long entryId, CancellationToken ct = default) =>
|
||||||
|
db.WriteAsync<IReadOnlyList<MediaConversion>>(
|
||||||
|
w =>
|
||||||
|
{
|
||||||
|
var list = new List<MediaConversion>();
|
||||||
|
using (var r = w.Command($"""
|
||||||
|
SELECT {MediaConversionStore.JoinedColumnList} FROM media_conversion mc JOIN media m ON m.id = mc.media_id
|
||||||
|
WHERE m.entry_id = @id ORDER BY mc.media_id, mc.id
|
||||||
|
""").With("@id", entryId).ExecuteReader())
|
||||||
|
{
|
||||||
|
while (r.Read())
|
||||||
|
{
|
||||||
|
list.Add(MediaConversionStore.ReadRow(r));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
w.Command("DELETE FROM media_conversion WHERE media_id IN (SELECT id FROM media WHERE entry_id = @id)").With("@id", entryId).ExecuteNonQuery();
|
||||||
|
w.Command("DELETE FROM entry WHERE id = @id").With("@id", entryId).ExecuteNonQuery();
|
||||||
|
return list;
|
||||||
|
},
|
||||||
|
ct);
|
||||||
|
|
||||||
public Task<IReadOnlyList<Entry>> ListByAccountAsync(long accountId, EntryListOptions? options = null, CancellationToken ct = default)
|
public Task<IReadOnlyList<Entry>> ListByAccountAsync(long accountId, EntryListOptions? options = null, CancellationToken ct = default)
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -137,10 +137,21 @@ internal static class ExportFilterSql
|
|||||||
private static string OneOnlyMatch(ExportFilterContext x) =>
|
private static string OneOnlyMatch(ExportFilterContext x) =>
|
||||||
$"((c.destination_id = {DestinationOf(x)} AND c.account_id = e.account_id) OR (c.account_id IS NOT NULL AND c.account_id <> e.account_id))";
|
$"((c.destination_id = {DestinationOf(x)} AND c.account_id = e.account_id) OR (c.account_id IS NOT NULL AND c.account_id <> e.account_id))";
|
||||||
|
|
||||||
/// <summary>The last copy of the file in its effective destination failed («Non riuscito»): «Copia in…» tries again.</summary>
|
/// <summary>
|
||||||
|
/// The last copy of the file in its effective destination failed («Non riuscito»), in any form but a frame: «Copia
|
||||||
|
/// in…» tries again.
|
||||||
|
/// </summary>
|
||||||
public static string Failed(ExportFilterContext x) => !x.HasFailed
|
public static string Failed(ExportFilterContext x) => !x.HasFailed
|
||||||
? "0"
|
? "0"
|
||||||
: $"EXISTS (SELECT 1 FROM export_copy c WHERE c.source_sha256 = m.sha256 AND c.destination_id = {DestinationOf(x)} AND c.account_id = e.account_id AND c.state = 'Failed')";
|
: $"EXISTS (SELECT 1 FROM export_copy c WHERE c.source_sha256 = m.sha256 AND c.destination_id = {DestinationOf(x)} AND c.account_id = e.account_id AND c.state = 'Failed' AND c.variant <> 'Frame')";
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// A frame of the file is copied in its effective destination (decision D4 of tappa E3): it never makes the file
|
||||||
|
/// copied, only the mark «Solo fotogrammi» of a file not copied otherwise. «Una copia sola» does not apply to frames.
|
||||||
|
/// </summary>
|
||||||
|
public static string FrameCopied(ExportFilterContext x) => !x.HasCopies
|
||||||
|
? "0"
|
||||||
|
: $"EXISTS (SELECT 1 FROM export_copy c WHERE c.source_sha256 = m.sha256 AND c.destination_id = {DestinationOf(x)} AND c.account_id = e.account_id AND c.state = 'Copied' AND c.variant = 'Frame')";
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// «Tolto o superato»: not copied, not failed, and its copy in the effective destination was removed, or a copy was
|
/// «Tolto o superato»: not copied, not failed, and its copy in the effective destination was removed, or a copy was
|
||||||
@@ -286,9 +297,9 @@ internal static class ExportFilterSql
|
|||||||
{
|
{
|
||||||
var destination = DestinationOf(x);
|
var destination = DestinationOf(x);
|
||||||
var removed = $"EXISTS (SELECT 1 FROM export_copy c WHERE c.source_sha256 = m.sha256 AND c.destination_id = {destination} AND c.account_id = e.account_id "
|
var removed = $"EXISTS (SELECT 1 FROM export_copy c WHERE c.source_sha256 = m.sha256 AND c.destination_id = {destination} AND c.account_id = e.account_id "
|
||||||
+ "AND c.state IN ('Removed', 'Superseded'))";
|
+ "AND c.state IN ('Removed', 'Superseded') AND c.variant <> 'Frame')";
|
||||||
var superseded = $"EXISTS (SELECT 1 FROM export_copy c WHERE c.superseded_by_sha256 = m.sha256 AND c.destination_id = {destination} AND c.account_id = e.account_id "
|
var superseded = $"EXISTS (SELECT 1 FROM export_copy c WHERE c.superseded_by_sha256 = m.sha256 AND c.destination_id = {destination} AND c.account_id = e.account_id "
|
||||||
+ "AND c.state IN ('Superseded', 'Removed'))";
|
+ "AND c.state IN ('Superseded', 'Removed') AND c.variant <> 'Frame')";
|
||||||
if (!bulk)
|
if (!bulk)
|
||||||
{
|
{
|
||||||
return $"({removed} OR {superseded})";
|
return $"({removed} OR {superseded})";
|
||||||
|
|||||||
@@ -826,6 +826,32 @@ internal sealed class ExportStore(FebeDatabase db) : IExportStore
|
|||||||
public Task<ExportItem?> GetItemAsync(long itemId, CancellationToken ct = default) =>
|
public Task<ExportItem?> GetItemAsync(long itemId, CancellationToken ct = default) =>
|
||||||
db.ReadAsync(c => ReadFirst(c.Command($"SELECT {ItemColumns} FROM export_item WHERE id = @id").With("@id", itemId), ReadItem), ct);
|
db.ReadAsync(c => ReadFirst(c.Command($"SELECT {ItemColumns} FROM export_item WHERE id = @id").With("@id", itemId), ReadItem), ct);
|
||||||
|
|
||||||
|
/// <summary>The first item of a file of a job in a form (ux_export_item_file).</summary>
|
||||||
|
internal const string FirstItemSql = "SELECT min(id) FROM export_item WHERE run_id = @r AND media_id = @m AND variant = @v AND format = @f";
|
||||||
|
|
||||||
|
public Task<IReadOnlySet<string>> LoadConvertedCopyShasAsync(CancellationToken ct = default) =>
|
||||||
|
db.ReadAsync<IReadOnlySet<string>>(
|
||||||
|
c =>
|
||||||
|
{
|
||||||
|
using var command = c.Command("SELECT DISTINCT copy_sha256 FROM export_copy WHERE variant IN ('Converted', 'Frame') AND copy_sha256 IS NOT NULL");
|
||||||
|
using var r = command.ExecuteReader();
|
||||||
|
var set = new HashSet<string>(StringComparer.Ordinal);
|
||||||
|
while (r.Read())
|
||||||
|
{
|
||||||
|
set.Add(r.GetString(0));
|
||||||
|
}
|
||||||
|
|
||||||
|
return set;
|
||||||
|
},
|
||||||
|
ct);
|
||||||
|
|
||||||
|
public Task<long?> FirstItemIdAsync(long runId, long mediaId, ExportVariant variant, ExportFormat format, CancellationToken ct = default) =>
|
||||||
|
db.ReadAsync(
|
||||||
|
c => c.Command(FirstItemSql).With("@r", runId).With("@m", mediaId).With("@v", Sql.Enum(variant)).With("@f", Sql.Enum(format)).ExecuteScalar() is long id
|
||||||
|
? id
|
||||||
|
: (long?)null,
|
||||||
|
ct);
|
||||||
|
|
||||||
public Task<IReadOnlyList<ExportItem>> ListItemsAsync(ExportItemQuery query, CancellationToken ct = default)
|
public Task<IReadOnlyList<ExportItem>> ListItemsAsync(ExportItemQuery query, CancellationToken ct = default)
|
||||||
{
|
{
|
||||||
ArgumentNullException.ThrowIfNull(query);
|
ArgumentNullException.ThrowIfNull(query);
|
||||||
@@ -878,13 +904,37 @@ internal sealed class ExportStore(FebeDatabase db) : IExportStore
|
|||||||
|
|
||||||
internal const string ReplacedCopySql = $"""
|
internal const string ReplacedCopySql = $"""
|
||||||
SELECT {CopyColumns} FROM export_copy
|
SELECT {CopyColumns} FROM export_copy
|
||||||
WHERE superseded_by_sha256 = @h AND destination_id = @d AND account_id = @a AND state IN ('Superseded', 'Removed')
|
WHERE superseded_by_sha256 = @h AND destination_id = @d AND account_id = @a AND state IN ('Superseded', 'Removed') AND variant <> 'Frame'
|
||||||
ORDER BY id DESC LIMIT 1
|
ORDER BY id DESC LIMIT 1
|
||||||
""";
|
""";
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The current rows of an original, any form but a frame (decision D3 of tappa E3; @h, @d, @a). INDEXED BY keeps
|
||||||
|
/// it on ix_export_copy_sha256 (a few rows, sorted): for «ORDER BY id» the planner would read a whole destination.
|
||||||
|
/// </summary>
|
||||||
|
internal const string CurrentCopiesAnyFormSql = $"""
|
||||||
|
SELECT {CopyColumns} FROM export_copy INDEXED BY ix_export_copy_sha256
|
||||||
|
WHERE source_sha256 = @h AND destination_id = @d AND account_id = @a AND variant <> 'Frame' AND state IN ('Copied', 'Failed')
|
||||||
|
ORDER BY id DESC
|
||||||
|
""";
|
||||||
|
|
||||||
|
/// <summary>The newest row of an original, any state and any form but a frame (@h, @d, @a).</summary>
|
||||||
|
internal const string LatestCopyAnyFormSql = $"""
|
||||||
|
SELECT {CopyColumns} FROM export_copy INDEXED BY ix_export_copy_sha256
|
||||||
|
WHERE source_sha256 = @h AND destination_id = @d AND account_id = @a AND variant <> 'Frame'
|
||||||
|
ORDER BY id DESC LIMIT 1
|
||||||
|
""";
|
||||||
|
|
||||||
|
/// <summary>The «Non riuscito» rows of an original that a success leaves stale (@h, @d, @a; the kept identity @v, @f).</summary>
|
||||||
|
internal const string ClearFailedSql = """
|
||||||
|
DELETE FROM export_copy
|
||||||
|
WHERE source_sha256 = @h AND destination_id = @d AND account_id = @a AND variant <> 'Frame' AND state = 'Failed'
|
||||||
|
AND NOT (variant = @v AND format = @f)
|
||||||
|
""";
|
||||||
|
|
||||||
internal const string CopiedElsewhereSql = $"""
|
internal const string CopiedElsewhereSql = $"""
|
||||||
SELECT {CopyColumns} FROM export_copy
|
SELECT {CopyColumns} FROM export_copy
|
||||||
WHERE source_sha256 = @h AND variant = @v AND format = @f AND state = 'Copied' AND account_id IS NOT NULL
|
WHERE source_sha256 = @h AND variant <> 'Frame' AND state = 'Copied' AND account_id IS NOT NULL
|
||||||
AND (@a IS NULL OR account_id <> @a)
|
AND (@a IS NULL OR account_id <> @a)
|
||||||
AND destination_id IN (SELECT id FROM export_destination WHERE removed_at IS NULL AND (scope = 'General' OR account_id IS NOT NULL))
|
AND destination_id IN (SELECT id FROM export_destination WHERE removed_at IS NULL AND (scope = 'General' OR account_id IS NOT NULL))
|
||||||
ORDER BY id DESC LIMIT 1
|
ORDER BY id DESC LIMIT 1
|
||||||
@@ -892,10 +942,13 @@ internal sealed class ExportStore(FebeDatabase db) : IExportStore
|
|||||||
|
|
||||||
internal const string RecentRunsSql = $"SELECT {RunColumns} FROM export_run ORDER BY started_at DESC, id DESC LIMIT @limit";
|
internal const string RecentRunsSql = $"SELECT {RunColumns} FROM export_run ORDER BY started_at DESC, id DESC LIMIT @limit";
|
||||||
|
|
||||||
/// <summary>The whole copies of a destination for some originals (ix_export_copy_sha256); @d and the list of SHA-256.</summary>
|
/// <summary>
|
||||||
|
/// The copies of a destination for some originals, in any form but a frame (ix_export_copy_sha256; decision D3 of
|
||||||
|
/// tappa E3); @d and the list of SHA-256.
|
||||||
|
/// </summary>
|
||||||
internal static string CopyStatesSql(string shaList) => $"""
|
internal static string CopyStatesSql(string shaList) => $"""
|
||||||
SELECT account_id, source_sha256, state, id FROM export_copy
|
SELECT account_id, source_sha256, state, id FROM export_copy
|
||||||
WHERE source_sha256 IN ({shaList}) AND destination_id = @d AND account_id IS NOT NULL AND variant = 'Whole' AND format = 'Original'
|
WHERE source_sha256 IN ({shaList}) AND destination_id = @d AND account_id IS NOT NULL AND variant <> 'Frame'
|
||||||
""";
|
""";
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -906,11 +959,12 @@ internal sealed class ExportStore(FebeDatabase db) : IExportStore
|
|||||||
internal static string ReplacedStatesSql(string shaList) => $"""
|
internal static string ReplacedStatesSql(string shaList) => $"""
|
||||||
SELECT account_id, superseded_by_sha256, state, id FROM export_copy
|
SELECT account_id, superseded_by_sha256, state, id FROM export_copy
|
||||||
WHERE superseded_by_sha256 IN ({shaList}) AND destination_id = @d AND account_id IS NOT NULL AND +state IN ('Superseded', 'Removed')
|
WHERE superseded_by_sha256 IN ({shaList}) AND destination_id = @d AND account_id IS NOT NULL AND +state IN ('Superseded', 'Removed')
|
||||||
|
AND variant <> 'Frame'
|
||||||
""";
|
""";
|
||||||
|
|
||||||
private const string CandidateColumns =
|
private const string CandidateColumns =
|
||||||
"m.id, m.entry_id, e.account_id, e.kind, m.kind, m.state, m.sha256, m.bytes, m.relative_path, m.position, "
|
"m.id, m.entry_id, e.account_id, e.kind, m.kind, m.state, m.sha256, m.bytes, m.relative_path, m.position, "
|
||||||
+ "EXISTS (SELECT 1 FROM highlight_entry he WHERE he.entry_id = e.id)";
|
+ "EXISTS (SELECT 1 FROM highlight_entry he WHERE he.entry_id = e.id), m.duration_ms";
|
||||||
|
|
||||||
private static ExportCandidate ReadCandidate(SqliteDataReader r) => new(
|
private static ExportCandidate ReadCandidate(SqliteDataReader r) => new(
|
||||||
r.GetInt64(0),
|
r.GetInt64(0),
|
||||||
@@ -923,7 +977,8 @@ internal sealed class ExportStore(FebeDatabase db) : IExportStore
|
|||||||
r.GetInt64OrNull(7),
|
r.GetInt64OrNull(7),
|
||||||
r.GetTextOrNull(8),
|
r.GetTextOrNull(8),
|
||||||
r.GetInt32(9),
|
r.GetInt32(9),
|
||||||
r.GetBool(10));
|
r.GetBool(10),
|
||||||
|
r.GetDurationOrNull(11));
|
||||||
|
|
||||||
public Task<IReadOnlyDictionary<long, bool>> ListAccountExportSwitchesAsync(CancellationToken ct = default) =>
|
public Task<IReadOnlyDictionary<long, bool>> ListAccountExportSwitchesAsync(CancellationToken ct = default) =>
|
||||||
db.ReadAsync<IReadOnlyDictionary<long, bool>>(
|
db.ReadAsync<IReadOnlyDictionary<long, bool>>(
|
||||||
@@ -948,16 +1003,44 @@ internal sealed class ExportStore(FebeDatabase db) : IExportStore
|
|||||||
ct);
|
ct);
|
||||||
}
|
}
|
||||||
|
|
||||||
public Task<ExportCopy?> FindCopiedElsewhereAsync(string sha256, ExportVariant variant, ExportFormat format, long? exceptAccountId = null, CancellationToken ct = default)
|
public Task<ExportCopy?> FindCopiedElsewhereAsync(string sha256, long? exceptAccountId = null, CancellationToken ct = default)
|
||||||
{
|
{
|
||||||
var sha = ExportValues.Sha(sha256, nameof(sha256));
|
var sha = ExportValues.Sha(sha256, nameof(sha256));
|
||||||
return db.ReadAsync(
|
return db.ReadAsync(
|
||||||
c => ReadFirst(
|
c => ReadFirst(
|
||||||
c.Command(CopiedElsewhereSql).With("@h", sha).With("@v", Sql.Enum(variant)).With("@f", Sql.Enum(format)).With("@a", Sql.Int(exceptAccountId)),
|
c.Command(CopiedElsewhereSql).With("@h", sha).With("@a", Sql.Int(exceptAccountId)),
|
||||||
ReadCopy),
|
ReadCopy),
|
||||||
ct);
|
ct);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public Task<IReadOnlyList<ExportCopy>> ListCurrentCopiesAnyFormAsync(long destinationId, long accountId, string sha256, CancellationToken ct = default)
|
||||||
|
{
|
||||||
|
var sha = ExportValues.Sha(sha256, nameof(sha256));
|
||||||
|
return db.ReadAsync<IReadOnlyList<ExportCopy>>(
|
||||||
|
c => ReadAll(c.Command(CurrentCopiesAnyFormSql).With("@h", sha).With("@d", destinationId).With("@a", accountId), ReadCopy),
|
||||||
|
ct);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Task<ExportCopy?> FindLatestCopyAnyFormAsync(long destinationId, long accountId, string sha256, CancellationToken ct = default)
|
||||||
|
{
|
||||||
|
var sha = ExportValues.Sha(sha256, nameof(sha256));
|
||||||
|
return db.ReadAsync(
|
||||||
|
c => ReadFirst(c.Command(LatestCopyAnyFormSql).With("@h", sha).With("@d", destinationId).With("@a", accountId), ReadCopy),
|
||||||
|
ct);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Task<int> ClearFailedAsync(long destinationId, long accountId, string sha256, ExportCopyIdentity except, CancellationToken ct = default)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(except);
|
||||||
|
var sha = ExportValues.Sha(sha256, nameof(sha256));
|
||||||
|
return db.WriteAsync(
|
||||||
|
w => w.Command(ClearFailedSql)
|
||||||
|
.With("@h", sha).With("@d", destinationId).With("@a", accountId)
|
||||||
|
.With("@v", Sql.Enum(except.Variant)).With("@f", Sql.Enum(except.Format))
|
||||||
|
.ExecuteNonQuery(),
|
||||||
|
ct);
|
||||||
|
}
|
||||||
|
|
||||||
public Task<IReadOnlyDictionary<(long AccountId, string Sha256), ExportCopyState>> GetCopyStatesAsync(
|
public Task<IReadOnlyDictionary<(long AccountId, string Sha256), ExportCopyState>> GetCopyStatesAsync(
|
||||||
long destinationId,
|
long destinationId,
|
||||||
IReadOnlyCollection<(long AccountId, string Sha256)> keys,
|
IReadOnlyCollection<(long AccountId, string Sha256)> keys,
|
||||||
@@ -968,8 +1051,9 @@ internal sealed class ExportStore(FebeDatabase db) : IExportStore
|
|||||||
return db.ReadAsync<IReadOnlyDictionary<(long AccountId, string Sha256), ExportCopyState>>(
|
return db.ReadAsync<IReadOnlyDictionary<(long AccountId, string Sha256), ExportCopyState>>(
|
||||||
c =>
|
c =>
|
||||||
{
|
{
|
||||||
// Per pair: the current row (Copied or Failed), else the newest row when Removed or Superseded, else a row
|
// Per pair, over every form but a frame (D3 of tappa E3): a Copied row, else a Failed one, else the newest
|
||||||
// replaced by this file. Rows of other accounts that share a SHA-256 are read and dropped here.
|
// row when Removed or Superseded, else a row replaced by this file. Rows of other accounts that share a
|
||||||
|
// SHA-256 are read and dropped here.
|
||||||
var current = new Dictionary<(long, string), ExportCopyState>();
|
var current = new Dictionary<(long, string), ExportCopyState>();
|
||||||
var newest = new Dictionary<(long, string), (long Id, ExportCopyState State)>();
|
var newest = new Dictionary<(long, string), (long Id, ExportCopyState State)>();
|
||||||
var replaced = new Dictionary<(long, string), (long Id, ExportCopyState State)>();
|
var replaced = new Dictionary<(long, string), (long Id, ExportCopyState State)>();
|
||||||
@@ -1000,7 +1084,7 @@ internal sealed class ExportStore(FebeDatabase db) : IExportStore
|
|||||||
{
|
{
|
||||||
Read(CopyStatesSql, chunk, (key, state, id) =>
|
Read(CopyStatesSql, chunk, (key, state, id) =>
|
||||||
{
|
{
|
||||||
if (state is ExportCopyState.Copied or ExportCopyState.Failed)
|
if (state == ExportCopyState.Copied || (state == ExportCopyState.Failed && !current.ContainsKey(key)))
|
||||||
{
|
{
|
||||||
current[key] = state;
|
current[key] = state;
|
||||||
}
|
}
|
||||||
@@ -1134,12 +1218,15 @@ internal sealed class ExportStore(FebeDatabase db) : IExportStore
|
|||||||
return marks;
|
return marks;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var copied = ExportFilterSql.Copied(x);
|
||||||
|
var frames = ExportFilterSql.FrameCopied(x);
|
||||||
foreach (var chunk in entryIds.Distinct().Chunk(IdChunk))
|
foreach (var chunk in entryIds.Distinct().Chunk(IdChunk))
|
||||||
{
|
{
|
||||||
using var command = c.Command(string.Empty);
|
using var command = c.Command(string.Empty);
|
||||||
var list = command.AddList("x", chunk);
|
var list = command.AddList("x", chunk);
|
||||||
command.CommandText = $"""
|
command.CommandText = $"""
|
||||||
SELECT m.entry_id, COUNT(*), SUM(CASE WHEN {ExportFilterSql.Copied(x)} THEN 1 ELSE 0 END)
|
SELECT m.entry_id, COUNT(*), SUM(CASE WHEN {copied} THEN 1 ELSE 0 END),
|
||||||
|
SUM(CASE WHEN NOT {copied} AND {frames} THEN 1 ELSE 0 END)
|
||||||
FROM media m JOIN entry e ON e.id = m.entry_id
|
FROM media m JOIN entry e ON e.id = m.entry_id
|
||||||
WHERE m.entry_id IN ({list}) AND {ExportFilterSql.DueFile(x)}
|
WHERE m.entry_id IN ({list}) AND {ExportFilterSql.DueFile(x)}
|
||||||
GROUP BY m.entry_id
|
GROUP BY m.entry_id
|
||||||
@@ -1147,7 +1234,7 @@ internal sealed class ExportStore(FebeDatabase db) : IExportStore
|
|||||||
using var r = command.ExecuteReader();
|
using var r = command.ExecuteReader();
|
||||||
while (r.Read())
|
while (r.Read())
|
||||||
{
|
{
|
||||||
marks[r.GetInt64(0)] = new ExportEntryCopies(r.GetInt32(1), r.GetInt32(2));
|
marks[r.GetInt64(0)] = new ExportEntryCopies(r.GetInt32(1), r.GetInt32(2), r.GetInt32(3));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1174,13 +1261,13 @@ internal sealed class ExportStore(FebeDatabase db) : IExportStore
|
|||||||
using var command = c.Command(string.Empty);
|
using var command = c.Command(string.Empty);
|
||||||
var list = command.AddList("x", chunk);
|
var list = command.AddList("x", chunk);
|
||||||
command.CommandText = $"""
|
command.CommandText = $"""
|
||||||
SELECT m.id, {ExportFilterSql.Copied(x)} FROM media m JOIN entry e ON e.id = m.entry_id
|
SELECT m.id, {ExportFilterSql.Copied(x)}, {ExportFilterSql.FrameCopied(x)} FROM media m JOIN entry e ON e.id = m.entry_id
|
||||||
WHERE m.id IN ({list}) AND {ExportFilterSql.DueFile(x)}
|
WHERE m.id IN ({list}) AND {ExportFilterSql.DueFile(x)}
|
||||||
""";
|
""";
|
||||||
using var r = command.ExecuteReader();
|
using var r = command.ExecuteReader();
|
||||||
while (r.Read())
|
while (r.Read())
|
||||||
{
|
{
|
||||||
marks[r.GetInt64(0)] = r.GetInt64(1) != 0 ? ExportMark.Copied : ExportMark.None;
|
marks[r.GetInt64(0)] = r.GetInt64(1) != 0 ? ExportMark.Copied : r.GetInt64(2) != 0 ? ExportMark.FrameOnly : ExportMark.None;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,514 @@
|
|||||||
|
using System.Globalization;
|
||||||
|
using System.Text;
|
||||||
|
using Febe.Core.Domain;
|
||||||
|
using Febe.Core.Library.Conversion;
|
||||||
|
using Febe.Core.Storage;
|
||||||
|
using Microsoft.Data.Sqlite;
|
||||||
|
|
||||||
|
namespace Febe.Data.Stores;
|
||||||
|
|
||||||
|
/// <summary>The queue, the commit and the hooks of the conversion for the library (tappa E3, WP2.3).</summary>
|
||||||
|
internal sealed partial class MediaConversionStore
|
||||||
|
{
|
||||||
|
/// <summary>The same columns of the alias <c>mc</c>, for joins.</summary>
|
||||||
|
private const string JoinedColumns =
|
||||||
|
"mc.id, mc.media_id, mc.format, mc.state, mc.source_sha256, mc.relative_path, mc.bytes, mc.sha256, mc.created_at, mc.converted_at, mc.state_changed_at, mc.last_error";
|
||||||
|
|
||||||
|
/// <summary>The columns of the alias <c>mc</c>, for other stores reading rows with <see cref="ReadRow"/>.</summary>
|
||||||
|
internal const string JoinedColumnList = JoinedColumns;
|
||||||
|
|
||||||
|
/// <summary>The present library files of the alias <c>m</c>, as the conversion for the library sees them.</summary>
|
||||||
|
private const string PresentMedia = "m.state IN ('Downloaded', 'Imported') AND m.sha256 IS NOT NULL AND m.relative_path IS NOT NULL";
|
||||||
|
|
||||||
|
/// <summary>A Failed row whose code says it never converts (animated, not decodable, CMYK…): its first code.</summary>
|
||||||
|
internal const string AsIsCondition = "last_error LIKE 'AsIs%'";
|
||||||
|
|
||||||
|
/// <summary>One row read in the order of <see cref="JoinedColumnList"/>.</summary>
|
||||||
|
internal static MediaConversion ReadRow(SqliteDataReader r) => Read(r);
|
||||||
|
|
||||||
|
public Task<IReadOnlyList<MediaConversion>> ListByEntryAsync(long entryId, CancellationToken ct = default) =>
|
||||||
|
db.ReadAsync<IReadOnlyList<MediaConversion>>(
|
||||||
|
c => ReadAll(c.Command($"""
|
||||||
|
SELECT {JoinedColumns} FROM media_conversion mc JOIN media m ON m.id = mc.media_id
|
||||||
|
WHERE m.entry_id = @e ORDER BY mc.media_id, mc.id
|
||||||
|
""").With("@e", entryId)),
|
||||||
|
ct);
|
||||||
|
|
||||||
|
public Task<IReadOnlyList<MediaConversion>> ListByMediaIdsAsync(IReadOnlyCollection<long> mediaIds, CancellationToken ct = default)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(mediaIds);
|
||||||
|
var ids = mediaIds.Distinct().ToList();
|
||||||
|
if (ids.Count == 0)
|
||||||
|
{
|
||||||
|
return Task.FromResult<IReadOnlyList<MediaConversion>>([]);
|
||||||
|
}
|
||||||
|
|
||||||
|
return db.ReadAsync<IReadOnlyList<MediaConversion>>(
|
||||||
|
c =>
|
||||||
|
{
|
||||||
|
var list = new List<MediaConversion>();
|
||||||
|
foreach (var chunk in ids.Chunk(500))
|
||||||
|
{
|
||||||
|
using var command = c.Command(string.Empty);
|
||||||
|
command.CommandText = $"SELECT {Columns} FROM media_conversion WHERE media_id IN ({command.AddList("m", chunk)})";
|
||||||
|
list.AddRange(ReadAll(command));
|
||||||
|
}
|
||||||
|
|
||||||
|
return list.OrderBy(x => x.MediaId).ThenBy(x => x.Id).ToList();
|
||||||
|
},
|
||||||
|
ct);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Task<IReadOnlyList<string>> ListPathsByAccountAsync(long accountId, CancellationToken ct = default) =>
|
||||||
|
db.ReadAsync<IReadOnlyList<string>>(
|
||||||
|
c =>
|
||||||
|
{
|
||||||
|
using var command = c.Command("""
|
||||||
|
SELECT DISTINCT mc.relative_path FROM media_conversion mc
|
||||||
|
JOIN media m ON m.id = mc.media_id JOIN entry e ON e.id = m.entry_id
|
||||||
|
WHERE e.account_id = @a AND mc.relative_path IS NOT NULL AND mc.state IN ('Converted', 'Superseded', 'Removed')
|
||||||
|
""").With("@a", accountId);
|
||||||
|
using var r = command.ExecuteReader();
|
||||||
|
var list = new List<string>();
|
||||||
|
while (r.Read())
|
||||||
|
{
|
||||||
|
list.Add(r.GetString(0));
|
||||||
|
}
|
||||||
|
|
||||||
|
return list;
|
||||||
|
},
|
||||||
|
ct);
|
||||||
|
|
||||||
|
public Task<IReadOnlyList<MediaConversion>> FindByPathAsync(long accountId, string relativePath, CancellationToken ct = default)
|
||||||
|
{
|
||||||
|
ArgumentException.ThrowIfNullOrWhiteSpace(relativePath);
|
||||||
|
return db.ReadAsync<IReadOnlyList<MediaConversion>>(
|
||||||
|
c => ReadAll(c.Command($"""
|
||||||
|
SELECT {JoinedColumns} FROM media_conversion mc
|
||||||
|
JOIN media m ON m.id = mc.media_id JOIN entry e ON e.id = m.entry_id
|
||||||
|
WHERE e.account_id = @a AND mc.relative_path = @p ORDER BY mc.id
|
||||||
|
""").With("@a", accountId).With("@p", relativePath)),
|
||||||
|
ct);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Task<int> MarkRemovedAsync(IReadOnlyCollection<long> ids, DateTimeOffset at, CancellationToken ct = default)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(ids);
|
||||||
|
var list = ids.Distinct().ToList();
|
||||||
|
return list.Count == 0 ? Task.FromResult(0) : db.WriteAsync(w => MarkRemoved(w, list, at), ct);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>«Tolto» for these ids among the Converted and Superseded rows, inside the caller's transaction.</summary>
|
||||||
|
internal static int MarkRemoved(WriteContext w, IReadOnlyCollection<long> ids, DateTimeOffset at)
|
||||||
|
{
|
||||||
|
var changed = 0;
|
||||||
|
foreach (var chunk in ids.Chunk(500))
|
||||||
|
{
|
||||||
|
using var command = w.Connection.Command(string.Empty, w.Transaction);
|
||||||
|
command.CommandText = $"""
|
||||||
|
UPDATE media_conversion SET state = 'Removed', state_changed_at = @at
|
||||||
|
WHERE state IN ('Converted', 'Superseded') AND id IN ({command.AddList("i", chunk)})
|
||||||
|
""";
|
||||||
|
changed += command.With("@at", Sql.Time(at)).ExecuteNonQuery();
|
||||||
|
}
|
||||||
|
|
||||||
|
return changed;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Task<IReadOnlyList<MediaConversion>> ForgetDeletedMediaAsync(long mediaId, DateTimeOffset at, CancellationToken ct = default) =>
|
||||||
|
db.WriteAsync<IReadOnlyList<MediaConversion>>(
|
||||||
|
w =>
|
||||||
|
{
|
||||||
|
w.Command("UPDATE media SET state = 'Deleted' WHERE id = @m").With("@m", mediaId).ExecuteNonQuery();
|
||||||
|
w.Command("DELETE FROM media_conversion WHERE media_id = @m AND state IN ('Pending', 'Failed')").With("@m", mediaId).ExecuteNonQuery();
|
||||||
|
var removed = ReadAll(w.Command($"""
|
||||||
|
SELECT {JoinedColumns} FROM media_conversion mc JOIN media m ON m.id = mc.media_id
|
||||||
|
WHERE mc.media_id = @m AND mc.state IN ('Converted', 'Superseded') ORDER BY mc.id
|
||||||
|
""").With("@m", mediaId));
|
||||||
|
MarkRemoved(w, removed.Select(c => c.Id).ToList(), at);
|
||||||
|
return removed;
|
||||||
|
},
|
||||||
|
ct);
|
||||||
|
|
||||||
|
/// <summary>The rows without a file left (Pending, Failed, Removed) of an entry's files go, inside the caller's transaction.</summary>
|
||||||
|
internal static int DeleteRowsWithoutFile(WriteContext w, long entryId) =>
|
||||||
|
w.Command("""
|
||||||
|
DELETE FROM media_conversion WHERE state IN ('Pending', 'Failed', 'Removed')
|
||||||
|
AND media_id IN (SELECT id FROM media WHERE entry_id = @e)
|
||||||
|
""").With("@e", entryId).ExecuteNonQuery();
|
||||||
|
|
||||||
|
public Task<IReadOnlyList<long>> SupersedeAsync(long accountId, string oldSha256, string newSha256, DateTimeOffset at, CancellationToken ct = default)
|
||||||
|
{
|
||||||
|
var old = ExportValues.Sha(oldSha256, nameof(oldSha256));
|
||||||
|
var now = ExportValues.Sha(newSha256, nameof(newSha256));
|
||||||
|
if (old == now)
|
||||||
|
{
|
||||||
|
return Task.FromResult<IReadOnlyList<long>>([]);
|
||||||
|
}
|
||||||
|
|
||||||
|
return db.WriteAsync<IReadOnlyList<long>>(
|
||||||
|
w =>
|
||||||
|
{
|
||||||
|
var media = new List<long>();
|
||||||
|
using (var find = w.Connection.Command("""
|
||||||
|
SELECT DISTINCT mc.media_id FROM media_conversion mc
|
||||||
|
JOIN media m ON m.id = mc.media_id JOIN entry e ON e.id = m.entry_id
|
||||||
|
WHERE e.account_id = @a AND mc.source_sha256 = @old AND m.sha256 = @new
|
||||||
|
AND mc.state IN ('Pending', 'Converted', 'Failed')
|
||||||
|
ORDER BY mc.media_id
|
||||||
|
""", w.Transaction))
|
||||||
|
{
|
||||||
|
find.With("@a", accountId).With("@old", old).With("@new", now);
|
||||||
|
using var r = find.ExecuteReader();
|
||||||
|
while (r.Read())
|
||||||
|
{
|
||||||
|
media.Add(r.GetInt64(0));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach (var chunk in media.Chunk(500))
|
||||||
|
{
|
||||||
|
using var command = w.Connection.Command(string.Empty, w.Transaction);
|
||||||
|
var list = command.AddList("m", chunk);
|
||||||
|
|
||||||
|
// Converted from the old bytes: history, its file stays. The queue and the failures take the new
|
||||||
|
// bytes (a verdict, «AsIs» included, was about the old ones) and are tried again.
|
||||||
|
command.CommandText = $"""
|
||||||
|
UPDATE media_conversion SET state = 'Superseded', state_changed_at = @at
|
||||||
|
WHERE state = 'Converted' AND source_sha256 = @old AND media_id IN ({list});
|
||||||
|
UPDATE media_conversion SET state = 'Pending', source_sha256 = @new, last_error = NULL, state_changed_at = @at
|
||||||
|
WHERE state IN ('Pending', 'Failed') AND source_sha256 = @old AND media_id IN ({list});
|
||||||
|
""";
|
||||||
|
command.With("@at", Sql.Time(at)).With("@old", old).With("@new", now).ExecuteNonQuery();
|
||||||
|
}
|
||||||
|
|
||||||
|
return media;
|
||||||
|
},
|
||||||
|
ct);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Task<int> DeleteQueueAsync(ExportFormat format, CancellationToken ct = default) =>
|
||||||
|
db.WriteAsync(w => DeleteQueue(w, format), ct);
|
||||||
|
|
||||||
|
public Task<int> SaveSettingsAndDeleteQueuesAsync(IReadOnlyDictionary<string, string?> settings, IReadOnlyCollection<ExportFormat> formats, CancellationToken ct = default)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(settings);
|
||||||
|
ArgumentNullException.ThrowIfNull(formats);
|
||||||
|
foreach (var key in settings.Keys)
|
||||||
|
{
|
||||||
|
ArgumentException.ThrowIfNullOrWhiteSpace(key);
|
||||||
|
}
|
||||||
|
|
||||||
|
return db.WriteAsync(
|
||||||
|
w =>
|
||||||
|
{
|
||||||
|
foreach (var (key, value) in settings)
|
||||||
|
{
|
||||||
|
SettingsStore.Set(w, key, value);
|
||||||
|
}
|
||||||
|
|
||||||
|
var deleted = 0;
|
||||||
|
foreach (var format in formats.Distinct())
|
||||||
|
{
|
||||||
|
deleted += DeleteQueue(w, format);
|
||||||
|
}
|
||||||
|
|
||||||
|
return deleted;
|
||||||
|
},
|
||||||
|
ct);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int DeleteQueue(WriteContext w, ExportFormat format) =>
|
||||||
|
w.Command($"""
|
||||||
|
DELETE FROM media_conversion
|
||||||
|
WHERE format = @f AND (state = 'Pending' OR (state = 'Failed' AND (last_error IS NULL OR NOT ({AsIsCondition}))))
|
||||||
|
""").With("@f", Sql.Enum(format)).ExecuteNonQuery();
|
||||||
|
|
||||||
|
public Task<bool> DeletePendingRowAsync(long id, CancellationToken ct = default) =>
|
||||||
|
db.WriteAsync(
|
||||||
|
w => w.Command("DELETE FROM media_conversion WHERE id = @id AND state = 'Pending'").With("@id", id).ExecuteNonQuery() > 0,
|
||||||
|
ct);
|
||||||
|
|
||||||
|
public Task<MediaConversionCounts> CountByStateAsync(CancellationToken ct = default) =>
|
||||||
|
db.ReadAsync(
|
||||||
|
c =>
|
||||||
|
{
|
||||||
|
using var command = c.Command($"""
|
||||||
|
SELECT state, CASE WHEN state = 'Failed' AND {AsIsCondition} THEN 1 ELSE 0 END, COUNT(*)
|
||||||
|
FROM media_conversion GROUP BY 1, 2
|
||||||
|
""");
|
||||||
|
using var r = command.ExecuteReader();
|
||||||
|
int pending = 0, converted = 0, failed = 0, asIs = 0, superseded = 0, removed = 0;
|
||||||
|
while (r.Read())
|
||||||
|
{
|
||||||
|
var n = (int)r.GetInt64(2);
|
||||||
|
switch (r.GetString(0))
|
||||||
|
{
|
||||||
|
case "Pending":
|
||||||
|
pending += n;
|
||||||
|
break;
|
||||||
|
case "Converted":
|
||||||
|
converted += n;
|
||||||
|
break;
|
||||||
|
case "Failed" when r.GetInt64(1) == 1:
|
||||||
|
asIs += n;
|
||||||
|
break;
|
||||||
|
case "Failed":
|
||||||
|
failed += n;
|
||||||
|
break;
|
||||||
|
case "Superseded":
|
||||||
|
superseded += n;
|
||||||
|
break;
|
||||||
|
case "Removed":
|
||||||
|
removed += n;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return new MediaConversionCounts(pending, converted, failed, asIs, superseded, removed);
|
||||||
|
},
|
||||||
|
ct);
|
||||||
|
|
||||||
|
public Task<int> EnqueueAsync(IReadOnlyList<MediaConversionRequest> requests, DateTimeOffset at, CancellationToken ct = default)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(requests);
|
||||||
|
if (requests.Count == 0)
|
||||||
|
{
|
||||||
|
return Task.FromResult(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
var valid = requests.Select(r =>
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(r);
|
||||||
|
if (r.Format == ExportFormat.Original)
|
||||||
|
{
|
||||||
|
throw new ArgumentException("Un file convertito ha un formato diverso dall'originale.", nameof(requests));
|
||||||
|
}
|
||||||
|
|
||||||
|
return r with { SourceSha256 = ExportValues.Sha(r.SourceSha256, nameof(r.SourceSha256)) };
|
||||||
|
}).ToList();
|
||||||
|
return db.WriteAsync(
|
||||||
|
w =>
|
||||||
|
{
|
||||||
|
var added = 0;
|
||||||
|
foreach (var r in valid)
|
||||||
|
{
|
||||||
|
// A current row (Pending, Converted, or Failed, which holds the slot) is left as it is.
|
||||||
|
added += w.Command("""
|
||||||
|
INSERT INTO media_conversion (media_id, format, state, source_sha256, created_at)
|
||||||
|
SELECT @m, @f, 'Pending', @s, @at WHERE EXISTS (SELECT 1 FROM media WHERE id = @m)
|
||||||
|
ON CONFLICT DO NOTHING
|
||||||
|
""").With("@m", r.MediaId).With("@f", Sql.Enum(r.Format)).With("@s", r.SourceSha256).With("@at", Sql.Time(at)).ExecuteNonQuery();
|
||||||
|
}
|
||||||
|
|
||||||
|
return added;
|
||||||
|
},
|
||||||
|
ct);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The present files of a kind that convert into <paramref name="format"/>, as a condition on the alias <c>m</c>.</summary>
|
||||||
|
private static string ExistingCondition(SqliteCommand command, MediaKind kind, ExportFormat format)
|
||||||
|
{
|
||||||
|
var excluded = LibraryConversionRules.ExcludedExtensions(format);
|
||||||
|
var sql = new StringBuilder($"m.kind = @k AND {PresentMedia}");
|
||||||
|
command.With("@k", Sql.Enum(kind));
|
||||||
|
for (var i = 0; i < excluded.Count; i++)
|
||||||
|
{
|
||||||
|
// LIKE compares ASCII letters without case, as the extension rule does.
|
||||||
|
sql.Append(CultureInfo.InvariantCulture, $" AND m.relative_path NOT LIKE @x{i}");
|
||||||
|
command.With(string.Create(CultureInfo.InvariantCulture, $"@x{i}"), "%" + excluded[i]);
|
||||||
|
}
|
||||||
|
|
||||||
|
return sql.ToString();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static List<(MediaKind Kind, ExportFormat Format)> Kinds(ExportFormat? photo, ExportFormat? video)
|
||||||
|
{
|
||||||
|
var kinds = new List<(MediaKind, ExportFormat)>();
|
||||||
|
if (photo is { } p && p != ExportFormat.Original)
|
||||||
|
{
|
||||||
|
if (!ExportFormats.IsPhotoFormat(p))
|
||||||
|
{
|
||||||
|
throw new ArgumentException("Il formato non è adatto alle foto.", nameof(photo));
|
||||||
|
}
|
||||||
|
|
||||||
|
kinds.Add((MediaKind.Photo, p));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (video is { } v && v != ExportFormat.Original)
|
||||||
|
{
|
||||||
|
if (!ExportFormats.IsVideoFormat(v))
|
||||||
|
{
|
||||||
|
throw new ArgumentException("Il formato non è adatto ai video.", nameof(video));
|
||||||
|
}
|
||||||
|
|
||||||
|
kinds.Add((MediaKind.Video, v));
|
||||||
|
}
|
||||||
|
|
||||||
|
return kinds;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Task<int> EnqueueExistingAsync(ExportFormat? photo, ExportFormat? video, DateTimeOffset at, CancellationToken ct = default)
|
||||||
|
{
|
||||||
|
var kinds = Kinds(photo, video);
|
||||||
|
if (kinds.Count == 0)
|
||||||
|
{
|
||||||
|
return Task.FromResult(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
return db.WriteAsync(
|
||||||
|
w =>
|
||||||
|
{
|
||||||
|
var added = 0;
|
||||||
|
foreach (var (kind, format) in kinds)
|
||||||
|
{
|
||||||
|
using var command = w.Connection.Command(string.Empty, w.Transaction);
|
||||||
|
var where = ExistingCondition(command, kind, format);
|
||||||
|
|
||||||
|
// One statement; a file with a current row in the format (a Failed one included) keeps it.
|
||||||
|
command.CommandText = $"""
|
||||||
|
INSERT INTO media_conversion (media_id, format, state, source_sha256, created_at)
|
||||||
|
SELECT m.id, @f, 'Pending', m.sha256, @at FROM media m WHERE {where} ORDER BY m.id
|
||||||
|
ON CONFLICT DO NOTHING
|
||||||
|
""";
|
||||||
|
added += command.With("@f", Sql.Enum(format)).With("@at", Sql.Time(at)).ExecuteNonQuery();
|
||||||
|
}
|
||||||
|
|
||||||
|
return added;
|
||||||
|
},
|
||||||
|
ct);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Task<(int Files, long Bytes)> CountExistingAsync(ExportFormat? photo, ExportFormat? video, CancellationToken ct = default)
|
||||||
|
{
|
||||||
|
var kinds = Kinds(photo, video);
|
||||||
|
if (kinds.Count == 0)
|
||||||
|
{
|
||||||
|
return Task.FromResult((0, 0L));
|
||||||
|
}
|
||||||
|
|
||||||
|
return db.ReadAsync(
|
||||||
|
c =>
|
||||||
|
{
|
||||||
|
var files = 0;
|
||||||
|
long bytes = 0;
|
||||||
|
foreach (var (kind, format) in kinds)
|
||||||
|
{
|
||||||
|
using var command = c.Command(string.Empty);
|
||||||
|
var where = ExistingCondition(command, kind, format);
|
||||||
|
command.CommandText = $"""
|
||||||
|
SELECT COUNT(*), COALESCE(SUM(m.bytes), 0) FROM media m
|
||||||
|
WHERE {where} AND NOT EXISTS (
|
||||||
|
SELECT 1 FROM media_conversion mc WHERE mc.media_id = m.id AND mc.format = @f AND mc.state IN ('Pending', 'Converted', 'Failed'))
|
||||||
|
""";
|
||||||
|
command.With("@f", Sql.Enum(format));
|
||||||
|
using var r = command.ExecuteReader();
|
||||||
|
if (r.Read())
|
||||||
|
{
|
||||||
|
files += (int)r.GetInt64(0);
|
||||||
|
bytes += r.GetInt64(1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (files, bytes);
|
||||||
|
},
|
||||||
|
ct);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Task<MediaConversionCommitOutcome> CommitAsync(MediaConversionCommit commit, CancellationToken ct = default)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(commit);
|
||||||
|
ArgumentException.ThrowIfNullOrWhiteSpace(commit.RelativePath);
|
||||||
|
ArgumentOutOfRangeException.ThrowIfNegative(commit.Bytes);
|
||||||
|
if (commit.Format == ExportFormat.Original)
|
||||||
|
{
|
||||||
|
throw new ArgumentException("Un file convertito ha un formato diverso dall'originale.", nameof(commit));
|
||||||
|
}
|
||||||
|
|
||||||
|
var source = ExportValues.Sha(commit.SourceSha256, nameof(commit.SourceSha256));
|
||||||
|
var sha = ExportValues.Sha(commit.Sha256, nameof(commit.Sha256));
|
||||||
|
return db.WriteAsync(w => Commit(w, commit, source, sha), ct);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static MediaConversionCommitOutcome Commit(WriteContext w, MediaConversionCommit commit, string source, string sha)
|
||||||
|
{
|
||||||
|
SqliteCommand Bind(SqliteCommand c) =>
|
||||||
|
c.With("@m", commit.MediaId).With("@f", Sql.Enum(commit.Format)).With("@s", source).With("@p", commit.RelativePath)
|
||||||
|
.With("@b", commit.Bytes).With("@h", sha).With("@at", Sql.Time(commit.At)).With("@e", Sql.Text(commit.Notes));
|
||||||
|
|
||||||
|
var recorded = Bind(w.Command($"""
|
||||||
|
UPDATE media_conversion SET state = 'Converted', relative_path = @p, bytes = @b, sha256 = @h, converted_at = @at,
|
||||||
|
state_changed_at = @at, last_error = @e
|
||||||
|
WHERE id = @id AND media_id = @m AND format = @f AND state = 'Pending' AND source_sha256 = @s
|
||||||
|
AND EXISTS (SELECT 1 FROM media m WHERE m.id = @m AND m.sha256 = @s AND {PresentMedia})
|
||||||
|
""")).With("@id", commit.ConversionId).ExecuteNonQuery();
|
||||||
|
if (recorded == 1)
|
||||||
|
{
|
||||||
|
return MediaConversionCommitOutcome.Recorded;
|
||||||
|
}
|
||||||
|
|
||||||
|
var present = w.Command($"SELECT COUNT(*) FROM media m WHERE m.id = @m AND m.sha256 = @s AND {PresentMedia}")
|
||||||
|
.With("@m", commit.MediaId).With("@s", source).ScalarInt64() > 0;
|
||||||
|
if (!present)
|
||||||
|
{
|
||||||
|
return MediaConversionCommitOutcome.SourceGone;
|
||||||
|
}
|
||||||
|
|
||||||
|
long? currentId = null;
|
||||||
|
string? currentState = null;
|
||||||
|
using (var r = w.Command("SELECT id, state FROM media_conversion WHERE media_id = @m AND format = @f AND state IN ('Pending', 'Converted', 'Failed')")
|
||||||
|
.With("@m", commit.MediaId).With("@f", Sql.Enum(commit.Format)).ExecuteReader())
|
||||||
|
{
|
||||||
|
if (r.Read())
|
||||||
|
{
|
||||||
|
currentId = r.GetInt64(0);
|
||||||
|
currentState = r.GetString(1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (currentState == "Converted")
|
||||||
|
{
|
||||||
|
return MediaConversionCommitOutcome.SlotTaken;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (currentId is { } id)
|
||||||
|
{
|
||||||
|
Bind(w.Command("""
|
||||||
|
UPDATE media_conversion SET state = 'Converted', source_sha256 = @s, relative_path = @p, bytes = @b, sha256 = @h,
|
||||||
|
converted_at = @at, state_changed_at = @at, last_error = @e
|
||||||
|
WHERE id = @id AND media_id = @m AND format = @f
|
||||||
|
""")).With("@id", id).ExecuteNonQuery();
|
||||||
|
return MediaConversionCommitOutcome.Upserted;
|
||||||
|
}
|
||||||
|
|
||||||
|
// The row went (the setting was turned off meanwhile): the file just written stays recorded.
|
||||||
|
Bind(w.Command("""
|
||||||
|
INSERT INTO media_conversion (media_id, format, state, source_sha256, relative_path, bytes, sha256, created_at, converted_at,
|
||||||
|
state_changed_at, last_error)
|
||||||
|
VALUES (@m, @f, 'Converted', @s, @p, @b, @h, @at, @at, @at, @e)
|
||||||
|
""")).ExecuteNonQuery();
|
||||||
|
return MediaConversionCommitOutcome.Upserted;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Task<int> ResetFailedAsync(IReadOnlyCollection<ExportFormat> formats, DateTimeOffset at, CancellationToken ct = default)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(formats);
|
||||||
|
if (formats.Count == 0)
|
||||||
|
{
|
||||||
|
return Task.FromResult(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
return db.WriteAsync(
|
||||||
|
w =>
|
||||||
|
{
|
||||||
|
using var command = w.Connection.Command(string.Empty, w.Transaction);
|
||||||
|
var list = command.AddList("f", formats.Distinct().Select(f => Sql.Enum(f)).ToList());
|
||||||
|
command.CommandText = $"""
|
||||||
|
UPDATE media_conversion SET state = 'Pending', last_error = NULL, state_changed_at = @at
|
||||||
|
WHERE state = 'Failed' AND format IN ({list}) AND (last_error IS NULL OR NOT ({AsIsCondition}))
|
||||||
|
""";
|
||||||
|
return command.With("@at", Sql.Time(at)).ExecuteNonQuery();
|
||||||
|
},
|
||||||
|
ct);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -4,7 +4,7 @@ using Microsoft.Data.Sqlite;
|
|||||||
|
|
||||||
namespace Febe.Data.Stores;
|
namespace Febe.Data.Stores;
|
||||||
|
|
||||||
internal sealed class MediaConversionStore(FebeDatabase db) : IMediaConversionStore
|
internal sealed partial class MediaConversionStore(FebeDatabase db) : IMediaConversionStore
|
||||||
{
|
{
|
||||||
private const string Columns =
|
private const string Columns =
|
||||||
"id, media_id, format, state, source_sha256, relative_path, bytes, sha256, created_at, converted_at, state_changed_at, last_error";
|
"id, media_id, format, state, source_sha256, relative_path, bytes, sha256, created_at, converted_at, state_changed_at, last_error";
|
||||||
|
|||||||
@@ -422,6 +422,7 @@ public static class AccountsApi
|
|||||||
|
|
||||||
var deleted = 0;
|
var deleted = 0;
|
||||||
var problems = 0;
|
var problems = 0;
|
||||||
|
var converted = 0;
|
||||||
var deletion = library.Deletion;
|
var deletion = library.Deletion;
|
||||||
while (true)
|
while (true)
|
||||||
{
|
{
|
||||||
@@ -436,13 +437,15 @@ public static class AccountsApi
|
|||||||
var result = await deletion.DeleteAsync(entry.Id, DeletionMode.AllowReturn, ct).ConfigureAwait(false);
|
var result = await deletion.DeleteAsync(entry.Id, DeletionMode.AllowReturn, ct).ConfigureAwait(false);
|
||||||
deleted += result.Found ? 1 : 0;
|
deleted += result.Found ? 1 : 0;
|
||||||
problems += result.FailedFiles.Count;
|
problems += result.FailedFiles.Count;
|
||||||
|
converted += result.ConvertedFiles;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
await storage.Accounts.DeleteAsync(id, ct).ConfigureAwait(false);
|
await storage.Accounts.DeleteAsync(id, ct).ConfigureAwait(false);
|
||||||
var message = $"{handle} rimosso con {ItalianText.Count(deleted, "elemento", "elementi")}."
|
var message = $"{handle} rimosso con {ItalianText.Count(deleted, "elemento", "elementi")}"
|
||||||
|
+ (converted > 0 ? $" e {ItalianText.Count(converted, "file convertito", "file convertiti")}." : ".")
|
||||||
+ (problems > 0 ? $" {ItalianText.Count(problems, "file non si è potuto cancellare", "file non si sono potuti cancellare")}: restano nella sua cartella." : string.Empty);
|
+ (problems > 0 ? $" {ItalianText.Count(problems, "file non si è potuto cancellare", "file non si sono potuti cancellare")}: restano nella sua cartella." : string.Empty);
|
||||||
return new RemoveAccountDto("removed", deleted, problems, message);
|
return new RemoveAccountDto("removed", deleted, problems, message, converted);
|
||||||
}
|
}
|
||||||
|
|
||||||
// ------------------------------------------------------------------------------------------ following and adding
|
// ------------------------------------------------------------------------------------------ following and adding
|
||||||
|
|||||||
@@ -39,6 +39,7 @@ public sealed class ApiErrorMiddleware(RequestDelegate next, ILogger<ApiErrorMid
|
|||||||
JsonException => (StatusCodes.Status400BadRequest, "Richiesta non leggibile."),
|
JsonException => (StatusCodes.Status400BadRequest, "Richiesta non leggibile."),
|
||||||
BadHttpRequestException => (StatusCodes.Status400BadRequest, "Richiesta non leggibile."),
|
BadHttpRequestException => (StatusCodes.Status400BadRequest, "Richiesta non leggibile."),
|
||||||
NotFoundException => (StatusCodes.Status404NotFound, ex.Message),
|
NotFoundException => (StatusCodes.Status404NotFound, ex.Message),
|
||||||
|
ApiStatusException a => (a.Status, ex.Message),
|
||||||
DuplicateRecordException => (StatusCodes.Status409Conflict, ex.Message),
|
DuplicateRecordException => (StatusCodes.Status409Conflict, ex.Message),
|
||||||
_ => (StatusCodes.Status500InternalServerError, "Errore interno: Febe non ha completato l'operazione. Riprova; se succede ancora, guarda il registro."),
|
_ => (StatusCodes.Status500InternalServerError, "Errore interno: Febe non ha completato l'operazione. Riprova; se succede ancora, guarda il registro."),
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -298,3 +298,30 @@ public sealed class NotFoundException : Exception
|
|||||||
{
|
{
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>An answer with another status and an Italian message: 409 (busy, in session), 503 (too slow).</summary>
|
||||||
|
public sealed class ApiStatusException : Exception
|
||||||
|
{
|
||||||
|
public ApiStatusException()
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
public ApiStatusException(string message)
|
||||||
|
: base(message)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
public ApiStatusException(string message, Exception innerException)
|
||||||
|
: base(message, innerException)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
public ApiStatusException(int status, string message)
|
||||||
|
: base(message)
|
||||||
|
{
|
||||||
|
Status = status;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The HTTP status (409 when not given).</summary>
|
||||||
|
public int Status { get; } = 409;
|
||||||
|
}
|
||||||
@@ -92,7 +92,9 @@ public sealed record MediaDto(
|
|||||||
bool Available,
|
bool Available,
|
||||||
string State,
|
string State,
|
||||||
bool Damaged = false,
|
bool Damaged = false,
|
||||||
IReadOnlyList<MediaCopyDto>? Copies = null);
|
IReadOnlyList<MediaCopyDto>? Copies = null,
|
||||||
|
bool? FramesAvailable = null,
|
||||||
|
IReadOnlyList<MediaConversionDto>? Conversions = null);
|
||||||
|
|
||||||
/// <summary>Everything the viewer shows of an entry.</summary>
|
/// <summary>Everything the viewer shows of an entry.</summary>
|
||||||
public sealed record EntryDto(
|
public sealed record EntryDto(
|
||||||
@@ -117,7 +119,8 @@ public sealed record EntryDto(
|
|||||||
|
|
||||||
public sealed record EntryIdsRequest(IReadOnlyList<long> Ids, string? Mode);
|
public sealed record EntryIdsRequest(IReadOnlyList<long> Ids, string? Mode);
|
||||||
|
|
||||||
public sealed record DeleteResultDto(int Deleted, int FilesRemoved, IReadOnlyList<string> Problems, string Message);
|
/// <summary>What «Elimina dalla libreria» did; <paramref name="ConvertedFiles"/>: converted files of the library deleted too (tappa E3).</summary>
|
||||||
|
public sealed record DeleteResultDto(int Deleted, int FilesRemoved, IReadOnlyList<string> Problems, string Message, int ConvertedFiles = 0);
|
||||||
|
|
||||||
/// <summary>Export by keys, or by the current filter when no keys are given.</summary>
|
/// <summary>Export by keys, or by the current filter when no keys are given.</summary>
|
||||||
public sealed record ExportRequest(IReadOnlyList<long>? Ids, string? Query);
|
public sealed record ExportRequest(IReadOnlyList<long>? Ids, string? Query);
|
||||||
@@ -222,7 +225,7 @@ public sealed record CheckNowDto(string Status, string Message, string? Token);
|
|||||||
|
|
||||||
public sealed record RemoveAccountRequest(bool DeleteFiles);
|
public sealed record RemoveAccountRequest(bool DeleteFiles);
|
||||||
|
|
||||||
public sealed record RemoveAccountDto(string Outcome, int DeletedEntries, int Problems, string Message);
|
public sealed record RemoveAccountDto(string Outcome, int DeletedEntries, int Problems, string Message, int ConvertedFiles = 0);
|
||||||
|
|
||||||
public sealed record ParseRequest(string Text);
|
public sealed record ParseRequest(string Text);
|
||||||
|
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ using Febe.Core.Abstractions;
|
|||||||
using Febe.Core.Domain;
|
using Febe.Core.Domain;
|
||||||
using Febe.Core.Export;
|
using Febe.Core.Export;
|
||||||
using Febe.Core.Library;
|
using Febe.Core.Library;
|
||||||
|
using Febe.Core.Library.Conversion;
|
||||||
using Febe.Core.Storage;
|
using Febe.Core.Storage;
|
||||||
using Febe.Web.Export;
|
using Febe.Web.Export;
|
||||||
using Febe.Web.Library;
|
using Febe.Web.Library;
|
||||||
@@ -10,6 +11,7 @@ using Microsoft.AspNetCore.Builder;
|
|||||||
using Microsoft.AspNetCore.Http;
|
using Microsoft.AspNetCore.Http;
|
||||||
using Microsoft.AspNetCore.Routing;
|
using Microsoft.AspNetCore.Routing;
|
||||||
using Microsoft.AspNetCore.WebUtilities;
|
using Microsoft.AspNetCore.WebUtilities;
|
||||||
|
using ItalianText = Febe.Core.Engine.ItalianText;
|
||||||
|
|
||||||
namespace Febe.Web.Api;
|
namespace Febe.Web.Api;
|
||||||
|
|
||||||
@@ -30,57 +32,72 @@ public static class ExportApi
|
|||||||
|
|
||||||
private static readonly TimeSpan DiskTimeout = TimeSpan.FromSeconds(10);
|
private static readonly TimeSpan DiskTimeout = TimeSpan.FromSeconds(10);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// One change of the export settings at a time: each saves all its keys from what it loaded, and the queue of the
|
||||||
|
/// library conversion compares before and after, so two quick changes must not both start from the same before.
|
||||||
|
/// </summary>
|
||||||
|
private static readonly SemaphoreSlim SettingsGate = new(1, 1);
|
||||||
|
|
||||||
public static void Map(IEndpointRouteBuilder endpoints)
|
public static void Map(IEndpointRouteBuilder endpoints)
|
||||||
{
|
{
|
||||||
ArgumentNullException.ThrowIfNull(endpoints);
|
ArgumentNullException.ThrowIfNull(endpoints);
|
||||||
|
|
||||||
endpoints.MapGet("/api/export", async (HttpContext context, ExportHub hub, IFebeStorage storage, FebeLibrary library, IClock clock, IServiceProvider services, CancellationToken ct) =>
|
endpoints.MapGet("/api/export", async (HttpContext context, ExportHub hub, IFebeStorage storage, FebeLibrary library, IClock clock, IServiceProvider services, CancellationToken ct) =>
|
||||||
{
|
ApiHttp.Json(await OverviewAsync(context, hub, storage, library, clock, services, ct).ConfigureAwait(false), FebeJsonContext.Default.ExportOverviewDto));
|
||||||
var service = await hub.GetAsync(ct).ConfigureAwait(false);
|
|
||||||
var root = hub.RootFor(context);
|
|
||||||
var d = SettingsApi.Deps.From(services);
|
|
||||||
var caps = SystemApi.Capabilities(context, d.Options, d.Shell, d.Browser, clock);
|
|
||||||
var state = ExportRoots.Evaluate(root);
|
|
||||||
var destinations = await storage.Exports.ListDestinationsAsync(includeRetired: false, ct).ConfigureAwait(false);
|
|
||||||
var names = await UsernamesAsync(storage, ct).ConfigureAwait(false);
|
|
||||||
var mapped = new List<ExportDestinationDto>(destinations.Count);
|
|
||||||
foreach (var destination in destinations)
|
|
||||||
{
|
|
||||||
var counts = await storage.Exports.CountCopiesAsync(destination.Id, ct).ConfigureAwait(false);
|
|
||||||
mapped.Add(Destination(destination, names, counts, root, clock));
|
|
||||||
}
|
|
||||||
|
|
||||||
var settings = await ExportSettings.LoadAsync(storage.Settings, ct).ConfigureAwait(false);
|
endpoints.MapPut("/api/export/settings", async (HttpContext context, ExportHub hub, IFebeStorage storage, FebeLibrary library, LibraryConversionQueue queue, LibraryChanges changes, IClock clock, IServiceProvider services, CancellationToken ct) =>
|
||||||
var active = service.ActiveRunIds;
|
|
||||||
var unfinished = (await storage.Exports.ListUnfinishedRunsAsync(ct).ConfigureAwait(false)).Count(r => !active.Contains(r.Id));
|
|
||||||
var naming = (await LibrarySettings.LoadAsync(storage.Settings, library.Layout.Root, ct).ConfigureAwait(false)).Naming;
|
|
||||||
return ApiHttp.Json(
|
|
||||||
new ExportOverviewDto(
|
|
||||||
new ExportRootDto(root.Root is not null, state.Active, root.Root is { } r ? ExportRoots.DisplayPath(root, r) : null, state.Problem, root.Root is null && caps.PickFolder),
|
|
||||||
SamePost(settings.SamePost),
|
|
||||||
mapped.FirstOrDefault(x => x.Scope == "general"),
|
|
||||||
[.. mapped.Where(x => x.Scope == "account").OrderBy(x => x.Username ?? x.FormerUsername, StringComparer.OrdinalIgnoreCase)],
|
|
||||||
active,
|
|
||||||
unfinished,
|
|
||||||
new ExportSchemesDto(naming.General.Text, naming.Highlight.Text, naming.ProfilePicture.Text, NamingScheme.Placeholders)),
|
|
||||||
FebeJsonContext.Default.ExportOverviewDto);
|
|
||||||
});
|
|
||||||
|
|
||||||
endpoints.MapPut("/api/export/settings", async (HttpContext context, IFebeStorage storage, LibraryChanges changes, IClock clock, CancellationToken ct) =>
|
|
||||||
{
|
{
|
||||||
var body = await ApiHttp.BodyAsync(context, FebeJsonContext.Default.ExportSettingsRequest).ConfigureAwait(false);
|
var body = await ApiHttp.BodyAsync(context, FebeJsonContext.Default.ExportSettingsRequest).ConfigureAwait(false);
|
||||||
var samePost = body.SamePost?.Trim().ToLowerInvariant() switch
|
var (before, after, queued) = await SaveSettingsAsync(body, storage, queue, ct).ConfigureAwait(false);
|
||||||
{
|
|
||||||
"oneperaccount" => SamePostCopies.OnePerAccount,
|
|
||||||
"oneonly" => SamePostCopies.OneOnly,
|
|
||||||
_ => throw new BadRequestException("Scelta sconosciuta: «Una copia per account» o «Una copia sola»."),
|
|
||||||
};
|
|
||||||
var settings = await ExportSettings.LoadAsync(storage.Settings, ct).ConfigureAwait(false);
|
|
||||||
await (settings with { SamePost = samePost }).SaveAsync(storage.Settings, ct).ConfigureAwait(false);
|
|
||||||
changes.Publish(new LibraryChange(clock.Now, null, "export"));
|
changes.Publish(new LibraryChange(clock.Now, null, "export"));
|
||||||
return ApiHttp.Message(samePost == SamePostCopies.OneOnly
|
var overview = await OverviewAsync(context, hub, storage, library, clock, services, ct).ConfigureAwait(false);
|
||||||
? "Fatto: lo stesso post in due account si copia una volta sola."
|
return ApiHttp.Json(new ExportSettingsSavedDto(SettingsMessage(before, after, body, queued), overview, queued), FebeJsonContext.Default.ExportSettingsSavedDto);
|
||||||
: "Fatto: lo stesso post in due account si copia una volta per ciascun account.");
|
});
|
||||||
|
|
||||||
|
endpoints.MapGet("/api/export/library-conversion", async (IFebeStorage storage, LibraryConversionWorker worker, CancellationToken ct) =>
|
||||||
|
ApiHttp.Json(await ConversionAsync(storage, worker, ct).ConfigureAwait(false), FebeJsonContext.Default.LibraryConversionDto));
|
||||||
|
|
||||||
|
endpoints.MapGet("/api/export/library-conversion/preview", async (string? photo, string? video, IFebeStorage storage, LibraryConversionQueue queue, CancellationToken ct) =>
|
||||||
|
{
|
||||||
|
var settings = await ExportSettings.LoadAsync(storage.Settings, ct).ConfigureAwait(false);
|
||||||
|
settings = settings with
|
||||||
|
{
|
||||||
|
LibraryPhotoFormat = ParseFormat(photo, MediaKind.Photo) ?? settings.LibraryPhotoFormat,
|
||||||
|
LibraryVideoFormat = ParseFormat(video, MediaKind.Video) ?? settings.LibraryVideoFormat,
|
||||||
|
};
|
||||||
|
|
||||||
|
// The question is about the kind being turned on or changed: the other one is not counted (it already had
|
||||||
|
// its answer). Without either, both formats set now.
|
||||||
|
var (photoAsked, videoAsked) = (!string.IsNullOrWhiteSpace(photo), !string.IsNullOrWhiteSpace(video));
|
||||||
|
var both = !photoAsked && !videoAsked;
|
||||||
|
var preview = settings.ConvertsLibrary
|
||||||
|
? await queue.PreviewExistingAsync(
|
||||||
|
both || photoAsked ? LibraryConversionRules.FormatFor(MediaKind.Photo, settings) : null,
|
||||||
|
both || videoAsked ? LibraryConversionRules.FormatFor(MediaKind.Video, settings) : null,
|
||||||
|
ct).ConfigureAwait(false)
|
||||||
|
: new LibraryConversionPreview(0, 0);
|
||||||
|
return ApiHttp.Json(new LibraryConversionPreviewDto(preview.Files, preview.Bytes, PreviewText(preview)), FebeJsonContext.Default.LibraryConversionPreviewDto);
|
||||||
|
});
|
||||||
|
|
||||||
|
endpoints.MapPost("/api/export/library-conversion/retry", async (LibraryConversionQueue queue, LibraryChanges changes, IClock clock, CancellationToken ct) =>
|
||||||
|
{
|
||||||
|
var reset = await queue.RetryFailedAsync(ct).ConfigureAwait(false);
|
||||||
|
changes.Publish(new LibraryChange(clock.Now, null, "export"));
|
||||||
|
return ApiHttp.Message(reset == 0
|
||||||
|
? "Nessuna conversione da riprovare."
|
||||||
|
: $"{Core.Engine.ItalianText.Count(reset, "file torna", "file tornano")} in coda per la conversione.");
|
||||||
|
});
|
||||||
|
|
||||||
|
endpoints.MapPost("/api/export/library-conversion/pause", async (LibraryConversionQueue queue, CancellationToken ct) =>
|
||||||
|
{
|
||||||
|
await queue.SetPausedAsync(true, ct).ConfigureAwait(false);
|
||||||
|
return ApiHttp.Message("Conversione della libreria interrotta: i file già convertiti restano, riprendi quando vuoi.");
|
||||||
|
});
|
||||||
|
|
||||||
|
endpoints.MapPost("/api/export/library-conversion/resume", async (LibraryConversionQueue queue, CancellationToken ct) =>
|
||||||
|
{
|
||||||
|
await queue.SetPausedAsync(false, ct).ConfigureAwait(false);
|
||||||
|
return ApiHttp.Message("La conversione della libreria riprende.");
|
||||||
});
|
});
|
||||||
|
|
||||||
endpoints.MapGet("/api/export/folders", async (string? path, HttpContext context, ExportHub hub, CancellationToken ct) =>
|
endpoints.MapGet("/api/export/folders", async (string? path, HttpContext context, ExportHub hub, CancellationToken ct) =>
|
||||||
@@ -228,7 +245,7 @@ public static class ExportApi
|
|||||||
var request = Request(body, clock);
|
var request = Request(body, clock);
|
||||||
var service = await hub.GetAsync(ct).ConfigureAwait(false);
|
var service = await hub.GetAsync(ct).ConfigureAwait(false);
|
||||||
var plan = await GuardAsync(() => service.PlanAsync(request, ct)).ConfigureAwait(false);
|
var plan = await GuardAsync(() => service.PlanAsync(request, ct)).ConfigureAwait(false);
|
||||||
return ApiHttp.Json(Plan(plan, hub.RootFor(context)), FebeJsonContext.Default.ExportPlanDto);
|
return ApiHttp.Json(Plan(plan, hub.RootFor(context), request.Frames is not null), FebeJsonContext.Default.ExportPlanDto);
|
||||||
});
|
});
|
||||||
|
|
||||||
endpoints.MapPost("/api/export/start", async (HttpContext context, ExportHub hub, IClock clock, CancellationToken ct) =>
|
endpoints.MapPost("/api/export/start", async (HttpContext context, ExportHub hub, IClock clock, CancellationToken ct) =>
|
||||||
@@ -237,7 +254,7 @@ public static class ExportApi
|
|||||||
var request = Request(body, clock);
|
var request = Request(body, clock);
|
||||||
var service = await hub.GetAsync(ct).ConfigureAwait(false);
|
var service = await hub.GetAsync(ct).ConfigureAwait(false);
|
||||||
var start = await GuardAsync(() => service.StartAsync(request, ct)).ConfigureAwait(false);
|
var start = await GuardAsync(() => service.StartAsync(request, ct)).ConfigureAwait(false);
|
||||||
return ApiHttp.Json(Job(start, hub.RootFor(context)), FebeJsonContext.Default.ExportJobDto);
|
return ApiHttp.Json(Job(start, hub.RootFor(context), request.Frames is not null), FebeJsonContext.Default.ExportJobDto);
|
||||||
});
|
});
|
||||||
|
|
||||||
endpoints.MapPost("/api/export/copy-again", async (HttpContext context, ExportHub hub, IFebeStorage storage, IMediaFileResolver files, CancellationToken ct) =>
|
endpoints.MapPost("/api/export/copy-again", async (HttpContext context, ExportHub hub, IFebeStorage storage, IMediaFileResolver files, CancellationToken ct) =>
|
||||||
@@ -275,18 +292,25 @@ public static class ExportApi
|
|||||||
throw new BadRequestException("Il file non è più in libreria: non c'è niente da copiare di nuovo.");
|
throw new BadRequestException("Il file non è più in libreria: non c'è niente da copiare di nuovo.");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// The same form only (tappa E3, D11): a JPG copy taken again is not «già copiato» because of a whole one.
|
||||||
if ((await storage.Exports.ListCopiesBySha256Async(sha, ct).ConfigureAwait(false)).Any(c =>
|
if ((await storage.Exports.ListCopiesBySha256Async(sha, ct).ConfigureAwait(false)).Any(c =>
|
||||||
c.State == ExportCopyState.Copied && c.SourceSha256 == sha && c.AccountId == accountId && c.DestinationId == copy.DestinationId && c.Variant == copy.Variant))
|
c.State == ExportCopyState.Copied && c.SourceSha256 == sha && c.AccountId == accountId && c.DestinationId == copy.DestinationId && SameForm(c, copy)))
|
||||||
{
|
{
|
||||||
throw new BadRequestException("Il file è già stato copiato di nuovo in questa cartella.");
|
throw new BadRequestException("Il file è già stato copiato di nuovo in questa cartella.");
|
||||||
}
|
}
|
||||||
|
|
||||||
// Among the files of the account with that content, one that is on the disk: the same SHA-256 can sit in two
|
// Among the files of the account with that content, one that is on the disk: the same SHA-256 can sit in two
|
||||||
// entries, and the first one found may be a file the library lost (it would end «non presente in libreria»).
|
// entries, and the first one found may be a file the library lost (it would end «non presente in libreria»).
|
||||||
|
// The file the copy was made from comes first, then one of the same kind.
|
||||||
var account = await storage.Accounts.GetAsync(accountId, ct).ConfigureAwait(false);
|
var account = await storage.Accounts.GetAsync(accountId, ct).ConfigureAwait(false);
|
||||||
var location = present.FirstOrDefault(l => account is not null && files.Resolve(account, l.Media) is not null) ?? present[0];
|
var kind = copy.MediaId is { } copiedId ? (await storage.Media.GetAsync(copiedId, ct).ConfigureAwait(false))?.Kind : null;
|
||||||
|
var location = present
|
||||||
|
.Where(l => account is not null && files.Resolve(account, l.Media) is not null)
|
||||||
|
.OrderBy(l => l.Media.Id == copy.MediaId ? 0 : l.Media.Kind == kind ? 1 : 2)
|
||||||
|
.FirstOrDefault() ?? present[0];
|
||||||
var service = await hub.GetAsync(ct).ConfigureAwait(false);
|
var service = await hub.GetAsync(ct).ConfigureAwait(false);
|
||||||
var start = await GuardAsync(() => service.StartAsync(new ExportJobRequest(new ExportSelection.Media([location.Media.Id]), CopyAgain: true), ct)).ConfigureAwait(false);
|
var exact = new ExportCopyRequest(copy.Variant, copy.Format, copy.FrameAt);
|
||||||
|
var start = await GuardAsync(() => service.StartAsync(new ExportJobRequest(new ExportSelection.Media([location.Media.Id]), CopyAgain: true, Exact: exact), ct)).ConfigureAwait(false);
|
||||||
return ApiHttp.Json(Job(start, hub.RootFor(context)), FebeJsonContext.Default.ExportJobDto);
|
return ApiHttp.Json(Job(start, hub.RootFor(context)), FebeJsonContext.Default.ExportJobDto);
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -382,8 +406,9 @@ public static class ExportApi
|
|||||||
Run(report.Run, summary, labels, clock, service.ActiveRunIds.Contains(id)),
|
Run(report.Run, summary, labels, clock, service.ActiveRunIds.Contains(id)),
|
||||||
ItemCounts(report.ByState),
|
ItemCounts(report.ByState),
|
||||||
report.BytesCopied,
|
report.BytesCopied,
|
||||||
[.. report.Accounts.Select(a => new ExportReportAccountDto(a.AccountId, a.Username, a.Copied, a.AlreadyCopied, a.Skipped, a.Failed))],
|
[.. report.Accounts.Select(a => new ExportReportAccountDto(a.AccountId, a.Username, a.Copied, a.AlreadyCopied, a.Skipped, a.Failed, a.AsIs))],
|
||||||
[.. report.Problems.Select(p => new ExportReportLineDto(p.ItemId, p.Username, p.RelativePath, ItemState(p.State), p.Text))]),
|
[.. report.Problems.Select(p => new ExportReportLineDto(p.ItemId, p.Username, p.RelativePath, ItemState(p.State), p.Text))],
|
||||||
|
[.. report.Notes.Select(p => new ExportReportLineDto(p.ItemId, p.Username, p.RelativePath, ItemState(p.State), p.Text))]),
|
||||||
FebeJsonContext.Default.ExportReportDto);
|
FebeJsonContext.Default.ExportReportDto);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -498,7 +523,9 @@ public static class ExportApi
|
|||||||
reachable,
|
reachable,
|
||||||
freeBytes,
|
freeBytes,
|
||||||
destination.IsOrphan,
|
destination.IsOrphan,
|
||||||
destination.RemovedAccountUsername);
|
destination.RemovedAccountUsername,
|
||||||
|
destination.PhotoFormat is { } photo ? FormatName(photo) : null,
|
||||||
|
destination.VideoFormat is { } video ? FormatName(video) : null);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>A destination with its counts, read from the database.</summary>
|
/// <summary>A destination with its counts, read from the database.</summary>
|
||||||
@@ -536,7 +563,7 @@ public static class ExportApi
|
|||||||
counts.Failed);
|
counts.Failed);
|
||||||
}
|
}
|
||||||
|
|
||||||
public static ExportPlanDto Plan(ExportPlan plan, ExportRootOptions root)
|
public static ExportPlanDto Plan(ExportPlan plan, ExportRootOptions root, bool frames = false)
|
||||||
{
|
{
|
||||||
ArgumentNullException.ThrowIfNull(plan);
|
ArgumentNullException.ThrowIfNull(plan);
|
||||||
return new ExportPlanDto(
|
return new ExportPlanDto(
|
||||||
@@ -547,7 +574,344 @@ public static class ExportApi
|
|||||||
plan.NotExported,
|
plan.NotExported,
|
||||||
plan.Missing,
|
plan.Missing,
|
||||||
[.. plan.Destinations.Select(d => new ExportPlanDestinationDto(d.DestinationId, d.Label, Display(root, d.RootPath), Scope(d.Scope), d.Username, d.Files, d.Bytes, d.Paused, d.Problem, d.FreeBytes))],
|
[.. plan.Destinations.Select(d => new ExportPlanDestinationDto(d.DestinationId, d.Label, Display(root, d.RootPath), Scope(d.Scope), d.Username, d.Files, d.Bytes, d.Paused, d.Problem, d.FreeBytes))],
|
||||||
plan.HasDestination);
|
plan.HasDestination,
|
||||||
|
[.. plan.AsIs.Select(a => new ExportPlanAsIsDto(a.Label, a.Files))],
|
||||||
|
plan.Converted,
|
||||||
|
plan.Lossy,
|
||||||
|
plan.Videos,
|
||||||
|
plan.PhotosSkipped,
|
||||||
|
plan.Frames,
|
||||||
|
plan.OverCap,
|
||||||
|
PlanSummary(plan, frames));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The line of «Copia in…» (tappa E3, §10.3): «312 file · 41 già copiati, saltati · circa 3 HEIC copiati come sono ·
|
||||||
|
/// circa 4,2 GB · con perdita»; for frames «12 fotogrammi da 4 video · le 3 foto si saltano».
|
||||||
|
/// </summary>
|
||||||
|
public static string PlanSummary(ExportPlan plan, bool frames)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(plan);
|
||||||
|
var parts = new List<string>();
|
||||||
|
if (frames)
|
||||||
|
{
|
||||||
|
parts.Add($"{ItalianText.Count(plan.Frames, "fotogramma", "fotogrammi")} da {ItalianText.Number(plan.Videos)} video");
|
||||||
|
if (plan.PhotosSkipped > 0)
|
||||||
|
{
|
||||||
|
parts.Add(PhotosSkippedText(plan.PhotosSkipped));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (plan.OverCap > 0)
|
||||||
|
{
|
||||||
|
parts.Add(ExportFrames.OverCapMessage);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
parts.Add(ItalianText.Count(plan.Files, "file", "file"));
|
||||||
|
if (plan.AlreadyCopied > 0)
|
||||||
|
{
|
||||||
|
parts.Add(plan.AlreadyCopied == 1 ? "1 già copiato, saltato" : $"{ItalianText.Number(plan.AlreadyCopied)} già copiati, saltati");
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach (var asIs in plan.AsIs.Where(a => a.Files > 0))
|
||||||
|
{
|
||||||
|
parts.Add($"circa {ItalianText.Number(asIs.Files)} {asIs.Label} {(asIs.Files == 1 ? "copiato com'è" : "copiati come sono")}");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (plan.Bytes > 0)
|
||||||
|
{
|
||||||
|
parts.Add("circa " + ItalianText.Bytes(plan.Bytes));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (plan.Lossy)
|
||||||
|
{
|
||||||
|
parts.Add("con perdita");
|
||||||
|
}
|
||||||
|
|
||||||
|
return string.Join(" · ", parts);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>«Le 4 foto si saltano» (frames are taken from videos only).</summary>
|
||||||
|
public static string PhotosSkippedText(int photos) =>
|
||||||
|
photos == 1 ? "la foto si salta" : $"le {ItalianText.Number(photos)} foto si saltano";
|
||||||
|
|
||||||
|
/// <summary>The wire name of a format (D21): <c>original</c>, <c>jpg</c>, <c>png</c>, <c>webplossless</c>, <c>mp4</c>.</summary>
|
||||||
|
public static string FormatName(ExportFormat format) => format.ToString().ToLowerInvariant();
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// PUT /api/export/settings under <see cref="SettingsGate"/>: loads the settings, applies the request, saves them
|
||||||
|
/// and tells the queue of the library conversion, all before the next change starts.
|
||||||
|
/// </summary>
|
||||||
|
private static async Task<(ExportSettings Before, ExportSettings After, int Queued)> SaveSettingsAsync(
|
||||||
|
ExportSettingsRequest body, IFebeStorage storage, LibraryConversionQueue queue, CancellationToken ct)
|
||||||
|
{
|
||||||
|
await SettingsGate.WaitAsync(ct).ConfigureAwait(false);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
return await SaveSettingsCoreAsync(body, storage, queue, ct).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
SettingsGate.Release();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static async Task<(ExportSettings Before, ExportSettings After, int Queued)> SaveSettingsCoreAsync(
|
||||||
|
ExportSettingsRequest body, IFebeStorage storage, LibraryConversionQueue queue, CancellationToken ct)
|
||||||
|
{
|
||||||
|
var queued = 0;
|
||||||
|
var before = await ExportSettings.LoadAsync(storage.Settings, ct).ConfigureAwait(false);
|
||||||
|
var after = before;
|
||||||
|
if (body.SamePost is { } samePostText)
|
||||||
|
{
|
||||||
|
after = after with
|
||||||
|
{
|
||||||
|
SamePost = samePostText.Trim().ToLowerInvariant() switch
|
||||||
|
{
|
||||||
|
"oneperaccount" => SamePostCopies.OnePerAccount,
|
||||||
|
"oneonly" => SamePostCopies.OneOnly,
|
||||||
|
_ => throw new BadRequestException("Scelta sconosciuta: «Una copia per account» o «Una copia sola»."),
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
after = after with
|
||||||
|
{
|
||||||
|
PhotoFormat = ParseFormat(body.PhotoFormat, MediaKind.Photo) ?? after.PhotoFormat,
|
||||||
|
VideoFormat = ParseFormat(body.VideoFormat, MediaKind.Video) ?? after.VideoFormat,
|
||||||
|
LibraryPhotoFormat = ParseFormat(body.LibraryPhotoFormat, MediaKind.Photo) ?? after.LibraryPhotoFormat,
|
||||||
|
LibraryVideoFormat = ParseFormat(body.LibraryVideoFormat, MediaKind.Video) ?? after.LibraryVideoFormat,
|
||||||
|
};
|
||||||
|
if (body.SamePost is null && body.PhotoFormat is null && body.VideoFormat is null && body.LibraryPhotoFormat is null && body.LibraryVideoFormat is null && body.ConvertExisting is null)
|
||||||
|
{
|
||||||
|
throw new BadRequestException("Niente da salvare: scegli un'impostazione.");
|
||||||
|
}
|
||||||
|
|
||||||
|
// The formats, their «dal» keys and the queue of a format replaced in one transaction; once it is stored, what
|
||||||
|
// follows no longer depends on the request (a closed tab must not leave half of it).
|
||||||
|
await queue.SaveSettingsAsync(before, after, ct).ConfigureAwait(false);
|
||||||
|
if (body.ConvertExisting == true)
|
||||||
|
{
|
||||||
|
// «Anche i N già in libreria» answers the question about the kind being changed: the other kind keeps
|
||||||
|
// what was answered for it («Solo i nuovi» included, Q29).
|
||||||
|
var photo = Changed(MediaKind.Photo, body.LibraryPhotoFormat, before, after);
|
||||||
|
var video = Changed(MediaKind.Video, body.LibraryVideoFormat, before, after);
|
||||||
|
if (photo is not null || video is not null)
|
||||||
|
{
|
||||||
|
queued = await queue.EnqueueExistingAsync(photo, video, CancellationToken.None).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (before, after, queued);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The library format of <paramref name="kind"/> when this request set it and it changed (the kind the question
|
||||||
|
/// «Convertire anche i N file già in libreria?» was asked about); null otherwise, or when it is «Originale».
|
||||||
|
/// </summary>
|
||||||
|
private static ExportFormat? Changed(MediaKind kind, string? requested, ExportSettings before, ExportSettings after)
|
||||||
|
{
|
||||||
|
var now = LibraryConversionRules.FormatFor(kind, after);
|
||||||
|
return requested is not null && now != LibraryConversionRules.FormatFor(kind, before) ? now : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// A format of <paramref name="kind"/> from its wire name; null for null or empty (nothing chosen). 400 for a name
|
||||||
|
/// that is not a format of that kind.
|
||||||
|
/// </summary>
|
||||||
|
public static ExportFormat? ParseFormat(string? text, MediaKind kind)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(text))
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
var name = text.Trim();
|
||||||
|
var format = Enum.GetValues<ExportFormat>().FirstOrDefault(f => string.Equals(FormatName(f), name, StringComparison.OrdinalIgnoreCase), (ExportFormat)(-1));
|
||||||
|
var fits = kind == MediaKind.Photo ? ExportFormats.IsPhotoFormat(format) : ExportFormats.IsVideoFormat(format);
|
||||||
|
if (!Enum.IsDefined(format) || !fits)
|
||||||
|
{
|
||||||
|
throw new BadRequestException(kind == MediaKind.Photo
|
||||||
|
? "Per le foto si sceglie Originale, JPG, PNG o WEBP senza perdita."
|
||||||
|
: "Per i video si sceglie Originale o MP4.");
|
||||||
|
}
|
||||||
|
|
||||||
|
return format;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>A frame format from its wire name: JPG, PNG or WEBP senza perdita; PNG when none is given (§16, domanda 35).</summary>
|
||||||
|
public static ExportFormat ParseFrameFormat(string? text)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(text))
|
||||||
|
{
|
||||||
|
return ExportFormat.Png;
|
||||||
|
}
|
||||||
|
|
||||||
|
var format = ParseFormat(text, MediaKind.Photo);
|
||||||
|
return format is ExportFormat.Jpg or ExportFormat.Png or ExportFormat.WebpLossless
|
||||||
|
? format.Value
|
||||||
|
: throw new BadRequestException("I fotogrammi si salvano in JPG, PNG o WEBP senza perdita.");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Which frames, from the page's request.</summary>
|
||||||
|
public static ExportFramesRequest Frames(FramesRequestDto body)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(body);
|
||||||
|
var mode = body.Mode?.Trim().ToLowerInvariant() switch
|
||||||
|
{
|
||||||
|
"istante" or "at" => FrameMode.At,
|
||||||
|
"ogni" or "every" => FrameMode.Every,
|
||||||
|
"numero" or "count" => FrameMode.Count,
|
||||||
|
_ => throw new BadRequestException("Modo dei fotogrammi sconosciuto: «Questo istante», «Uno ogni k secondi» o «N in tutto»."),
|
||||||
|
};
|
||||||
|
return new ExportFramesRequest(
|
||||||
|
mode,
|
||||||
|
mode == FrameMode.At ? TimeSpan.FromMilliseconds(Math.Max(0, body.AtMs ?? 0)) : null,
|
||||||
|
mode == FrameMode.Every && body.EveryMs is { } every ? TimeSpan.FromMilliseconds(every) : null,
|
||||||
|
mode == FrameMode.Count ? body.Count : null,
|
||||||
|
ParseFrameFormat(body.Format));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Two copy rows of the same form: variant, format and frame instant (the full identity of §4.10 without the file).</summary>
|
||||||
|
public static bool SameForm(ExportCopy a, ExportCopy b)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(a);
|
||||||
|
ArgumentNullException.ThrowIfNull(b);
|
||||||
|
return a.Variant == b.Variant && a.Format == b.Format && a.FrameAt == b.FrameAt;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The wire name of a state of a conversion of the library; a failure that never converts is <c>asIs</c>.</summary>
|
||||||
|
public static string ConversionState(MediaConversion conversion)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(conversion);
|
||||||
|
return conversion.State switch
|
||||||
|
{
|
||||||
|
MediaConversionState.Pending => "pending",
|
||||||
|
MediaConversionState.Converted => "converted",
|
||||||
|
MediaConversionState.Failed when LibraryConversionText.IsAsIs(conversion.LastError) => "asIs",
|
||||||
|
MediaConversionState.Failed => "failed",
|
||||||
|
MediaConversionState.Superseded => "superseded",
|
||||||
|
_ => "removed",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The state of the conversion of the library, for the settings and the Dashboard.</summary>
|
||||||
|
public static async Task<LibraryConversionDto> ConversionAsync(IFebeStorage storage, LibraryConversionWorker worker, CancellationToken ct)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(storage);
|
||||||
|
ArgumentNullException.ThrowIfNull(worker);
|
||||||
|
var status = await worker.StatusAsync(ct).ConfigureAwait(false);
|
||||||
|
var settings = await ExportSettings.LoadAsync(storage.Settings, ct).ConfigureAwait(false);
|
||||||
|
var parts = new List<string>();
|
||||||
|
if (status.Pending > 0)
|
||||||
|
{
|
||||||
|
parts.Add("In coda " + ItalianText.Number(status.Pending));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (status.Converted > 0)
|
||||||
|
{
|
||||||
|
parts.Add("convertiti " + ItalianText.Number(status.Converted));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (status.Failed > 0)
|
||||||
|
{
|
||||||
|
parts.Add("non riusciti " + ItalianText.Number(status.Failed));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (status.AsIs > 0)
|
||||||
|
{
|
||||||
|
parts.Add("non si convertono " + ItalianText.Number(status.AsIs));
|
||||||
|
}
|
||||||
|
|
||||||
|
var text = parts.Count == 0 ? "Nessun file convertito" : ItalianText.Capitalize(string.Join(" · ", parts));
|
||||||
|
if (status.Paused)
|
||||||
|
{
|
||||||
|
text = "In pausa · " + text;
|
||||||
|
}
|
||||||
|
|
||||||
|
return new LibraryConversionDto(status.Pending, status.Converted, status.Failed, status.AsIs, status.Paused, status.Waiting, text, settings.ConvertsLibrary);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string PreviewText(LibraryConversionPreview preview) => preview.Files switch
|
||||||
|
{
|
||||||
|
0 => "Nessun file già in libreria da convertire.",
|
||||||
|
1 => $"Anche quello già in libreria: l'originale occupa circa {ItalianText.Bytes(preview.Bytes)}; il convertito può occupare di più.",
|
||||||
|
var n => $"Anche i {ItalianText.Number(n)} già in libreria: gli originali occupano circa {ItalianText.Bytes(preview.Bytes)}; i convertiti possono occupare di più.",
|
||||||
|
};
|
||||||
|
|
||||||
|
private static string SettingsMessage(ExportSettings before, ExportSettings after, ExportSettingsRequest body, int queued)
|
||||||
|
{
|
||||||
|
var parts = new List<string>();
|
||||||
|
if (body.SamePost is not null && body.PhotoFormat is null && body.VideoFormat is null && body.LibraryPhotoFormat is null && body.LibraryVideoFormat is null)
|
||||||
|
{
|
||||||
|
return after.SamePost == SamePostCopies.OneOnly
|
||||||
|
? "Fatto: lo stesso post in due account si copia una volta sola."
|
||||||
|
: "Fatto: lo stesso post in due account si copia una volta per ciascun account.";
|
||||||
|
}
|
||||||
|
|
||||||
|
if (before.PhotoFormat != after.PhotoFormat || before.VideoFormat != after.VideoFormat)
|
||||||
|
{
|
||||||
|
parts.Add("i nuovi formati valgono per i file non ancora copiati");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (before.ConvertsLibrary != after.ConvertsLibrary || before.LibraryPhotoFormat != after.LibraryPhotoFormat || before.LibraryVideoFormat != after.LibraryVideoFormat)
|
||||||
|
{
|
||||||
|
parts.Add(!after.ConvertsLibrary
|
||||||
|
? "la conversione della libreria è spenta, i file convertiti restano dove sono"
|
||||||
|
: queued > 0
|
||||||
|
? $"si convertono i nuovi file e {ItalianText.Count(queued, "file già in libreria", "file già in libreria")}"
|
||||||
|
: "si convertono i nuovi file; l'originale resta");
|
||||||
|
}
|
||||||
|
else if (queued > 0)
|
||||||
|
{
|
||||||
|
parts.Add($"{ItalianText.Count(queued, "file già in libreria entra", "file già in libreria entrano")} in coda");
|
||||||
|
}
|
||||||
|
|
||||||
|
return parts.Count == 0 ? "Fatto." : "Fatto: " + string.Join("; ", parts) + ".";
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Impostazioni → Esportazione: root, destinations, settings, formats and the conversion of the library.</summary>
|
||||||
|
public static async Task<ExportOverviewDto> OverviewAsync(HttpContext context, ExportHub hub, IFebeStorage storage, FebeLibrary library, IClock clock, IServiceProvider services, CancellationToken ct)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(hub);
|
||||||
|
ArgumentNullException.ThrowIfNull(storage);
|
||||||
|
ArgumentNullException.ThrowIfNull(library);
|
||||||
|
ArgumentNullException.ThrowIfNull(clock);
|
||||||
|
ArgumentNullException.ThrowIfNull(services);
|
||||||
|
var service = await hub.GetAsync(ct).ConfigureAwait(false);
|
||||||
|
var root = hub.RootFor(context);
|
||||||
|
var d = SettingsApi.Deps.From(services);
|
||||||
|
var caps = SystemApi.Capabilities(context, d.Options, d.Shell, d.Browser, clock);
|
||||||
|
var state = ExportRoots.Evaluate(root);
|
||||||
|
var destinations = await storage.Exports.ListDestinationsAsync(includeRetired: false, ct).ConfigureAwait(false);
|
||||||
|
var names = await UsernamesAsync(storage, ct).ConfigureAwait(false);
|
||||||
|
var mapped = new List<ExportDestinationDto>(destinations.Count);
|
||||||
|
foreach (var destination in destinations)
|
||||||
|
{
|
||||||
|
var counts = await storage.Exports.CountCopiesAsync(destination.Id, ct).ConfigureAwait(false);
|
||||||
|
mapped.Add(Destination(destination, names, counts, root, clock));
|
||||||
|
}
|
||||||
|
|
||||||
|
var settings = await ExportSettings.LoadAsync(storage.Settings, ct).ConfigureAwait(false);
|
||||||
|
var active = service.ActiveRunIds;
|
||||||
|
var unfinished = (await storage.Exports.ListUnfinishedRunsAsync(ct).ConfigureAwait(false)).Count(r => !active.Contains(r.Id));
|
||||||
|
var naming = (await LibrarySettings.LoadAsync(storage.Settings, library.Layout.Root, ct).ConfigureAwait(false)).Naming;
|
||||||
|
var worker = services.GetService(typeof(LibraryConversionWorker)) as LibraryConversionWorker;
|
||||||
|
return new ExportOverviewDto(
|
||||||
|
new ExportRootDto(root.Root is not null, state.Active, root.Root is { } r ? ExportRoots.DisplayPath(root, r) : null, state.Problem, root.Root is null && caps.PickFolder),
|
||||||
|
SamePost(settings.SamePost),
|
||||||
|
mapped.FirstOrDefault(x => x.Scope == "general"),
|
||||||
|
[.. mapped.Where(x => x.Scope == "account").OrderBy(x => x.Username ?? x.FormerUsername, StringComparer.OrdinalIgnoreCase)],
|
||||||
|
active,
|
||||||
|
unfinished,
|
||||||
|
new ExportSchemesDto(naming.General.Text, naming.Highlight.Text, naming.ProfilePicture.Text, NamingScheme.Placeholders),
|
||||||
|
FormatName(settings.PhotoFormat),
|
||||||
|
FormatName(settings.VideoFormat),
|
||||||
|
FormatName(settings.LibraryPhotoFormat),
|
||||||
|
FormatName(settings.LibraryVideoFormat),
|
||||||
|
worker is null ? null : await ConversionAsync(storage, worker, ct).ConfigureAwait(false));
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>The request of a «Copia in…»: exactly one selection.</summary>
|
/// <summary>The request of a «Copia in…»: exactly one selection.</summary>
|
||||||
@@ -581,7 +945,16 @@ public static class ExportApi
|
|||||||
selection = new ExportSelection.Account(body.AccountId!.Value);
|
selection = new ExportSelection.Account(body.AccountId!.Value);
|
||||||
}
|
}
|
||||||
|
|
||||||
return new ExportJobRequest(selection, body.CopyAgain);
|
var photo = ParseFormat(body.PhotoFormat, MediaKind.Photo);
|
||||||
|
var video = ParseFormat(body.VideoFormat, MediaKind.Video);
|
||||||
|
var formats = photo is null && video is null ? null : new ExportFormatChoice(photo, video);
|
||||||
|
var frames = body.Frames is { } f ? Frames(f) : null;
|
||||||
|
if (frames is not null && formats is not null)
|
||||||
|
{
|
||||||
|
throw new BadRequestException("I fotogrammi non si chiedono insieme ai formati delle copie.");
|
||||||
|
}
|
||||||
|
|
||||||
|
return new ExportJobRequest(selection, body.CopyAgain, Formats: formats, Frames: frames);
|
||||||
}
|
}
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------------------------- helpers
|
// ---------------------------------------------------------------------------------------------- helpers
|
||||||
@@ -630,7 +1003,13 @@ public static class ExportApi
|
|||||||
Clean(body.HighlightNamingScheme),
|
Clean(body.HighlightNamingScheme),
|
||||||
Clean(body.ProfileNamingScheme),
|
Clean(body.ProfileNamingScheme),
|
||||||
body.Automatic,
|
body.Automatic,
|
||||||
body.OnlyNew);
|
body.OnlyNew,
|
||||||
|
DestinationFormat(body.PhotoFormat, MediaKind.Photo),
|
||||||
|
DestinationFormat(body.VideoFormat, MediaKind.Video));
|
||||||
|
|
||||||
|
/// <summary>A destination's format: null, empty or <c>general</c> is «Come le impostazioni generali».</summary>
|
||||||
|
private static ExportFormat? DestinationFormat(string? text, MediaKind kind) =>
|
||||||
|
string.Equals(text?.Trim(), "general", StringComparison.OrdinalIgnoreCase) ? null : ParseFormat(text, kind);
|
||||||
|
|
||||||
private static string? Clean(string? text) => string.IsNullOrWhiteSpace(text) ? null : text.Trim();
|
private static string? Clean(string? text) => string.IsNullOrWhiteSpace(text) ? null : text.Trim();
|
||||||
|
|
||||||
@@ -646,9 +1025,9 @@ public static class ExportApi
|
|||||||
_ => "finished",
|
_ => "finished",
|
||||||
};
|
};
|
||||||
|
|
||||||
private static ExportJobDto Job(ExportStart start, ExportRootOptions root) => new(
|
private static ExportJobDto Job(ExportStart start, ExportRootOptions root, bool frames = false) => new(
|
||||||
[.. start.Runs.Select(r => r.Id)],
|
[.. start.Runs.Select(r => r.Id)],
|
||||||
Plan(start.Plan, root),
|
Plan(start.Plan, root, frames),
|
||||||
start.Runs.Count == 0
|
start.Runs.Count == 0
|
||||||
? "Niente da copiare: i file scelti sono già copiati, non si esportano o non sono in libreria."
|
? "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.");
|
: "Copia avviata: segui l'avanzamento nella Dashboard, scheda Esportazione.");
|
||||||
|
|||||||
@@ -43,11 +43,16 @@ public sealed record ExportDestinationDto(
|
|||||||
bool? Reachable = null,
|
bool? Reachable = null,
|
||||||
long? FreeBytes = null,
|
long? FreeBytes = null,
|
||||||
bool Orphan = false,
|
bool Orphan = false,
|
||||||
string? FormerUsername = null);
|
string? FormerUsername = null,
|
||||||
|
string? PhotoFormat = null,
|
||||||
|
string? VideoFormat = null);
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// <c>GET /api/export</c>: Impostazioni → Esportazione and the notice of the Dashboard. <paramref name="SamePost"/>:
|
/// <c>GET /api/export</c>: Impostazioni → Esportazione and the notice of the Dashboard. <paramref name="SamePost"/>:
|
||||||
/// <c>onePerAccount</c> or <c>oneOnly</c>. <paramref name="UnfinishedRuns"/>: interrupted or paused jobs («Riprendi»).
|
/// <c>onePerAccount</c> or <c>oneOnly</c>. <paramref name="UnfinishedRuns"/>: interrupted or paused jobs («Riprendi»).
|
||||||
|
/// Formats (tappa E3) on the wire: <c>original</c>, <c>jpg</c>, <c>png</c>, <c>webplossless</c>, <c>mp4</c>; the
|
||||||
|
/// library ones are <c>original</c> while the conversion of the library is off. <paramref name="LibraryConversion"/>:
|
||||||
|
/// the state of that conversion.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public sealed record ExportOverviewDto(
|
public sealed record ExportOverviewDto(
|
||||||
ExportRootDto Root,
|
ExportRootDto Root,
|
||||||
@@ -56,10 +61,45 @@ public sealed record ExportOverviewDto(
|
|||||||
IReadOnlyList<ExportDestinationDto> Own,
|
IReadOnlyList<ExportDestinationDto> Own,
|
||||||
IReadOnlyList<long> ActiveRunIds,
|
IReadOnlyList<long> ActiveRunIds,
|
||||||
int UnfinishedRuns,
|
int UnfinishedRuns,
|
||||||
ExportSchemesDto Library);
|
ExportSchemesDto Library,
|
||||||
|
string PhotoFormat = "original",
|
||||||
|
string VideoFormat = "original",
|
||||||
|
string LibraryPhotoFormat = "original",
|
||||||
|
string LibraryVideoFormat = "original",
|
||||||
|
LibraryConversionDto? LibraryConversion = null);
|
||||||
|
|
||||||
/// <summary><c>PUT /api/export/settings</c>: «Lo stesso post in due account», <c>onePerAccount</c> or <c>oneOnly</c>.</summary>
|
/// <summary>
|
||||||
public sealed record ExportSettingsRequest(string SamePost);
|
/// The conversion of the library (tappa E3, spec §4.10): files in the queue, converted, failed («Riprova»), that never
|
||||||
|
/// convert (<paramref name="AsIs"/>: «non si convertono»), «In pausa», and why it waits (Italian, null when it does
|
||||||
|
/// not): an import, a copy or a rebuild at work, an engine session, low space. <paramref name="Text"/>: the status line
|
||||||
|
/// («In coda 12 · convertiti 340 · non riusciti 2 · non si convertono 3»). <paramref name="On"/>: a library format is
|
||||||
|
/// chosen.
|
||||||
|
/// </summary>
|
||||||
|
public sealed record LibraryConversionDto(int Pending, int Converted, int Failed, int AsIs, bool Paused, string? Waiting, string Text, bool On);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// <c>PUT /api/export/settings</c>, every field optional (null keeps it): «Lo stesso post in due account»
|
||||||
|
/// (<c>onePerAccount</c> or <c>oneOnly</c>), the formats of the copies and of the library (wire names).
|
||||||
|
/// <paramref name="ConvertExisting"/>: the answer «Anche i N già in libreria» when a library format is turned on or
|
||||||
|
/// changed; it queues the files of the kinds whose library format this request changes, never those of the other.
|
||||||
|
/// </summary>
|
||||||
|
public sealed record ExportSettingsRequest(
|
||||||
|
string? SamePost = null,
|
||||||
|
string? PhotoFormat = null,
|
||||||
|
string? VideoFormat = null,
|
||||||
|
string? LibraryPhotoFormat = null,
|
||||||
|
string? LibraryVideoFormat = null,
|
||||||
|
bool? ConvertExisting = null);
|
||||||
|
|
||||||
|
/// <summary>What <c>PUT /api/export/settings</c> did: a message, the overview after the change, the files queued.</summary>
|
||||||
|
public sealed record ExportSettingsSavedDto(string Message, ExportOverviewDto Overview, int Queued = 0);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// «Converti anche i N file già in libreria?»: <paramref name="Files"/> that would enter the queue, the bytes of their
|
||||||
|
/// originals («circa») and the line of the question («gli originali occupano circa 3,1 GB; i convertiti possono occupare
|
||||||
|
/// di più»).
|
||||||
|
/// </summary>
|
||||||
|
public sealed record LibraryConversionPreviewDto(int Files, long Bytes, string Text);
|
||||||
|
|
||||||
/// <summary>Docker: the subfolders of a folder of <c>/esporta</c>. <paramref name="Relative"/> is "" for the root.</summary>
|
/// <summary>Docker: the subfolders of a folder of <c>/esporta</c>. <paramref name="Relative"/> is "" for the root.</summary>
|
||||||
public sealed record ExportFolderListDto(string Relative, string? Parent, string Display, IReadOnlyList<SourceFolderDto> Folders);
|
public sealed record ExportFolderListDto(string Relative, string? Parent, string Display, IReadOnlyList<SourceFolderDto> Folders);
|
||||||
@@ -88,7 +128,9 @@ public sealed record ExportDestinationRequest(
|
|||||||
string? HighlightNamingScheme,
|
string? HighlightNamingScheme,
|
||||||
string? ProfileNamingScheme,
|
string? ProfileNamingScheme,
|
||||||
bool Automatic = false,
|
bool Automatic = false,
|
||||||
bool OnlyNew = true);
|
bool OnlyNew = true,
|
||||||
|
string? PhotoFormat = null,
|
||||||
|
string? VideoFormat = null);
|
||||||
|
|
||||||
/// <summary>A saved destination (a change of folder gives a new id) and the warnings of its schemes.</summary>
|
/// <summary>A saved destination (a change of folder gives a new id) and the warnings of its schemes.</summary>
|
||||||
public sealed record ExportDestinationSavedDto(ExportDestinationDto Destination, IReadOnlyList<string> Warnings);
|
public sealed record ExportDestinationSavedDto(ExportDestinationDto Destination, IReadOnlyList<string> Warnings);
|
||||||
@@ -97,7 +139,10 @@ public sealed record ExportDestinationSavedDto(ExportDestinationDto Destination,
|
|||||||
/// What a «Copia in…» copies: exactly one of <paramref name="MediaIds"/> (files of «Tutte le foto» or the viewer),
|
/// What a «Copia in…» copies: exactly one of <paramref name="MediaIds"/> (files of «Tutte le foto» or the viewer),
|
||||||
/// <paramref name="EntryIds"/> (a grouped selection), <paramref name="Query"/> (the filter of the Libreria, as its query
|
/// <paramref name="EntryIds"/> (a grouped selection), <paramref name="Query"/> (the filter of the Libreria, as its query
|
||||||
/// string, with <paramref name="Mode"/> <c>grouped</c> or <c>files</c>) or <paramref name="AccountId"/> (every file of
|
/// string, with <paramref name="Mode"/> <c>grouped</c> or <c>files</c>) or <paramref name="AccountId"/> (every file of
|
||||||
/// the account). <paramref name="CopyAgain"/>: «Copia di nuovo anche i tolti o superati».
|
/// the account). <paramref name="CopyAgain"/>: «Copia di nuovo anche i tolti o superati». Tappa E3:
|
||||||
|
/// <paramref name="PhotoFormat"/>/<paramref name="VideoFormat"/> override the destination's for this request only
|
||||||
|
/// (null: as the destination); <paramref name="Frames"/> makes it a frames job («Fotogrammi…» → «Nella cartella delle
|
||||||
|
/// copie»), without formats.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public sealed record CopyJobRequestDto(
|
public sealed record CopyJobRequestDto(
|
||||||
IReadOnlyList<long>? MediaIds,
|
IReadOnlyList<long>? MediaIds,
|
||||||
@@ -105,7 +150,20 @@ public sealed record CopyJobRequestDto(
|
|||||||
string? Query,
|
string? Query,
|
||||||
string? Mode,
|
string? Mode,
|
||||||
long? AccountId,
|
long? AccountId,
|
||||||
bool CopyAgain = false);
|
bool CopyAgain = false,
|
||||||
|
string? PhotoFormat = null,
|
||||||
|
string? VideoFormat = null,
|
||||||
|
FramesRequestDto? Frames = null);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Which frames (spec §4.10 «Fotogrammi»): <paramref name="Mode"/> <c>istante</c> (at <paramref name="AtMs"/>),
|
||||||
|
/// <c>ogni</c> (every <paramref name="EveryMs"/>, at least 100) or <c>numero</c> (<paramref name="Count"/> in all, 1 to
|
||||||
|
/// 1.000); <paramref name="Format"/> <c>jpg</c>, <c>png</c> (the default) or <c>webplossless</c>.
|
||||||
|
/// </summary>
|
||||||
|
public sealed record FramesRequestDto(string? Mode, long? AtMs = null, long? EveryMs = null, int? Count = null, string? Format = null);
|
||||||
|
|
||||||
|
/// <summary>Files of a plan copied as they are, of one kind («3 HEIC copiati come sono»).</summary>
|
||||||
|
public sealed record ExportPlanAsIsDto(string Label, int Files);
|
||||||
|
|
||||||
/// <summary>A destination of a plan. <paramref name="Problem"/>: why it cannot be written now (paused, not reachable).</summary>
|
/// <summary>A destination of a plan. <paramref name="Problem"/>: why it cannot be written now (paused, not reachable).</summary>
|
||||||
public sealed record ExportPlanDestinationDto(
|
public sealed record ExportPlanDestinationDto(
|
||||||
@@ -123,7 +181,12 @@ public sealed record ExportPlanDestinationDto(
|
|||||||
/// <summary>
|
/// <summary>
|
||||||
/// The summary of «Copia in…» (spec §10.3). <paramref name="Files"/>/<paramref name="Bytes"/>: what will be written
|
/// The summary of «Copia in…» (spec §10.3). <paramref name="Files"/>/<paramref name="Bytes"/>: what will be written
|
||||||
/// (with «Copia di nuovo» the tolti/superati too). <paramref name="NotExported"/>: of accounts that are not exported
|
/// (with «Copia di nuovo» the tolti/superati too). <paramref name="NotExported"/>: of accounts that are not exported
|
||||||
/// (switch off, no destination, type not taken). <paramref name="Missing"/>: not in the library.
|
/// (switch off, no destination, type not taken). <paramref name="Missing"/>: not in the library. Tappa E3:
|
||||||
|
/// <paramref name="AsIs"/> files predicted copied as they are («circa»), <paramref name="Converted"/> predicted
|
||||||
|
/// converted, <paramref name="Lossy"/> «con perdita»; a frames job: <paramref name="Videos"/>,
|
||||||
|
/// <paramref name="PhotosSkipped"/>, <paramref name="Frames"/> and <paramref name="OverCap"/> (videos over 1.000
|
||||||
|
/// frames: the job is refused). <paramref name="Summary"/>: the line of the dialog («312 file · 41 già copiati, saltati ·
|
||||||
|
/// circa 3 HEIC copiati come sono · circa 4,2 GB · con perdita»).
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public sealed record ExportPlanDto(
|
public sealed record ExportPlanDto(
|
||||||
int Files,
|
int Files,
|
||||||
@@ -133,7 +196,15 @@ public sealed record ExportPlanDto(
|
|||||||
int NotExported,
|
int NotExported,
|
||||||
int Missing,
|
int Missing,
|
||||||
IReadOnlyList<ExportPlanDestinationDto> Destinations,
|
IReadOnlyList<ExportPlanDestinationDto> Destinations,
|
||||||
bool HasDestination = true);
|
bool HasDestination = true,
|
||||||
|
IReadOnlyList<ExportPlanAsIsDto>? AsIs = null,
|
||||||
|
int Converted = 0,
|
||||||
|
bool Lossy = false,
|
||||||
|
int Videos = 0,
|
||||||
|
int PhotosSkipped = 0,
|
||||||
|
int Frames = 0,
|
||||||
|
int OverCap = 0,
|
||||||
|
string? Summary = null);
|
||||||
|
|
||||||
/// <summary>The jobs a «Copia in…» started, one per destination (empty: nothing to copy), and the plan it followed.</summary>
|
/// <summary>The jobs a «Copia in…» started, one per destination (empty: nothing to copy), and the plan it followed.</summary>
|
||||||
public sealed record ExportJobDto(IReadOnlyList<long> RunIds, ExportPlanDto Plan, string Message);
|
public sealed record ExportJobDto(IReadOnlyList<long> RunIds, ExportPlanDto Plan, string Message);
|
||||||
@@ -174,24 +245,33 @@ public sealed record ExportRunDto(
|
|||||||
int Done,
|
int Done,
|
||||||
bool Running = false);
|
bool Running = false);
|
||||||
|
|
||||||
/// <summary>The files of one account in a job (<paramref name="Copied"/> counts written and adopted files).</summary>
|
/// <summary>
|
||||||
public sealed record ExportReportAccountDto(long? AccountId, string Username, int Copied, int AlreadyCopied, int Skipped, int Failed);
|
/// The files of one account in a job (<paramref name="Copied"/> counts written and adopted files).
|
||||||
|
/// <paramref name="AsIs"/>: files copied as they are, by kind («HEIC» → 3).
|
||||||
|
/// </summary>
|
||||||
|
public sealed record ExportReportAccountDto(long? AccountId, string Username, int Copied, int AlreadyCopied, int Skipped, int Failed, IReadOnlyDictionary<string, int>? AsIs = null);
|
||||||
|
|
||||||
/// <summary>A file of the report that needs a look, with its reason in Italian.</summary>
|
/// <summary>A file of the report that needs a look, with its reason in Italian.</summary>
|
||||||
public sealed record ExportReportLineDto(long ItemId, string Username, string? Path, string State, string Text);
|
public sealed record ExportReportLineDto(long ItemId, string Username, string? Path, string State, string Text);
|
||||||
|
|
||||||
/// <summary>The report of a job (at most 200 problems).</summary>
|
/// <summary>
|
||||||
|
/// The report of a job (at most 200 problems). <paramref name="Notes"/> (tappa E3): files copied or adopted with a note
|
||||||
|
/// (what a conversion could not keep, a file copied as it is), at most 200.
|
||||||
|
/// </summary>
|
||||||
public sealed record ExportReportDto(
|
public sealed record ExportReportDto(
|
||||||
ExportRunDto Run,
|
ExportRunDto Run,
|
||||||
IReadOnlyDictionary<string, int> ByState,
|
IReadOnlyDictionary<string, int> ByState,
|
||||||
long BytesCopied,
|
long BytesCopied,
|
||||||
IReadOnlyList<ExportReportAccountDto> Accounts,
|
IReadOnlyList<ExportReportAccountDto> Accounts,
|
||||||
IReadOnlyList<ExportReportLineDto> Problems);
|
IReadOnlyList<ExportReportLineDto> Problems,
|
||||||
|
IReadOnlyList<ExportReportLineDto>? Notes = null);
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// A copy of a file of the viewer (spec §4.6, §4.10). <paramref name="State"/>: copied, removed, superseded, failed;
|
/// A copy of a file of the viewer (spec §4.6, §4.10). <paramref name="State"/>: copied, removed, superseded, failed;
|
||||||
/// <paramref name="Variant"/>: whole (tappa E2 copies originals only). <paramref name="ForAccount"/>: with «Una copia
|
/// <paramref name="Variant"/>: whole, converted or frame; <paramref name="Format"/>: the wire name of a converted copy or
|
||||||
/// sola», the account it was copied for when it is another one. <paramref name="CanCopyAgain"/>: «Copia di nuovo».
|
/// of a frame (null for a whole one); <paramref name="FrameAtMs"/> and <paramref name="FrameLabel"/> («0:01,25») for a
|
||||||
|
/// frame. <paramref name="ForAccount"/>: with «Una copia sola», the account it was copied for when it is another one.
|
||||||
|
/// <paramref name="CanCopyAgain"/>: «Copia di nuovo» of that same form. <paramref name="Notes"/>: why it failed.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public sealed record MediaCopyDto(
|
public sealed record MediaCopyDto(
|
||||||
long CopyId,
|
long CopyId,
|
||||||
@@ -203,7 +283,17 @@ public sealed record MediaCopyDto(
|
|||||||
long? FrameAtMs,
|
long? FrameAtMs,
|
||||||
LocalTimeDto At,
|
LocalTimeDto At,
|
||||||
string? ForAccount,
|
string? ForAccount,
|
||||||
bool CanCopyAgain);
|
bool CanCopyAgain,
|
||||||
|
string? FrameLabel = null,
|
||||||
|
string? Notes = null);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// A converted file of the library next to its original (tappa E3, spec §4.10): <paramref name="Format"/> (wire name),
|
||||||
|
/// <paramref name="State"/> <c>pending</c>, <c>converted</c>, <c>failed</c>, <c>asIs</c> («non si converte»),
|
||||||
|
/// <c>superseded</c> or <c>removed</c>, its size, and <paramref name="Notes"/>: what was not kept, or why it failed or
|
||||||
|
/// does not convert. <paramref name="Available"/>: the file is on disk («Scarica», «Mostra nella cartella»).
|
||||||
|
/// </summary>
|
||||||
|
public sealed record MediaConversionDto(long Id, string Format, string State, long? Bytes, string? Notes, bool Available, string? FileName);
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// «Copie esterne» of the account card. <paramref name="Destination"/>: the effective one (its own folder, else the
|
/// «Copie esterne» of the account card. <paramref name="Destination"/>: the effective one (its own folder, else the
|
||||||
@@ -218,3 +308,51 @@ public sealed record ExportAccountDto(
|
|||||||
int NotCopied,
|
int NotCopied,
|
||||||
int RemovedOrSuperseded,
|
int RemovedOrSuperseded,
|
||||||
int Failed);
|
int Failed);
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------------------------- frames (tappa E3)
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// <c>GET /api/media/{id}/frames/info</c>: whether frames can be taken from the video (<paramref name="Unavailable"/>:
|
||||||
|
/// «Fotogramma non disponibile per questo video»), its length and its size as shown (rotation applied).
|
||||||
|
/// </summary>
|
||||||
|
public sealed record FrameInfoDto(bool Available, string? Unavailable, long DurationMs, int Width, int Height, bool HasAudio);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// One instant of a frames request: the one asked for, the one really shown (the frame's identity, ms rounded up), its
|
||||||
|
/// label («0:01,25») and the suffix of its file name (<c>_t0m01s250</c>, <c>_f001</c>).
|
||||||
|
/// </summary>
|
||||||
|
public sealed record FrameInstantDto(int Index, long RequestedMs, long ActualMs, string Label, string Suffix);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// <c>GET /api/media/{id}/frames/instants</c>: the instants of a mode for one video (at most 1.000). <paramref name="Total"/>:
|
||||||
|
/// how many it asks; <paramref name="Problem"/>: why none is given (over 1.000, not available).
|
||||||
|
/// </summary>
|
||||||
|
public sealed record FrameInstantsDto(long DurationMs, int Total, bool OverCap, string? Problem, IReadOnlyList<FrameInstantDto> Instants);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The frames of a selection («Fotogrammi…» from the selection bars): exactly one of <paramref name="MediaIds"/>,
|
||||||
|
/// <paramref name="EntryIds"/> (every video of those entries) or <paramref name="Query"/> with <paramref name="Mode"/>,
|
||||||
|
/// and which frames.
|
||||||
|
/// </summary>
|
||||||
|
public sealed record FramesSelectionRequest(IReadOnlyList<long>? MediaIds, IReadOnlyList<long>? EntryIds, string? Query, string? Mode, FramesRequestDto? Frames);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// <c>POST /api/frames/plan</c>: what «Scarica» would give. <paramref name="NotAvailable"/>: videos without frames (or
|
||||||
|
/// not on disk); <paramref name="OverCap"/>: videos over 1.000 frames; <paramref name="TooManyToDownload"/>: more than
|
||||||
|
/// 500 frames («Nella cartella delle copie»); <paramref name="NeedsQuiet"/>: more than 20 (only outside engine sessions
|
||||||
|
/// and other long work). <paramref name="Problem"/>: why «Scarica» cannot run now; <paramref name="Summary"/>: the line
|
||||||
|
/// of the dialog («12 fotogrammi da 4 video · le 3 foto si saltano»).
|
||||||
|
/// </summary>
|
||||||
|
public sealed record FramesPlanDto(int Videos, int PhotosSkipped, int NotAvailable, int Frames, int OverCap, bool TooManyToDownload, bool NeedsQuiet, string? Problem, string Summary);
|
||||||
|
|
||||||
|
/// <summary>A download of frames ready: open <paramref name="Url"/> once within 5 minutes.</summary>
|
||||||
|
public sealed record FramesTokenDto(string Token, int Frames, string Url);
|
||||||
|
|
||||||
|
/// <summary>A converted file of the library («Mostra nella cartella»).</summary>
|
||||||
|
public sealed record ConversionActionRequest(long ConversionId);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// What «Elimina dalla libreria» would remove (tappa E3, spec §4.6): the entries, their files and the converted files of
|
||||||
|
/// the library made from them («elimino gli elementi interi, 9 file e 2 file convertiti»).
|
||||||
|
/// </summary>
|
||||||
|
public sealed record EntryDeletionPreviewDto(int Entries, int Files, int ConvertedFiles);
|
||||||
@@ -105,4 +105,14 @@ namespace Febe.Web.Api;
|
|||||||
[JsonSerializable(typeof(IReadOnlyList<ExportRunDto>))]
|
[JsonSerializable(typeof(IReadOnlyList<ExportRunDto>))]
|
||||||
[JsonSerializable(typeof(ExportReportDto))]
|
[JsonSerializable(typeof(ExportReportDto))]
|
||||||
[JsonSerializable(typeof(ExportAccountDto))]
|
[JsonSerializable(typeof(ExportAccountDto))]
|
||||||
|
[JsonSerializable(typeof(ExportSettingsSavedDto))]
|
||||||
|
[JsonSerializable(typeof(LibraryConversionDto))]
|
||||||
|
[JsonSerializable(typeof(LibraryConversionPreviewDto))]
|
||||||
|
[JsonSerializable(typeof(FrameInfoDto))]
|
||||||
|
[JsonSerializable(typeof(FrameInstantsDto))]
|
||||||
|
[JsonSerializable(typeof(FramesSelectionRequest))]
|
||||||
|
[JsonSerializable(typeof(FramesPlanDto))]
|
||||||
|
[JsonSerializable(typeof(FramesTokenDto))]
|
||||||
|
[JsonSerializable(typeof(ConversionActionRequest))]
|
||||||
|
[JsonSerializable(typeof(EntryDeletionPreviewDto))]
|
||||||
public sealed partial class FebeJsonContext : JsonSerializerContext;
|
public sealed partial class FebeJsonContext : JsonSerializerContext;
|
||||||
@@ -0,0 +1,424 @@
|
|||||||
|
using System.Globalization;
|
||||||
|
using Febe.Core.Abstractions;
|
||||||
|
using Febe.Core.Domain;
|
||||||
|
using Febe.Core.Export;
|
||||||
|
using Febe.Core.Library;
|
||||||
|
using Febe.Core.Library.Conversion;
|
||||||
|
using Febe.Core.Storage;
|
||||||
|
using Febe.Web.Export;
|
||||||
|
using Febe.Web.Library;
|
||||||
|
using Febe.Web.Native;
|
||||||
|
using Microsoft.AspNetCore.Builder;
|
||||||
|
using Microsoft.AspNetCore.Http;
|
||||||
|
using Microsoft.AspNetCore.Routing;
|
||||||
|
using Microsoft.AspNetCore.StaticFiles;
|
||||||
|
using ItalianText = Febe.Core.Engine.ItalianText;
|
||||||
|
|
||||||
|
namespace Febe.Web.Api;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Frames of videos and the converted files of the library (spec §4.10, tappa E3): what a video allows, a frame at an
|
||||||
|
/// instant (previews of the dialog «Fotogrammi…» and «Scarica» of one frame), the instants of a mode, the plan of
|
||||||
|
/// «Scarica» for a selection and its download (one image, or a zip made while it is sent), and the files of the
|
||||||
|
/// conversion of the library («Scarica», «Mostra nella cartella»). Frames to a folder of the copies go through
|
||||||
|
/// <c>/api/export/plan</c> and <c>/start</c> with <c>frames</c>. Nothing here writes a file.
|
||||||
|
/// </summary>
|
||||||
|
public static class FramesApi
|
||||||
|
{
|
||||||
|
private static readonly FileExtensionContentTypeProvider ContentTypes = new();
|
||||||
|
|
||||||
|
public static void Map(IEndpointRouteBuilder endpoints)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(endpoints);
|
||||||
|
|
||||||
|
endpoints.MapGet("/api/media/{id:long}/frames/info", async (long id, IFebeStorage storage, IMediaFileResolver files, FrameService frames, CancellationToken ct) =>
|
||||||
|
{
|
||||||
|
var video = await VideoAsync(storage, files, id, ct).ConfigureAwait(false);
|
||||||
|
var info = await frames.InfoAsync(video.Path, video.Media.Sha256, ct).ConfigureAwait(false);
|
||||||
|
return ApiHttp.Json(
|
||||||
|
new FrameInfoDto(info.Available, info.Unavailable, (long)info.Duration.TotalMilliseconds, info.Width, info.Height, info.HasAudio),
|
||||||
|
FebeJsonContext.Default.FrameInfoDto);
|
||||||
|
});
|
||||||
|
|
||||||
|
endpoints.MapGet("/api/media/{id:long}/frame", async (long id, long? at, string? format, int? max, string? download, HttpContext context, IFebeStorage storage, IMediaFileResolver files, FrameService frames, CancellationToken ct) =>
|
||||||
|
{
|
||||||
|
var video = await VideoAsync(storage, files, id, ct).ConfigureAwait(false);
|
||||||
|
int? side = max is { } m ? Math.Clamp(m, 16, FrameService.MaxPreview) : null;
|
||||||
|
var chosen = string.IsNullOrWhiteSpace(format) && side is not null ? ExportFormat.Jpg : ExportApi.ParseFrameFormat(format);
|
||||||
|
var instant = TimeSpan.FromMilliseconds(Math.Max(0, at ?? 0));
|
||||||
|
var frame = await frames.FrameAsync(video.Path, video.Media.Sha256, instant, chosen, side, ct).ConfigureAwait(false);
|
||||||
|
if (download is "1" or "true")
|
||||||
|
{
|
||||||
|
context.Response.Headers.CacheControl = "private, no-cache";
|
||||||
|
var name = FrameService.FileName(Stem(video.Media), FrameMode.At, frame.Actual, 0, 1, chosen);
|
||||||
|
return Results.File(frame.Data, frame.ContentType, name);
|
||||||
|
}
|
||||||
|
|
||||||
|
// The same file, instant, size and format always give the same picture.
|
||||||
|
context.Response.Headers.CacheControl = "private, max-age=600";
|
||||||
|
return Results.File(frame.Data, frame.ContentType);
|
||||||
|
});
|
||||||
|
|
||||||
|
endpoints.MapGet("/api/media/{id:long}/frames/instants", async (long id, string? mode, long? at, long? every, int? count, IFebeStorage storage, IMediaFileResolver files, FrameService frames, CancellationToken ct) =>
|
||||||
|
{
|
||||||
|
var video = await VideoAsync(storage, files, id, ct).ConfigureAwait(false);
|
||||||
|
var request = ExportApi.Frames(new FramesRequestDto(mode ?? "numero", at, every, count, "png"));
|
||||||
|
ExportPlanner.Validate(new ExportJobRequest(new ExportSelection.Media([id]), Frames: request));
|
||||||
|
var info = await frames.InfoAsync(video.Path, video.Media.Sha256, ct).ConfigureAwait(false);
|
||||||
|
var durationMs = (long)info.Duration.TotalMilliseconds;
|
||||||
|
if (!info.Available)
|
||||||
|
{
|
||||||
|
return ApiHttp.Json(new FrameInstantsDto(durationMs, 0, false, info.Unavailable ?? VideoFrameReader.NotAvailableMessage, []), FebeJsonContext.Default.FrameInstantsDto);
|
||||||
|
}
|
||||||
|
|
||||||
|
var total = ExportFrames.FrameCount(info.Duration, request);
|
||||||
|
if (total > ExportFrames.MaxPerVideo)
|
||||||
|
{
|
||||||
|
return ApiHttp.Json(new FrameInstantsDto(durationMs, (int)Math.Min(total, int.MaxValue), true, ExportFrames.OverCapMessage, []), FebeJsonContext.Default.FrameInstantsDto);
|
||||||
|
}
|
||||||
|
|
||||||
|
var (_, targets) = await frames.LocateAsync(video.Path, video.Media.Sha256, request, ct).ConfigureAwait(false);
|
||||||
|
var list = targets.Select(t => new FrameInstantDto(
|
||||||
|
t.Index,
|
||||||
|
(long)t.Requested.TotalMilliseconds,
|
||||||
|
ExportFrames.ActualMs(t.Actual),
|
||||||
|
ExportFrames.Label(t.Actual),
|
||||||
|
ExportFrames.Suffix(request.Mode, t.Actual, t.Index, targets.Count))).ToList();
|
||||||
|
return ApiHttp.Json(new FrameInstantsDto(durationMs, list.Count, false, null, list), FebeJsonContext.Default.FrameInstantsDto);
|
||||||
|
});
|
||||||
|
|
||||||
|
endpoints.MapPost("/api/frames/plan", async (HttpContext context, IFebeStorage storage, IMediaFileResolver files, FrameService frames, LongWorkGate gate, IEngineSessionState session, IClock clock, CancellationToken ct) =>
|
||||||
|
{
|
||||||
|
var body = await ApiHttp.BodyAsync(context, FebeJsonContext.Default.FramesSelectionRequest).ConfigureAwait(false);
|
||||||
|
var plan = await SelectionAsync(body, storage, files, frames, clock, ct).ConfigureAwait(false);
|
||||||
|
var problem = Problem(plan, gate, session);
|
||||||
|
return ApiHttp.Json(
|
||||||
|
new FramesPlanDto(plan.VideoCount, plan.Photos, plan.NotAvailable, plan.Frames, plan.OverCap, plan.Frames > FrameService.MaxDownload, plan.Frames > FrameService.MaxAnyTime, problem, Summary(plan)),
|
||||||
|
FebeJsonContext.Default.FramesPlanDto);
|
||||||
|
});
|
||||||
|
|
||||||
|
endpoints.MapPost("/api/frames/download-token", async (HttpContext context, IFebeStorage storage, IMediaFileResolver files, FrameService frames, LongWorkGate gate, IEngineSessionState session, IClock clock, CancellationToken ct) =>
|
||||||
|
{
|
||||||
|
var body = await ApiHttp.BodyAsync(context, FebeJsonContext.Default.FramesSelectionRequest).ConfigureAwait(false);
|
||||||
|
var plan = await SelectionAsync(body, storage, files, frames, clock, ct).ConfigureAwait(false);
|
||||||
|
if (plan.Frames == 0)
|
||||||
|
{
|
||||||
|
throw new BadRequestException(plan.OverCap > 0 ? ExportFrames.OverCapMessage : FrameService.NothingText);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (plan.Frames > FrameService.MaxDownload)
|
||||||
|
{
|
||||||
|
throw new BadRequestException(FrameService.TooManyText);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (Problem(plan, gate, session) is { } problem)
|
||||||
|
{
|
||||||
|
throw new ApiStatusException(409, problem);
|
||||||
|
}
|
||||||
|
|
||||||
|
var token = frames.Register(new FrameDownloadPlan(plan.Request.Mode, plan.Request.Format, plan.Videos));
|
||||||
|
return ApiHttp.Json(new FramesTokenDto(token, plan.Frames, "/api/frames/download/" + token), FebeJsonContext.Default.FramesTokenDto);
|
||||||
|
});
|
||||||
|
|
||||||
|
endpoints.MapGet("/api/frames/download/{token}", async (string token, HttpContext context, IFebeStorage storage, FebeLibrary library, FrameService frames, LongWorkGate gate, IEngineSessionState session, IClock clock) =>
|
||||||
|
{
|
||||||
|
var plan = frames.Take(token) ?? throw new NotFoundException("Questo scaricamento non vale più: scegli di nuovo «Scarica».");
|
||||||
|
var ct = context.RequestAborted;
|
||||||
|
if (plan.Frames == 1)
|
||||||
|
{
|
||||||
|
var video = plan.Videos.First(v => v.Instants.Count > 0);
|
||||||
|
var one = await frames.FrameAsync(video.Path, null, video.Instants[0], plan.Format, null, ct).ConfigureAwait(false);
|
||||||
|
var name = FrameService.FileName(video.Stem, plan.Mode, one.Actual, 0, video.Instants.Count, plan.Format);
|
||||||
|
context.Response.Headers.CacheControl = "private, no-cache";
|
||||||
|
await Results.File(one.Data, one.ContentType, name).ExecuteAsync(context).ConfigureAwait(false);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
IDisposable? lease = null;
|
||||||
|
if (plan.Frames > FrameService.MaxAnyTime)
|
||||||
|
{
|
||||||
|
if (session.InSession)
|
||||||
|
{
|
||||||
|
throw new ApiStatusException(409, FrameService.SessionText);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!gate.TryEnter(LongWorkKind.FrameDownload, out lease, out var busy))
|
||||||
|
{
|
||||||
|
throw new ApiStatusException(409, LongWorkGate.BusyMessage(LongWorkKind.FrameDownload, busy ?? LongWorkKind.FrameDownload));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var publication = (await LibrarySettings.LoadAsync(storage.Settings, library.Layout.Root, ct).ConfigureAwait(false)).SetFileTimeToPublication;
|
||||||
|
context.Response.ContentType = "application/zip";
|
||||||
|
context.Response.Headers.CacheControl = "private, no-cache";
|
||||||
|
context.Response.Headers.ContentDisposition = $"attachment; filename=\"febe-fotogrammi-{FrameService.Day(clock.Now, clock.LocalZone)}.zip\"";
|
||||||
|
await context.Response.StartAsync(ct).ConfigureAwait(false);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await frames.WriteZipAsync(context.Response.Body, plan, publication, ct).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
catch (Exception ex) when (ex is OperationCanceledException or IOException)
|
||||||
|
{
|
||||||
|
// The page went away, or stopped reading: the zip is left unfinished, so the browser says it failed.
|
||||||
|
context.Abort();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
lease?.Dispose();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
endpoints.MapGet("/api/conversions/{id:long}/file", async (long id, string? download, HttpContext context, IFebeStorage storage, IConversionFileResolver files, CancellationToken ct) =>
|
||||||
|
{
|
||||||
|
var path = await ConversionPathAsync(storage, files, id, ct).ConfigureAwait(false) ?? throw new NotFoundException("Il file convertito non è sul disco.");
|
||||||
|
if (!ContentTypes.TryGetContentType(path, out var type))
|
||||||
|
{
|
||||||
|
type = "application/octet-stream";
|
||||||
|
}
|
||||||
|
|
||||||
|
context.Response.Headers.CacheControl = "private, no-cache";
|
||||||
|
return download is "1" or "true"
|
||||||
|
? Results.File(path, type, Path.GetFileName(path), enableRangeProcessing: true)
|
||||||
|
: Results.File(path, type, enableRangeProcessing: true);
|
||||||
|
});
|
||||||
|
|
||||||
|
endpoints.MapPost("/api/conversions/show-in-folder", async (HttpContext context, IFebeStorage storage, IConversionFileResolver files, INativeShell shell, CancellationToken ct) =>
|
||||||
|
{
|
||||||
|
var body = await ApiHttp.BodyAsync(context, FebeJsonContext.Default.ConversionActionRequest).ConfigureAwait(false);
|
||||||
|
var path = await ConversionPathAsync(storage, files, body.ConversionId, ct).ConfigureAwait(false)
|
||||||
|
?? throw new NotFoundException("Il file convertito non è sul disco: forse è stato spostato o cancellato fuori da Febe.");
|
||||||
|
if (!await shell.ShowInFolderAsync(path, ct).ConfigureAwait(false))
|
||||||
|
{
|
||||||
|
throw new BadRequestException("Qui non si può aprire la cartella: usa «Scarica».");
|
||||||
|
}
|
||||||
|
|
||||||
|
return ApiHttp.Message("Cartella aperta.");
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The rows of the converted files of one library file for the viewer (tappa E3, §16 domanda 30).</summary>
|
||||||
|
public static IReadOnlyList<MediaConversionDto> Conversions(IConversionFileResolver files, Account account, IEnumerable<MediaConversion> rows)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(files);
|
||||||
|
ArgumentNullException.ThrowIfNull(account);
|
||||||
|
ArgumentNullException.ThrowIfNull(rows);
|
||||||
|
return [.. rows
|
||||||
|
.Where(r => r.State != MediaConversionState.Removed)
|
||||||
|
.Select(r =>
|
||||||
|
{
|
||||||
|
var path = files.Resolve(account, r);
|
||||||
|
return new MediaConversionDto(
|
||||||
|
r.Id,
|
||||||
|
ExportApi.FormatName(r.Format),
|
||||||
|
ExportApi.ConversionState(r),
|
||||||
|
r.Bytes,
|
||||||
|
LibraryConversionText.Note(r.LastError),
|
||||||
|
path is not null,
|
||||||
|
r.RelativePath is { } relative ? Path.GetFileName(LibraryLayout.ToPlatform(relative)) : null);
|
||||||
|
})];
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------------------------- selection
|
||||||
|
|
||||||
|
/// <summary>What «Scarica» would give for a selection: the videos with their instants, and what is left out.</summary>
|
||||||
|
/// <param name="VideoCount">Videos of the selection (with frames or not).</param>
|
||||||
|
/// <param name="Frames">Frames in all (from the lengths of the database when the videos were not opened).</param>
|
||||||
|
private sealed record FramesSelection(ExportFramesRequest Request, List<FrameDownloadVideo> Videos, int VideoCount, int Photos, int NotAvailable, int OverCap, int Frames);
|
||||||
|
|
||||||
|
private static async Task<FramesSelection> SelectionAsync(FramesSelectionRequest body, IFebeStorage storage, IMediaFileResolver files, FrameService frames, IClock clock, CancellationToken ct)
|
||||||
|
{
|
||||||
|
var request = body.Frames is { } f ? ExportApi.Frames(f) : throw new BadRequestException("Scegli quali fotogrammi.");
|
||||||
|
var selection = ExportApi.Request(new CopyJobRequestDto(body.MediaIds, body.EntryIds, body.Query, body.Mode, null), clock).Selection;
|
||||||
|
ExportPlanner.Validate(new ExportJobRequest(selection, Frames: request));
|
||||||
|
var accounts = (await storage.Accounts.ListAsync(ct).ConfigureAwait(false)).ToDictionary(a => a.Id);
|
||||||
|
|
||||||
|
// The present videos of the selection, in media order; photos are counted and skipped.
|
||||||
|
var candidates = new List<ExportCandidate>();
|
||||||
|
var photos = 0;
|
||||||
|
var missing = 0;
|
||||||
|
long after = 0;
|
||||||
|
while (true)
|
||||||
|
{
|
||||||
|
var page = await storage.Exports.ListCandidatesAsync(selection, after, 500, ct).ConfigureAwait(false);
|
||||||
|
if (page.Count == 0)
|
||||||
|
{
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
after = page[^1].MediaId;
|
||||||
|
foreach (var c in page)
|
||||||
|
{
|
||||||
|
if (c.MediaKind != MediaKind.Video)
|
||||||
|
{
|
||||||
|
photos++;
|
||||||
|
}
|
||||||
|
else if (!EntryStateRules.IsPresent(c.State) || c.RelativePath is null || !accounts.ContainsKey(c.AccountId))
|
||||||
|
{
|
||||||
|
missing++;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
candidates.Add(c);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Few enough to download: each video is opened (from the cache when it was seen) for its length and whether
|
||||||
|
// frames can be taken; otherwise the lengths of the database are enough to say «scegli la cartella delle copie».
|
||||||
|
var probe = candidates.Count <= FrameService.MaxDownload;
|
||||||
|
var videos = new List<FrameDownloadVideo>();
|
||||||
|
var notAvailable = missing;
|
||||||
|
var overCap = 0;
|
||||||
|
var unprobedFrames = 0L;
|
||||||
|
foreach (var c in candidates)
|
||||||
|
{
|
||||||
|
var account = accounts[c.AccountId];
|
||||||
|
TimeSpan duration;
|
||||||
|
string? path = null;
|
||||||
|
if (probe)
|
||||||
|
{
|
||||||
|
var media = await storage.Media.GetAsync(c.MediaId, ct).ConfigureAwait(false);
|
||||||
|
path = media is null ? null : files.Resolve(account, media);
|
||||||
|
if (path is null)
|
||||||
|
{
|
||||||
|
notAvailable++;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
var info = await frames.InfoAsync(path, c.Sha256, ct).ConfigureAwait(false);
|
||||||
|
if (!info.Available)
|
||||||
|
{
|
||||||
|
notAvailable++;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
duration = info.Duration;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
duration = c.Duration ?? TimeSpan.Zero;
|
||||||
|
}
|
||||||
|
|
||||||
|
var count = ExportFrames.FrameCount(duration, request);
|
||||||
|
if (count > ExportFrames.MaxPerVideo)
|
||||||
|
{
|
||||||
|
overCap++;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!probe)
|
||||||
|
{
|
||||||
|
unprobedFrames += count;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
var entry = await storage.Entries.GetAsync(c.EntryId, ct).ConfigureAwait(false);
|
||||||
|
videos.Add(new FrameDownloadVideo(
|
||||||
|
account.Username,
|
||||||
|
path!,
|
||||||
|
Path.GetFileNameWithoutExtension(LibraryLayout.ToPlatform(c.RelativePath!)),
|
||||||
|
ExportFrames.Instants(duration, request),
|
||||||
|
entry?.PublishedAt ?? clock.Now));
|
||||||
|
}
|
||||||
|
|
||||||
|
var total = probe ? videos.Sum(v => v.Instants.Count) : (int)Math.Min(unprobedFrames, int.MaxValue);
|
||||||
|
return new FramesSelection(request, videos, candidates.Count + missing, photos, notAvailable, overCap, total);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Why «Scarica» cannot run now; null when it can.</summary>
|
||||||
|
private static string? Problem(FramesSelection plan, LongWorkGate gate, IEngineSessionState session)
|
||||||
|
{
|
||||||
|
if (plan.Frames == 0)
|
||||||
|
{
|
||||||
|
return plan.OverCap > 0 ? ExportFrames.OverCapMessage : FrameService.NothingText;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (plan.Frames > FrameService.MaxDownload)
|
||||||
|
{
|
||||||
|
return FrameService.TooManyText;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (plan.Frames > FrameService.MaxAnyTime)
|
||||||
|
{
|
||||||
|
if (session.InSession)
|
||||||
|
{
|
||||||
|
return FrameService.SessionText;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (gate.Busy is { } busy)
|
||||||
|
{
|
||||||
|
return LongWorkGate.BusyMessage(LongWorkKind.FrameDownload, busy);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>«12 fotogrammi da 4 video · le 3 foto si saltano · 3 video senza fotogrammi».</summary>
|
||||||
|
private static string Summary(FramesSelection plan)
|
||||||
|
{
|
||||||
|
var withFrames = plan.VideoCount - plan.NotAvailable - plan.OverCap;
|
||||||
|
var parts = new List<string>
|
||||||
|
{
|
||||||
|
withFrames > 0
|
||||||
|
? $"{ItalianText.Count(plan.Frames, "fotogramma", "fotogrammi")} da {ItalianText.Number(withFrames)} video"
|
||||||
|
: ItalianText.Count(plan.Frames, "fotogramma", "fotogrammi"),
|
||||||
|
};
|
||||||
|
if (plan.Photos > 0)
|
||||||
|
{
|
||||||
|
parts.Add(ExportApi.PhotosSkippedText(plan.Photos));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (plan.NotAvailable > 0)
|
||||||
|
{
|
||||||
|
parts.Add(plan.NotAvailable == 1 ? "1 video senza fotogrammi" : $"{ItalianText.Number(plan.NotAvailable)} video senza fotogrammi");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (plan.OverCap > 0)
|
||||||
|
{
|
||||||
|
parts.Add(plan.OverCap == 1 ? "1 video oltre 1.000 fotogrammi" : $"{ItalianText.Number(plan.OverCap)} video oltre 1.000 fotogrammi");
|
||||||
|
}
|
||||||
|
|
||||||
|
return string.Join(" · ", parts);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------------------------- helpers
|
||||||
|
|
||||||
|
private sealed record VideoFile(Account Account, Media Media, string Path);
|
||||||
|
|
||||||
|
/// <summary>A present video of the library on disk; 404 otherwise.</summary>
|
||||||
|
private static async Task<VideoFile> VideoAsync(IFebeStorage storage, IMediaFileResolver files, long mediaId, CancellationToken ct)
|
||||||
|
{
|
||||||
|
var media = await storage.Media.GetAsync(mediaId, ct).ConfigureAwait(false) ?? throw new NotFoundException("File non trovato.");
|
||||||
|
if (media.Kind != MediaKind.Video)
|
||||||
|
{
|
||||||
|
throw new BadRequestException("I fotogrammi si prendono solo dai video.");
|
||||||
|
}
|
||||||
|
|
||||||
|
var entry = await storage.Entries.GetAsync(media.EntryId, ct).ConfigureAwait(false) ?? throw new NotFoundException("Elemento non trovato.");
|
||||||
|
var account = await storage.Accounts.GetAsync(entry.AccountId, ct).ConfigureAwait(false) ?? throw new NotFoundException("Account non trovato.");
|
||||||
|
var path = files.Resolve(account, media) ?? throw new NotFoundException("Il file non è sul disco.");
|
||||||
|
return new VideoFile(account, media, path);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string Stem(Media media) =>
|
||||||
|
media.RelativePath is { } relative ? Path.GetFileNameWithoutExtension(LibraryLayout.ToPlatform(relative)) : "video-" + media.Id.ToString(CultureInfo.InvariantCulture);
|
||||||
|
|
||||||
|
/// <summary>The file of a Converted or Superseded conversion of a present account, or null.</summary>
|
||||||
|
private static async Task<string?> ConversionPathAsync(IFebeStorage storage, IConversionFileResolver files, long id, CancellationToken ct)
|
||||||
|
{
|
||||||
|
var conversion = await storage.Conversions.GetAsync(id, ct).ConfigureAwait(false) ?? throw new NotFoundException("Conversione non trovata.");
|
||||||
|
if (conversion.State is not (MediaConversionState.Converted or MediaConversionState.Superseded))
|
||||||
|
{
|
||||||
|
throw new NotFoundException("Questa conversione non ha un file.");
|
||||||
|
}
|
||||||
|
|
||||||
|
var media = await storage.Media.GetAsync(conversion.MediaId, ct).ConfigureAwait(false) ?? throw new NotFoundException("File non trovato.");
|
||||||
|
var entry = await storage.Entries.GetAsync(media.EntryId, ct).ConfigureAwait(false) ?? throw new NotFoundException("Elemento non trovato.");
|
||||||
|
var account = await storage.Accounts.GetAsync(entry.AccountId, ct).ConfigureAwait(false) ?? throw new NotFoundException("Account non trovato.");
|
||||||
|
return files.Resolve(account, conversion);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -5,6 +5,7 @@ using Febe.Core.Domain;
|
|||||||
using Febe.Core.Export;
|
using Febe.Core.Export;
|
||||||
using Febe.Core.Library;
|
using Febe.Core.Library;
|
||||||
using Febe.Core.Storage;
|
using Febe.Core.Storage;
|
||||||
|
using Febe.Web.Export;
|
||||||
using Febe.Web.Library;
|
using Febe.Web.Library;
|
||||||
using Febe.Web.Native;
|
using Febe.Web.Native;
|
||||||
using Microsoft.AspNetCore.Builder;
|
using Microsoft.AspNetCore.Builder;
|
||||||
@@ -136,8 +137,8 @@ public static class LibraryApi
|
|||||||
return ApiHttp.Message("Cartella aperta.");
|
return ApiHttp.Message("Cartella aperta.");
|
||||||
});
|
});
|
||||||
|
|
||||||
endpoints.MapGet("/api/entries/{id:long}", async (long id, IFebeStorage storage, IMediaFileResolver files, FebeLibrary library, IClock clock, CancellationToken ct) =>
|
endpoints.MapGet("/api/entries/{id:long}", async (long id, IFebeStorage storage, IMediaFileResolver files, FebeLibrary library, IClock clock, FrameService frames, IConversionFileResolver conversions, CancellationToken ct) =>
|
||||||
ApiHttp.Json(await EntryAsync(id, storage, files, library, clock, ct).ConfigureAwait(false), FebeJsonContext.Default.EntryDto));
|
ApiHttp.Json(await EntryAsync(id, storage, files, library, clock, ct, frames, conversions).ConfigureAwait(false), FebeJsonContext.Default.EntryDto));
|
||||||
|
|
||||||
endpoints.MapPost("/api/entries/{id:long}/open-on-instagram", async (long id, IFebeStorage storage, INativeShell shell, IClock clock, CancellationToken ct) =>
|
endpoints.MapPost("/api/entries/{id:long}/open-on-instagram", async (long id, IFebeStorage storage, INativeShell shell, IClock clock, CancellationToken ct) =>
|
||||||
{
|
{
|
||||||
@@ -165,12 +166,43 @@ public static class LibraryApi
|
|||||||
var results = await library.Deletion.DeleteManyAsync(body.Ids, mode, ct).ConfigureAwait(false);
|
var results = await library.Deletion.DeleteManyAsync(body.Ids, mode, ct).ConfigureAwait(false);
|
||||||
var deleted = results.Count(r => r.Found);
|
var deleted = results.Count(r => r.Found);
|
||||||
var removed = results.Sum(r => r.DeletedFiles.Count);
|
var removed = results.Sum(r => r.DeletedFiles.Count);
|
||||||
|
var converted = results.Sum(r => r.ConvertedFiles);
|
||||||
var problems = results.SelectMany(r => r.FailedFiles).ToList();
|
var problems = results.SelectMany(r => r.FailedFiles).ToList();
|
||||||
changes.Publish(new LibraryChange(clock.Now, null, "deleted"));
|
changes.Publish(new LibraryChange(clock.Now, null, "deleted"));
|
||||||
var message = (deleted == 1 ? "Elemento eliminato dalla libreria" : $"{Core.Engine.ItalianText.Number(deleted)} elementi eliminati dalla libreria")
|
var message = (deleted == 1 ? "Elemento eliminato dalla libreria" : $"{Core.Engine.ItalianText.Number(deleted)} elementi eliminati dalla libreria")
|
||||||
|
+ (converted > 0 ? $", con {Core.Engine.ItalianText.Count(converted, "file convertito", "file convertiti")}" : string.Empty)
|
||||||
+ (mode == DeletionMode.Remember ? ": Febe non li scarica di nuovo." : ": se ricompaiono, Febe li scarica di nuovo.")
|
+ (mode == DeletionMode.Remember ? ": Febe non li scarica di nuovo." : ": se ricompaiono, Febe li scarica di nuovo.")
|
||||||
+ (problems.Count > 0 ? $" {Core.Engine.ItalianText.Count(problems.Count, "file non si è potuto cancellare", "file non si sono potuti cancellare")}: chiudi i programmi che li usano e riprova." : string.Empty);
|
+ (problems.Count > 0 ? $" {Core.Engine.ItalianText.Count(problems.Count, "file non si è potuto cancellare", "file non si sono potuti cancellare")}: chiudi i programmi che li usano e riprova." : string.Empty);
|
||||||
return ApiHttp.Json(new DeleteResultDto(deleted, removed, problems, message), FebeJsonContext.Default.DeleteResultDto);
|
return ApiHttp.Json(new DeleteResultDto(deleted, removed, problems, message, converted), FebeJsonContext.Default.DeleteResultDto);
|
||||||
|
});
|
||||||
|
|
||||||
|
// What «Elimina dalla libreria» would remove (tappa E3): the confirmation also counts the converted files.
|
||||||
|
endpoints.MapPost("/api/entries/delete-preview", async (HttpContext context, IFebeStorage storage, CancellationToken ct) =>
|
||||||
|
{
|
||||||
|
var body = await ApiHttp.BodyAsync(context, FebeJsonContext.Default.EntryIdsRequest).ConfigureAwait(false);
|
||||||
|
if (body.Ids.Count > 5000)
|
||||||
|
{
|
||||||
|
throw new BadRequestException("Troppi elementi in una richiesta.");
|
||||||
|
}
|
||||||
|
|
||||||
|
var entries = 0;
|
||||||
|
var files = 0;
|
||||||
|
var converted = 0;
|
||||||
|
foreach (var id in body.Ids.Distinct())
|
||||||
|
{
|
||||||
|
var stored = await storage.Entries.GetWithMediaAsync(id, ct).ConfigureAwait(false);
|
||||||
|
if (stored is null)
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
entries++;
|
||||||
|
files += stored.Media.Count(m => m.RelativePath is not null && EntryStateRules.IsPresent(m.State));
|
||||||
|
converted += (await storage.Conversions.ListByEntryAsync(id, ct).ConfigureAwait(false))
|
||||||
|
.Count(c => c.State is MediaConversionState.Converted or MediaConversionState.Superseded && c.RelativePath is not null);
|
||||||
|
}
|
||||||
|
|
||||||
|
return ApiHttp.Json(new EntryDeletionPreviewDto(entries, files, converted), FebeJsonContext.Default.EntryDeletionPreviewDto);
|
||||||
});
|
});
|
||||||
|
|
||||||
endpoints.MapPost("/api/entries/export", async (HttpContext context, IFebeStorage storage, IClock clock) =>
|
endpoints.MapPost("/api/entries/export", async (HttpContext context, IFebeStorage storage, IClock clock) =>
|
||||||
@@ -220,7 +252,12 @@ public static class LibraryApi
|
|||||||
tile.FilePosition);
|
tile.FilePosition);
|
||||||
}
|
}
|
||||||
|
|
||||||
public static async Task<EntryDto> EntryAsync(long id, IFebeStorage storage, IMediaFileResolver files, FebeLibrary library, IClock clock, CancellationToken ct)
|
/// <summary>
|
||||||
|
/// Everything the viewer shows of an entry. With <paramref name="frames"/>, a video says whether frames can be taken
|
||||||
|
/// (from the cache by SHA-256, else probed within a short time: null when it takes longer); with
|
||||||
|
/// <paramref name="conversions"/>, each file lists its converted files of the library (tappa E3).
|
||||||
|
/// </summary>
|
||||||
|
public static async Task<EntryDto> EntryAsync(long id, IFebeStorage storage, IMediaFileResolver files, FebeLibrary library, IClock clock, CancellationToken ct, FrameService? frames = null, IConversionFileResolver? conversions = null)
|
||||||
{
|
{
|
||||||
ArgumentNullException.ThrowIfNull(storage);
|
ArgumentNullException.ThrowIfNull(storage);
|
||||||
ArgumentNullException.ThrowIfNull(files);
|
ArgumentNullException.ThrowIfNull(files);
|
||||||
@@ -236,6 +273,7 @@ public static class LibraryApi
|
|||||||
var accountFolder = Path.GetFileName(Path.TrimEndingDirectorySeparator(library.Layout.AccountFolder(account)));
|
var accountFolder = Path.GetFileName(Path.TrimEndingDirectorySeparator(library.Layout.AccountFolder(account)));
|
||||||
var avatar = await AccountsApi.AvatarAsync(storage, account.Id, ct).ConfigureAwait(false);
|
var avatar = await AccountsApi.AvatarAsync(storage, account.Id, ct).ConfigureAwait(false);
|
||||||
var copies = await EntryCopiesContext.LoadAsync(storage, account, ct).ConfigureAwait(false);
|
var copies = await EntryCopiesContext.LoadAsync(storage, account, ct).ConfigureAwait(false);
|
||||||
|
var converted = conversions is null ? [] : await storage.Conversions.ListByEntryAsync(id, ct).ConfigureAwait(false);
|
||||||
var media = new List<MediaDto>(stored.Media.Count);
|
var media = new List<MediaDto>(stored.Media.Count);
|
||||||
foreach (var m in stored.Media)
|
foreach (var m in stored.Media)
|
||||||
{
|
{
|
||||||
@@ -263,7 +301,9 @@ public static class LibraryApi
|
|||||||
path is not null,
|
path is not null,
|
||||||
ApiMapping.State(m.State),
|
ApiMapping.State(m.State),
|
||||||
damaged,
|
damaged,
|
||||||
copies is null ? null : await copies.CopiesAsync(storage, m, now, zone, ct).ConfigureAwait(false)));
|
copies is null ? null : await copies.CopiesAsync(storage, m, now, zone, ct).ConfigureAwait(false),
|
||||||
|
await FramesAvailableAsync(frames, m, path, ct).ConfigureAwait(false),
|
||||||
|
conversions is null ? null : FramesApi.Conversions(conversions, account, converted.Where(c => c.MediaId == m.Id))));
|
||||||
}
|
}
|
||||||
|
|
||||||
return new EntryDto(
|
return new EntryDto(
|
||||||
@@ -311,9 +351,14 @@ public static class LibraryApi
|
|||||||
var tile = tiles[i];
|
var tile = tiles[i];
|
||||||
if (tile.FilePosition is not null)
|
if (tile.FilePosition is not null)
|
||||||
{
|
{
|
||||||
if (tile.CoverMediaId is { } mediaId && fileMarks is not null && fileMarks.TryGetValue(mediaId, out var mark) && mark == ExportMark.Copied)
|
if (tile.CoverMediaId is { } mediaId && fileMarks is not null && fileMarks.TryGetValue(mediaId, out var mark))
|
||||||
{
|
{
|
||||||
list[i] = list[i] with { Copies = "copied" };
|
list[i] = mark switch
|
||||||
|
{
|
||||||
|
ExportMark.Copied => list[i] with { Copies = "copied" },
|
||||||
|
ExportMark.FrameOnly => list[i] with { Copies = "frameOnly" },
|
||||||
|
_ => list[i],
|
||||||
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
else if (entryCopies is not null && entryCopies.TryGetValue(tile.EntryId, out var copies))
|
else if (entryCopies is not null && entryCopies.TryGetValue(tile.EntryId, out var copies))
|
||||||
@@ -322,6 +367,7 @@ public static class LibraryApi
|
|||||||
{
|
{
|
||||||
ExportMark.Copied => list[i] with { Copies = "copied" },
|
ExportMark.Copied => list[i] with { Copies = "copied" },
|
||||||
ExportMark.Partly => list[i] with { Copies = "partly", CopiesDone = copies.Copied, CopiesDue = copies.Due },
|
ExportMark.Partly => list[i] with { Copies = "partly", CopiesDone = copies.Copied, CopiesDue = copies.Due },
|
||||||
|
ExportMark.FrameOnly => list[i] with { Copies = "frameOnly" },
|
||||||
_ => list[i],
|
_ => list[i],
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -402,7 +448,7 @@ public static class LibraryApi
|
|||||||
&& !destination.IsRetired
|
&& !destination.IsRetired
|
||||||
&& Enabled
|
&& Enabled
|
||||||
&& Effective?.Id == destination.Id
|
&& Effective?.Id == destination.Id
|
||||||
&& !rows.Any(c => c.State == ExportCopyState.Copied && c.SourceSha256 == sha && c.AccountId == Account.Id && c.DestinationId == destination.Id && c.Variant == copy.Variant);
|
&& !rows.Any(c => c.State == ExportCopyState.Copied && c.SourceSha256 == sha && c.AccountId == Account.Id && c.DestinationId == destination.Id && ExportApi.SameForm(c, copy));
|
||||||
shown.Add(new MediaCopyDto(
|
shown.Add(new MediaCopyDto(
|
||||||
copy.Id,
|
copy.Id,
|
||||||
ExportDestinations.Label(destination),
|
ExportDestinations.Label(destination),
|
||||||
@@ -415,10 +461,12 @@ public static class LibraryApi
|
|||||||
_ => "frame",
|
_ => "frame",
|
||||||
},
|
},
|
||||||
copy.Format == ExportFormat.Original ? null : copy.Format.ToString().ToLowerInvariant(),
|
copy.Format == ExportFormat.Original ? null : copy.Format.ToString().ToLowerInvariant(),
|
||||||
copy.FrameAt is { } frame ? (long)frame.TotalMilliseconds : null,
|
copy.FrameAt is { } frame ? ExportFrames.ActualMs(frame) : null,
|
||||||
ApiMapping.Local(copy.StateChangedAt ?? copy.CopiedAt, now, zone),
|
ApiMapping.Local(copy.StateChangedAt ?? copy.CopiedAt, now, zone),
|
||||||
own ? null : copy.AccountId is { } other && Usernames.TryGetValue(other, out var name) ? name : null,
|
own ? null : copy.AccountId is { } other && Usernames.TryGetValue(other, out var name) ? name : null,
|
||||||
canCopyAgain));
|
canCopyAgain,
|
||||||
|
copy.FrameAt is { } frameAt ? ExportFrames.Label(frameAt) : null,
|
||||||
|
copy.State == ExportCopyState.Failed ? copy.LastError : null));
|
||||||
if (shown.Count == MaxShown)
|
if (shown.Count == MaxShown)
|
||||||
{
|
{
|
||||||
break;
|
break;
|
||||||
@@ -436,6 +484,30 @@ public static class LibraryApi
|
|||||||
/// Febe does not decode, a HEIC or a picture over the limit is told from its first bytes, without reading it whole.
|
/// Febe does not decode, a HEIC or a picture over the limit is told from its first bytes, without reading it whole.
|
||||||
/// The file is only read, never touched (rule 12).
|
/// The file is only read, never touched (rule 12).
|
||||||
/// </summary>
|
/// </summary>
|
||||||
|
private static readonly TimeSpan FramesProbeTime = TimeSpan.FromSeconds(3);
|
||||||
|
|
||||||
|
/// <summary>Whether «Fotogramma» works on a video on disk; null for a photo, a missing file or a slow probe.</summary>
|
||||||
|
private static async Task<bool?> FramesAvailableAsync(FrameService? frames, Media media, string? path, CancellationToken ct)
|
||||||
|
{
|
||||||
|
if (frames is null || media.Kind != MediaKind.Video || path is null)
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
return (await frames.InfoAsync(path, media.Sha256, ct).WaitAsync(FramesProbeTime, ct).ConfigureAwait(false)).Available;
|
||||||
|
}
|
||||||
|
catch (TimeoutException)
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private static async Task<bool> IsDamagedAsync(Media media, string? path, CancellationToken ct) =>
|
private static async Task<bool> IsDamagedAsync(Media media, string? path, CancellationToken ct) =>
|
||||||
media.Kind == MediaKind.Photo && !media.HasThumbnail && path is not null && await DamagedImage.IsFileDamagedAsync(path, ct).ConfigureAwait(false);
|
media.Kind == MediaKind.Photo && !media.HasThumbnail && path is not null && await DamagedImage.IsFileDamagedAsync(path, ct).ConfigureAwait(false);
|
||||||
|
|
||||||
|
|||||||
@@ -390,12 +390,28 @@ public sealed class DemoShell(IHttpContextAccessor accessor, string root) : INat
|
|||||||
public Task SetAutostartAsync(bool enabled, CancellationToken ct) => Task.CompletedTask;
|
public Task SetAutostartAsync(bool enabled, CancellationToken ct) => Task.CompletedTask;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>Files of the demo: the shared sample pictures. Videos have only their cover.</summary>
|
/// <summary>Files of the demo: the shared sample pictures, and one short video for every video (tappa E3).</summary>
|
||||||
public sealed class DemoFileResolver(DemoWorld world) : IMediaFileResolver
|
public sealed class DemoFileResolver(DemoWorld world) : IMediaFileResolver
|
||||||
{
|
{
|
||||||
public string? Resolve(Account account, Media media)
|
public string? Resolve(Account account, Media media)
|
||||||
{
|
{
|
||||||
ArgumentNullException.ThrowIfNull(media);
|
ArgumentNullException.ThrowIfNull(media);
|
||||||
return media.Kind == MediaKind.Photo && media.Sha256 is { } sha && world.Pictures.TryGetValue(sha, out var path) && File.Exists(path) ? path : null;
|
return media.Kind switch
|
||||||
|
{
|
||||||
|
MediaKind.Photo => media.Sha256 is { } sha && world.Pictures.TryGetValue(sha, out var path) && File.Exists(path) ? path : null,
|
||||||
|
MediaKind.Video => world.VideoFile is { } video && File.Exists(video) ? video : null,
|
||||||
|
_ => null,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The converted files of the demo's library: the rows <see cref="DemoExport"/> seeded (tappa E3).</summary>
|
||||||
|
public sealed class DemoConversionFileResolver(DemoWorld world) : IConversionFileResolver
|
||||||
|
{
|
||||||
|
public string? Resolve(Account account, MediaConversion conversion)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(conversion);
|
||||||
|
return conversion.State is MediaConversionState.Converted or MediaConversionState.Superseded
|
||||||
|
&& world.ConversionFiles.TryGetValue(conversion.Id, out var path) && File.Exists(path) ? path : null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,4 +1,6 @@
|
|||||||
|
using System.Security.Cryptography;
|
||||||
using Febe.Core.Abstractions;
|
using Febe.Core.Abstractions;
|
||||||
|
using Febe.Core.Codecs.Images;
|
||||||
using Febe.Core.Domain;
|
using Febe.Core.Domain;
|
||||||
using Febe.Core.Export;
|
using Febe.Core.Export;
|
||||||
using Febe.Core.Library;
|
using Febe.Core.Library;
|
||||||
@@ -11,7 +13,8 @@ namespace Febe.Web.Demo;
|
|||||||
/// The copies to external folders of the demo (spec §10.6, tappa E2): a general folder «Disco USB», an own folder
|
/// The copies to external folders of the demo (spec §10.6, tappa E2): a general folder «Disco USB», an own folder
|
||||||
/// «Studio Lumen» for @studio.lumen.demo, @il.porto.demo not exported, and for @marta.demo about two thirds of its
|
/// «Studio Lumen» for @studio.lumen.demo, @il.porto.demo not exported, and for @marta.demo about two thirds of its
|
||||||
/// photos copied by the real engine (a completed job with its report), one «Tolto», one «Superato» and one «Errore»,
|
/// photos copied by the real engine (a completed job with its report), one «Tolto», one «Superato» and one «Errore»,
|
||||||
/// and a job left «interrotto» for the Dashboard. Everything lives in the demo's temporary folder, whose «esporta» is
|
/// and a job left «interrotto» for the Dashboard; tappa E3 adds a copy converted to PNG, a frame of a video and two
|
||||||
|
/// conversions of the library («Convertito», «Non si converte»). Everything lives in the demo's temporary folder, whose «esporta» is
|
||||||
/// the demo's <c>/esporta</c>: the counts, the marks and the «Copie» filter come from the same rows the engine wrote.
|
/// the demo's <c>/esporta</c>: the counts, the marks and the «Copie» filter come from the same rows the engine wrote.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public static class DemoExport
|
public static class DemoExport
|
||||||
@@ -117,6 +120,179 @@ public static class DemoExport
|
|||||||
}
|
}
|
||||||
|
|
||||||
await HistoryAsync(database, world, general, marta, photos, rest, clock, ct).ConfigureAwait(false);
|
await HistoryAsync(database, world, general, marta, photos, rest, clock, ct).ConfigureAwait(false);
|
||||||
|
|
||||||
|
// Tappa E3: a converted copy by the real engine (PNG, «Copia in…» → «Cambia»), a frame and two conversions.
|
||||||
|
if (rest.Skip(FormatsFrom).FirstOrDefault() is { } toConvert)
|
||||||
|
{
|
||||||
|
await service.StartAsync(
|
||||||
|
new ExportJobRequest(new ExportSelection.Media([toConvert.Id]), Formats: new ExportFormatChoice(ExportFormat.Png, null)),
|
||||||
|
ct).ConfigureAwait(false);
|
||||||
|
await service.WaitAsync(ct).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
await FrameAsync(database, world, general, marta, clock, ct).ConfigureAwait(false);
|
||||||
|
await ConversionsAsync(root, database, world, [.. rest.Skip(FormatsFrom + 1).Take(2)], clock, ct).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The instant the demo's frame copy was asked at; the demo video shows its 10th picture then (1.125 s).</summary>
|
||||||
|
public static readonly TimeSpan FrameAsked = TimeSpan.FromMilliseconds(1234);
|
||||||
|
|
||||||
|
// rest[0..2] are «Tolto», «Superato» and «Errore», rest[3..14] the interrupted job.
|
||||||
|
private const int FormatsFrom = 15;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// A frame of a video of @marta.demo in the general folder, as «Fotogrammi…» → «Nella cartella delle copie» writes it:
|
||||||
|
/// the demo shares one video file whose SHA-256 is not the one recorded, so the engine would refuse it (rule: the
|
||||||
|
/// frames are of the file recorded); the row and its PNG are written here.
|
||||||
|
/// </summary>
|
||||||
|
private static async Task FrameAsync(FebeDatabase database, DemoWorld world, ExportDestination general, Account marta, IClock clock, CancellationToken ct)
|
||||||
|
{
|
||||||
|
if (world.VideoFile is not { } videoFile || !File.Exists(videoFile)
|
||||||
|
|| await VideoAsync(database, marta, ct).ConfigureAwait(false) is not { } video
|
||||||
|
|| await database.Entries.GetAsync(video.EntryId, ct).ConfigureAwait(false) is not { } entry)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
byte[] png;
|
||||||
|
TimeSpan actual;
|
||||||
|
await using (var stream = File.OpenRead(videoFile))
|
||||||
|
{
|
||||||
|
using var reader = VideoFrameReader.Open(stream, out var info);
|
||||||
|
if (!info.Available)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
var target = reader.Locate([FrameAsked])[0];
|
||||||
|
using var frame = reader.Decode([target], ct).Single();
|
||||||
|
png = ImageConverter.Encode(frame.Image, ImageFormat.Png, null);
|
||||||
|
actual = TimeSpan.FromMilliseconds(ExportFrames.ActualMs(target.Actual));
|
||||||
|
}
|
||||||
|
|
||||||
|
var suffix = ExportFrames.Suffix(FrameMode.At, actual, 0, 1);
|
||||||
|
var segments = ExportPaths.Segments(general, LibraryNaming.Default, marta, entry, video, null, false, world.Zone, new ExportNameOptions(".png", suffix));
|
||||||
|
var relative = ExportPaths.RelativePathFor(general, segments, keepSuffix: suffix);
|
||||||
|
var framePath = Path.Combine(general.RootPath, LibraryLayout.ToPlatform(relative));
|
||||||
|
Directory.CreateDirectory(Path.GetDirectoryName(framePath)!);
|
||||||
|
await using (var output = new FileStream(framePath, FileMode.CreateNew, FileAccess.Write))
|
||||||
|
{
|
||||||
|
await output.WriteAsync(png, ct).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
await database.Exports.AddCopyAsync(
|
||||||
|
new ExportCopy
|
||||||
|
{
|
||||||
|
DestinationId = general.Id,
|
||||||
|
AccountId = marta.Id,
|
||||||
|
MediaId = video.Id,
|
||||||
|
SourceSha256 = video.Sha256!,
|
||||||
|
Variant = ExportVariant.Frame,
|
||||||
|
Format = ExportFormat.Png,
|
||||||
|
FrameAt = actual,
|
||||||
|
State = ExportCopyState.Copied,
|
||||||
|
RelativePath = relative,
|
||||||
|
Bytes = png.Length,
|
||||||
|
CopySha256 = Convert.ToHexStringLower(SHA256.HashData(png)),
|
||||||
|
CopiedAt = clock.Now.AddDays(-1),
|
||||||
|
},
|
||||||
|
ct).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Two conversions of the library (spec §4.10): a PNG next to its original («Convertito», its file in the demo's
|
||||||
|
/// «convertiti» folder) and one that never converts («Non si converte»). The demo never runs the conversion.
|
||||||
|
/// </summary>
|
||||||
|
private static async Task ConversionsAsync(string root, FebeDatabase database, DemoWorld world, IReadOnlyList<Media> photos, IClock clock, CancellationToken ct)
|
||||||
|
{
|
||||||
|
var now = clock.Now;
|
||||||
|
if (photos.Count > 0 && photos[0] is { Sha256: { } sha, RelativePath: { } original } converted
|
||||||
|
&& world.Pictures.TryGetValue(sha, out var source) && File.Exists(source))
|
||||||
|
{
|
||||||
|
var result = await Task.Run(() => ImageConverter.Convert(File.ReadAllBytes(source), ImageFormat.Png), ct).ConfigureAwait(false);
|
||||||
|
var folder = Path.Combine(root, "convertiti");
|
||||||
|
Directory.CreateDirectory(folder);
|
||||||
|
var file = Path.Combine(folder, sha + ".png");
|
||||||
|
await File.WriteAllBytesAsync(file, result.Data, ct).ConfigureAwait(false);
|
||||||
|
var row = await database.Conversions.AddAsync(
|
||||||
|
new MediaConversion
|
||||||
|
{
|
||||||
|
MediaId = converted.Id,
|
||||||
|
Format = ExportFormat.Png,
|
||||||
|
State = MediaConversionState.Converted,
|
||||||
|
SourceSha256 = sha,
|
||||||
|
RelativePath = Path.ChangeExtension(original, ".png"),
|
||||||
|
Bytes = result.Data.Length,
|
||||||
|
Sha256 = Convert.ToHexStringLower(SHA256.HashData(result.Data)),
|
||||||
|
CreatedAt = now.AddDays(-4),
|
||||||
|
ConvertedAt = now.AddDays(-4),
|
||||||
|
StateChangedAt = now.AddDays(-4),
|
||||||
|
LastError = ExportText.JoinNotes([.. result.NotCarried, .. result.Losses]),
|
||||||
|
},
|
||||||
|
ct).ConfigureAwait(false);
|
||||||
|
world.ConversionFiles[row.Id] = file;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (photos.Count > 1 && photos[1].Sha256 is { } asIsSha)
|
||||||
|
{
|
||||||
|
await database.Conversions.AddAsync(
|
||||||
|
new MediaConversion
|
||||||
|
{
|
||||||
|
MediaId = photos[1].Id,
|
||||||
|
Format = ExportFormat.Png,
|
||||||
|
State = MediaConversionState.Failed,
|
||||||
|
SourceSha256 = asIsSha,
|
||||||
|
CreatedAt = now.AddDays(-4),
|
||||||
|
StateChangedAt = now.AddDays(-4),
|
||||||
|
LastError = ImageConversionLosses.AsIsAnimated,
|
||||||
|
},
|
||||||
|
ct).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// A present video of an account whose SHA-256 the fewest files share (the demo's videos take the SHA-256 of their
|
||||||
|
/// cover picture, and the marks of the copies go by SHA-256): the newest among those.
|
||||||
|
/// </summary>
|
||||||
|
private static async Task<Media?> VideoAsync(FebeDatabase database, Account account, CancellationToken ct)
|
||||||
|
{
|
||||||
|
var files = new Dictionary<string, int>(StringComparer.Ordinal);
|
||||||
|
var videos = new List<long>();
|
||||||
|
LibraryCursor? cursor = null;
|
||||||
|
do
|
||||||
|
{
|
||||||
|
var page = await database.Entries.QueryLibraryAsync(
|
||||||
|
new LibraryQuery { Filter = new LibraryFilter { AccountIds = [account.Id] }, Mode = MosaicMode.Files, Cursor = cursor, Limit = 500 },
|
||||||
|
ct).ConfigureAwait(false);
|
||||||
|
foreach (var tile in page.Tiles)
|
||||||
|
{
|
||||||
|
if (tile.CoverSha256 is { } sha)
|
||||||
|
{
|
||||||
|
files[sha] = files.GetValueOrDefault(sha) + 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (tile.CoverKind == MediaKind.Video && tile.CoverMediaId is { } id)
|
||||||
|
{
|
||||||
|
videos.Add(id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
cursor = page.Older;
|
||||||
|
}
|
||||||
|
while (cursor is not null);
|
||||||
|
|
||||||
|
Media? best = null;
|
||||||
|
foreach (var id in videos)
|
||||||
|
{
|
||||||
|
if (await database.Media.GetAsync(id, ct).ConfigureAwait(false) is { Sha256: { } sha, RelativePath: not null } media
|
||||||
|
&& EntryStateRules.IsPresent(media.State)
|
||||||
|
&& (best is null || files.GetValueOrDefault(sha) < files.GetValueOrDefault(best.Sha256!)))
|
||||||
|
{
|
||||||
|
best = media;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return best;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>One «Tolto», one «Superato» (its old file still in the folder), one «Errore», and a job «interrotto».</summary>
|
/// <summary>One «Tolto», one «Superato» (its old file still in the folder), one «Errore», and a job «interrotto».</summary>
|
||||||
|
|||||||
@@ -99,6 +99,7 @@ public sealed class DemoHost : IAsyncDisposable
|
|||||||
services.AddSingleton<INativeShell>(sp => sp.GetRequiredService<DemoShell>());
|
services.AddSingleton<INativeShell>(sp => sp.GetRequiredService<DemoShell>());
|
||||||
services.AddSingleton<IBrowserWindow>(sp => sp.GetRequiredService<DemoShell>());
|
services.AddSingleton<IBrowserWindow>(sp => sp.GetRequiredService<DemoShell>());
|
||||||
services.AddSingleton<IMediaFileResolver, DemoFileResolver>();
|
services.AddSingleton<IMediaFileResolver, DemoFileResolver>();
|
||||||
|
services.AddSingleton<IConversionFileResolver, DemoConversionFileResolver>();
|
||||||
services.AddSingleton<IConfigurationProblems, DemoConfigurationProblems>();
|
services.AddSingleton<IConfigurationProblems, DemoConfigurationProblems>();
|
||||||
services.AddSingleton<IConnectionService, DemoConnectionService>();
|
services.AddSingleton<IConnectionService, DemoConnectionService>();
|
||||||
services.AddSingleton<IBrowserPreview, DemoBrowserPreview>();
|
services.AddSingleton<IBrowserPreview, DemoBrowserPreview>();
|
||||||
|
|||||||
@@ -1,6 +1,8 @@
|
|||||||
|
using System.Collections.Concurrent;
|
||||||
using System.Globalization;
|
using System.Globalization;
|
||||||
using System.Security.Cryptography;
|
using System.Security.Cryptography;
|
||||||
using Febe.Core.Abstractions;
|
using Febe.Core.Abstractions;
|
||||||
|
using Febe.Core.Codecs.H264;
|
||||||
using Febe.Core.Domain;
|
using Febe.Core.Domain;
|
||||||
using Febe.Core.Library;
|
using Febe.Core.Library;
|
||||||
using Febe.Core.Storage;
|
using Febe.Core.Storage;
|
||||||
@@ -64,6 +66,15 @@ public sealed class DemoWorld
|
|||||||
|
|
||||||
/// <summary>Sample pictures in the proportions of a story (the browser preview of the demo).</summary>
|
/// <summary>Sample pictures in the proportions of a story (the browser preview of the demo).</summary>
|
||||||
public IReadOnlyList<string> StoryPictures { get; init; } = [];
|
public IReadOnlyList<string> StoryPictures { get; init; } = [];
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 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).
|
||||||
|
/// </summary>
|
||||||
|
public string? VideoFile { get; init; }
|
||||||
|
|
||||||
|
/// <summary>The files of the seeded conversions of the library, by row id (written by <see cref="DemoExport"/>).</summary>
|
||||||
|
public ConcurrentDictionary<long, string> ConversionFiles { get; } = new();
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -583,8 +594,11 @@ public static class DemoSeeder
|
|||||||
|
|
||||||
var mine = accounts.First(a => a.Spec.Mine).Account;
|
var mine = accounts.First(a => a.Spec.Mine).Account;
|
||||||
var variants = await DemoDuplicates.SeedAsync(storage, thumbnails, pictures, now, ct).ConfigureAwait(false);
|
var variants = await DemoDuplicates.SeedAsync(storage, thumbnails, pictures, now, ct).ConfigureAwait(false);
|
||||||
|
var videoFile = Path.Combine(pictures, "video-dimostrativo.mp4");
|
||||||
|
await File.WriteAllBytesAsync(videoFile, await Task.Run(H264PcmWriter.DemoVideo, ct).ConfigureAwait(false), ct).ConfigureAwait(false);
|
||||||
return new DemoWorld
|
return new DemoWorld
|
||||||
{
|
{
|
||||||
|
VideoFile = videoFile,
|
||||||
SeededAt = now,
|
SeededAt = now,
|
||||||
Zone = zone,
|
Zone = zone,
|
||||||
Pictures = pool.Files.Concat(variants).ToDictionary(p => p.Key, p => p.Value, StringComparer.Ordinal),
|
Pictures = pool.Files.Concat(variants).ToDictionary(p => p.Key, p => p.Value, StringComparer.Ordinal),
|
||||||
|
|||||||
@@ -0,0 +1,471 @@
|
|||||||
|
using System.Collections.Concurrent;
|
||||||
|
using System.Globalization;
|
||||||
|
using System.IO.Compression;
|
||||||
|
using System.Security.Cryptography;
|
||||||
|
using Febe.Core.Abstractions;
|
||||||
|
using Febe.Core.Codecs.Images;
|
||||||
|
using Febe.Core.Domain;
|
||||||
|
using Febe.Core.Export;
|
||||||
|
using Febe.Core.Library;
|
||||||
|
using Febe.Core.Library.Conversion;
|
||||||
|
using Febe.Web.Api;
|
||||||
|
|
||||||
|
namespace Febe.Web.Export;
|
||||||
|
|
||||||
|
/// <summary>A frame encoded for the page: its bytes, media type, extension and the instant really shown.</summary>
|
||||||
|
public sealed record EncodedFrame(byte[] Data, string ContentType, string Extension, TimeSpan Actual);
|
||||||
|
|
||||||
|
/// <summary>The frames of one video in a download: where it is, its account and name, and the instants asked.</summary>
|
||||||
|
/// <param name="Username">The account (first segment of the zip entries).</param>
|
||||||
|
/// <param name="Path">The library file.</param>
|
||||||
|
/// <param name="Stem">The library file name without extension.</param>
|
||||||
|
/// <param name="Instants">The instants asked, in increasing order.</param>
|
||||||
|
/// <param name="PublishedAt">When the entry was published (the time of the zip entries, D18).</param>
|
||||||
|
public sealed record FrameDownloadVideo(string Username, string Path, string Stem, IReadOnlyList<TimeSpan> Instants, DateTimeOffset PublishedAt);
|
||||||
|
|
||||||
|
/// <summary>A «Scarica» of frames waiting for its address to be opened.</summary>
|
||||||
|
public sealed record FrameDownloadPlan(FrameMode Mode, ExportFormat Format, IReadOnlyList<FrameDownloadVideo> Videos)
|
||||||
|
{
|
||||||
|
/// <summary>The frames in all.</summary>
|
||||||
|
public int Frames => Videos.Sum(v => v.Instants.Count);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Frames of videos for the page (spec §4.10 «Fotogrammi», tappa E3, D14): what a video allows (kept for 64 files by
|
||||||
|
/// SHA-256), a single frame for the previews and «Scarica», and the zip of several. Previews and single frames go one at
|
||||||
|
/// a time (one decoder busy, never a queue of heavy work) within <see cref="Budget"/>; they are not long work and run at
|
||||||
|
/// any time. A zip of up to <see cref="MaxAnyTime"/> frames runs at any time too; from 21 to <see cref="MaxDownload"/>
|
||||||
|
/// it takes <see cref="LongWorkKind.FrameDownload"/> and never runs during an engine session. Nothing here writes a
|
||||||
|
/// file: the frames go to the page only.
|
||||||
|
/// </summary>
|
||||||
|
public sealed class FrameService(IClock clock)
|
||||||
|
{
|
||||||
|
/// <summary>The longest side of a preview.</summary>
|
||||||
|
public const int MaxPreview = 480;
|
||||||
|
|
||||||
|
/// <summary>The most frames of a zip at any time.</summary>
|
||||||
|
public const int MaxAnyTime = 20;
|
||||||
|
|
||||||
|
/// <summary>The most frames of «Scarica».</summary>
|
||||||
|
public const int MaxDownload = 500;
|
||||||
|
|
||||||
|
/// <summary>Video infos kept.</summary>
|
||||||
|
public const int CacheSize = 64;
|
||||||
|
|
||||||
|
public const string TimeoutText = "Il fotogramma richiede troppo tempo: scegli la cartella delle copie";
|
||||||
|
|
||||||
|
public const string SessionText = "Il motore è in sessione: per più di 20 fotogrammi riprova fra poco";
|
||||||
|
|
||||||
|
public const string TooManyText = "Per più di 500 fotogrammi scegli la cartella delle copie";
|
||||||
|
|
||||||
|
public const string NothingText = "Nessun fotogramma da scaricare: scegli dei video con i fotogrammi disponibili.";
|
||||||
|
|
||||||
|
private static readonly TimeSpan TokenLife = TimeSpan.FromMinutes(5);
|
||||||
|
|
||||||
|
private readonly SemaphoreSlim _one = new(1, 1);
|
||||||
|
private readonly Lock _cacheGate = new();
|
||||||
|
private readonly Dictionary<string, (VideoFrameInfo Info, long Used)> _cache = new(StringComparer.Ordinal);
|
||||||
|
private readonly ConcurrentDictionary<string, (FrameDownloadPlan Plan, DateTimeOffset Expires)> _tokens = new(StringComparer.Ordinal);
|
||||||
|
private long _uses;
|
||||||
|
|
||||||
|
/// <summary>The time a preview or a single frame may take, waiting included.</summary>
|
||||||
|
public TimeSpan Budget { get; init; } = TimeSpan.FromSeconds(30);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// A write of the zip that makes no progress for this long aborts the download: each piece of 64 KB sent restarts
|
||||||
|
/// the time, so a slow link that keeps reading is never cut.
|
||||||
|
/// </summary>
|
||||||
|
public TimeSpan WriteStall { get; init; } = TimeSpan.FromSeconds(60);
|
||||||
|
|
||||||
|
/// <summary>The timers of <see cref="WriteStall"/> (a seam: a test moves their time only as its link sends).</summary>
|
||||||
|
public TimeProvider StallTime { get; init; } = TimeProvider.System;
|
||||||
|
|
||||||
|
/// <summary>What a video allows, from the cache by SHA-256 when known (the file is opened only the first time).</summary>
|
||||||
|
public async Task<VideoFrameInfo> InfoAsync(string path, string? sha256, CancellationToken ct)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(path);
|
||||||
|
if (sha256 is { Length: > 0 } && Cached(sha256) is { } cached)
|
||||||
|
{
|
||||||
|
return cached;
|
||||||
|
}
|
||||||
|
|
||||||
|
var info = await Task.Run(
|
||||||
|
() =>
|
||||||
|
{
|
||||||
|
using var stream = OpenRead(path);
|
||||||
|
using var reader = VideoFrameReader.Open(stream, out var found);
|
||||||
|
return found;
|
||||||
|
},
|
||||||
|
ct).ConfigureAwait(false);
|
||||||
|
if (sha256 is { Length: > 0 })
|
||||||
|
{
|
||||||
|
Remember(sha256, info);
|
||||||
|
}
|
||||||
|
|
||||||
|
return info;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The instants of <paramref name="request"/> for the video at <paramref name="path"/> with the samples really shown;
|
||||||
|
/// empty when the video has no frames. <see cref="ArgumentException"/> over 1.000 frames.
|
||||||
|
/// </summary>
|
||||||
|
public Task<(VideoFrameInfo Info, IReadOnlyList<VideoFrameTarget> Targets)> LocateAsync(string path, string? sha256, ExportFramesRequest request, CancellationToken ct)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(path);
|
||||||
|
ArgumentNullException.ThrowIfNull(request);
|
||||||
|
return Task.Run(
|
||||||
|
() =>
|
||||||
|
{
|
||||||
|
using var stream = OpenRead(path);
|
||||||
|
using var reader = VideoFrameReader.Open(stream, out var info);
|
||||||
|
if (sha256 is { Length: > 0 })
|
||||||
|
{
|
||||||
|
Remember(sha256, info);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!info.Available)
|
||||||
|
{
|
||||||
|
return (info, (IReadOnlyList<VideoFrameTarget>)[]);
|
||||||
|
}
|
||||||
|
|
||||||
|
var instants = ExportFrames.Instants(info.Duration, request);
|
||||||
|
return (info, reader.Locate(instants));
|
||||||
|
},
|
||||||
|
ct);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The frame shown at <paramref name="at"/>, encoded in <paramref name="format"/>; with <paramref name="maxSide"/>
|
||||||
|
/// scaled down to fit it (a preview). One at a time, within <see cref="Budget"/>: past it
|
||||||
|
/// <see cref="ApiStatusException"/> 503. <see cref="NotFoundException"/> when the video has no frames.
|
||||||
|
/// </summary>
|
||||||
|
public async Task<EncodedFrame> FrameAsync(string path, string? sha256, TimeSpan at, ExportFormat format, int? maxSide, CancellationToken ct)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(path);
|
||||||
|
var image = MediaConverter.ImageFormatOf(format) ?? throw new BadRequestException("I fotogrammi si salvano in JPG, PNG o WEBP senza perdita.");
|
||||||
|
using var budget = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
||||||
|
budget.CancelAfter(Budget);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await _one.WaitAsync(budget.Token).ConfigureAwait(false);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
return await Task.Run(() => Decode(path, sha256, at, image, maxSide, budget.Token), budget.Token).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
_one.Release();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (OperationCanceledException) when (!ct.IsCancellationRequested)
|
||||||
|
{
|
||||||
|
throw new ApiStatusException(503, TimeoutText);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Keeps a download for <see cref="TokenLife"/>, for one use; returns its token.</summary>
|
||||||
|
public string Register(FrameDownloadPlan plan)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(plan);
|
||||||
|
var now = clock.Now;
|
||||||
|
foreach (var (key, value) in _tokens)
|
||||||
|
{
|
||||||
|
if (value.Expires <= now)
|
||||||
|
{
|
||||||
|
_tokens.TryRemove(key, out _);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var token = Convert.ToHexStringLower(RandomNumberGenerator.GetBytes(16));
|
||||||
|
_tokens[token] = (plan, now + TokenLife);
|
||||||
|
return token;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The download of <paramref name="token"/>, taken once; null when unknown, used or expired.</summary>
|
||||||
|
public FrameDownloadPlan? Take(string token)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrEmpty(token) || !_tokens.TryRemove(token, out var found))
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return found.Expires > clock.Now ? found.Plan : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The name of a frame file: the library stem, the suffix of its instant (D13), the format's extension.</summary>
|
||||||
|
public static string FileName(string stem, FrameMode mode, TimeSpan actual, int index, int count, ExportFormat format) =>
|
||||||
|
WindowsFileNames.SanitizeSegment(stem + ExportFrames.Suffix(mode, actual, index, count) + MediaConverter.ExtensionOf(format));
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Writes the zip of <paramref name="plan"/> into <paramref name="output"/> as it is made (not compressed: the
|
||||||
|
/// images are), entries <c>account/name</c> unique as the copies number them («x (2).png»), dated per
|
||||||
|
/// <paramref name="publicationTime"/> (the publication, else now), within the years a zip can hold.
|
||||||
|
/// </summary>
|
||||||
|
public async Task WriteZipAsync(Stream output, FrameDownloadPlan plan, bool publicationTime, CancellationToken ct)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(output);
|
||||||
|
ArgumentNullException.ThrowIfNull(plan);
|
||||||
|
var image = MediaConverter.ImageFormatOf(plan.Format) ?? throw new ArgumentException("Formato del fotogramma non valido.", nameof(plan));
|
||||||
|
var guarded = new StallGuardStream(output, WriteStall, StallTime);
|
||||||
|
var names = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||||
|
var zip = await ZipArchive.CreateAsync(guarded, ZipArchiveMode.Create, leaveOpen: true, entryNameEncoding: null, ct).ConfigureAwait(false);
|
||||||
|
await using (zip.ConfigureAwait(false))
|
||||||
|
{
|
||||||
|
foreach (var video in plan.Videos)
|
||||||
|
{
|
||||||
|
var folder = WindowsFileNames.SanitizeSegment(video.Username);
|
||||||
|
var time = EntryTime(publicationTime ? video.PublishedAt : clock.Now);
|
||||||
|
await foreach (var (index, frame) in FramesAsync(video, plan, image, ct).ConfigureAwait(false))
|
||||||
|
{
|
||||||
|
var name = FileName(video.Stem, plan.Mode, frame.Actual, index, video.Instants.Count, plan.Format);
|
||||||
|
var relative = folder + "/" + name;
|
||||||
|
var suffix = ExportFrames.Suffix(plan.Mode, frame.Actual, index, video.Instants.Count);
|
||||||
|
for (var attempt = 2; !names.Add(relative); attempt++)
|
||||||
|
{
|
||||||
|
relative = ExportPaths.NumberedName("febe", folder + "/" + name, attempt, keepSuffix: suffix);
|
||||||
|
}
|
||||||
|
|
||||||
|
var entry = zip.CreateEntry(relative, CompressionLevel.NoCompression);
|
||||||
|
entry.LastWriteTime = time;
|
||||||
|
var stream = await entry.OpenAsync(ct).ConfigureAwait(false);
|
||||||
|
await using (stream.ConfigureAwait(false))
|
||||||
|
{
|
||||||
|
await stream.WriteAsync(frame.Data, ct).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
await guarded.CompleteAsync(ct).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The frames of one video of a download, encoded, in decoding order, with their index among its instants.</summary>
|
||||||
|
public async IAsyncEnumerable<(int Index, EncodedFrame Frame)> FramesAsync(FrameDownloadVideo video, FrameDownloadPlan plan, ImageFormat image, [System.Runtime.CompilerServices.EnumeratorCancellation] CancellationToken ct)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(video);
|
||||||
|
ArgumentNullException.ThrowIfNull(plan);
|
||||||
|
Stream stream;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
stream = OpenRead(video.Path);
|
||||||
|
}
|
||||||
|
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||||
|
{
|
||||||
|
yield break; // the file went since the plan: its frames are left out
|
||||||
|
}
|
||||||
|
|
||||||
|
await using (stream.ConfigureAwait(false))
|
||||||
|
{
|
||||||
|
var (reader, info) = await Task.Run(() => (VideoFrameReader.Open(stream, out var found), found), ct).ConfigureAwait(false);
|
||||||
|
using (reader)
|
||||||
|
{
|
||||||
|
if (!info.Available)
|
||||||
|
{
|
||||||
|
yield break;
|
||||||
|
}
|
||||||
|
|
||||||
|
var targets = reader.Locate(video.Instants);
|
||||||
|
using var frames = reader.Decode(targets, ct).GetEnumerator();
|
||||||
|
var shown = new HashSet<long>();
|
||||||
|
while (await Task.Run(() => frames.MoveNext(), ct).ConfigureAwait(false))
|
||||||
|
{
|
||||||
|
using var frame = frames.Current;
|
||||||
|
if (!shown.Add(frame.Actual.Ticks))
|
||||||
|
{
|
||||||
|
continue; // two instants on the same picture give it once, as the copies do
|
||||||
|
}
|
||||||
|
|
||||||
|
var data = await Task.Run(() => ImageConverter.Encode(frame.Image, image, null), ct).ConfigureAwait(false);
|
||||||
|
yield return (frame.Index, new EncodedFrame(data, ContentType(image), MediaConverter.ExtensionOf(plan.Format), frame.Actual));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The media type of an image format written by Febe.</summary>
|
||||||
|
public static string ContentType(ImageFormat format) => format switch
|
||||||
|
{
|
||||||
|
ImageFormat.Jpeg => "image/jpeg",
|
||||||
|
ImageFormat.Png => "image/png",
|
||||||
|
_ => "image/webp",
|
||||||
|
};
|
||||||
|
|
||||||
|
private EncodedFrame Decode(string path, string? sha256, TimeSpan at, ImageFormat image, int? maxSide, CancellationToken ct)
|
||||||
|
{
|
||||||
|
using var stream = OpenRead(path);
|
||||||
|
using var reader = VideoFrameReader.Open(stream, out var info);
|
||||||
|
if (sha256 is { Length: > 0 })
|
||||||
|
{
|
||||||
|
Remember(sha256, info);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!info.Available)
|
||||||
|
{
|
||||||
|
throw new NotFoundException(info.Unavailable ?? VideoFrameReader.NotAvailableMessage);
|
||||||
|
}
|
||||||
|
|
||||||
|
var targets = reader.Locate([at]);
|
||||||
|
using var frame = reader.Decode(targets, ct).FirstOrDefault() ?? throw new NotFoundException(VideoFrameReader.NotAvailableMessage);
|
||||||
|
ct.ThrowIfCancellationRequested();
|
||||||
|
var source = frame.Image;
|
||||||
|
if (maxSide is { } max && Math.Max(source.Width, source.Height) > max)
|
||||||
|
{
|
||||||
|
var (width, height) = ImageResampler.FitWithin(source.Width, source.Height, max);
|
||||||
|
using var small = ImageResampler.Resize(source, width, height);
|
||||||
|
return new EncodedFrame(ImageConverter.Encode(small, image, null), ContentType(image), Extension(image), frame.Actual);
|
||||||
|
}
|
||||||
|
|
||||||
|
return new EncodedFrame(ImageConverter.Encode(source, image, null), ContentType(image), Extension(image), frame.Actual);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string Extension(ImageFormat image) => image switch
|
||||||
|
{
|
||||||
|
ImageFormat.Jpeg => ".jpg",
|
||||||
|
ImageFormat.Png => ".png",
|
||||||
|
_ => ".webp",
|
||||||
|
};
|
||||||
|
|
||||||
|
/// <summary>The time of a zip entry: within 1980-2107, the years a zip can hold.</summary>
|
||||||
|
private DateTimeOffset EntryTime(DateTimeOffset instant)
|
||||||
|
{
|
||||||
|
var local = TimeZoneInfo.ConvertTime(instant, clock.LocalZone);
|
||||||
|
var min = new DateTimeOffset(1980, 1, 1, 0, 0, 0, local.Offset);
|
||||||
|
var max = new DateTimeOffset(2107, 12, 31, 23, 59, 58, local.Offset);
|
||||||
|
return local < min ? min : local > max ? max : local;
|
||||||
|
}
|
||||||
|
|
||||||
|
private VideoFrameInfo? Cached(string sha256)
|
||||||
|
{
|
||||||
|
lock (_cacheGate)
|
||||||
|
{
|
||||||
|
if (_cache.TryGetValue(sha256, out var found))
|
||||||
|
{
|
||||||
|
_cache[sha256] = (found.Info, ++_uses);
|
||||||
|
return found.Info;
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void Remember(string sha256, VideoFrameInfo info)
|
||||||
|
{
|
||||||
|
lock (_cacheGate)
|
||||||
|
{
|
||||||
|
_cache[sha256] = (info, ++_uses);
|
||||||
|
if (_cache.Count > CacheSize)
|
||||||
|
{
|
||||||
|
var oldest = _cache.MinBy(p => p.Value.Used).Key;
|
||||||
|
_cache.Remove(oldest);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static FileStream OpenRead(string path) =>
|
||||||
|
new(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete, 128 * 1024, FileOptions.RandomAccess);
|
||||||
|
|
||||||
|
internal static string Day(DateTimeOffset now, TimeZoneInfo zone) =>
|
||||||
|
LocalCalendar.Today(now, zone).ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// A write-only stream that gives up a write making no progress for a while (the page stopped reading). The zip of
|
||||||
|
/// .NET 10 writes the small data descriptor of each entry synchronously even through its asynchronous API: those
|
||||||
|
/// bytes are kept here and sent with the next asynchronous write, so the response never sees a synchronous write.
|
||||||
|
/// </summary>
|
||||||
|
private sealed class StallGuardStream(Stream inner, TimeSpan stall, TimeProvider time) : Stream
|
||||||
|
{
|
||||||
|
// A data descriptor is 16 or 24 bytes; anything far larger written synchronously is a change of the BCL.
|
||||||
|
private const int MaxPending = 64 * 1024;
|
||||||
|
|
||||||
|
// The bytes of one guarded write: the response buffer of Kestrel (64 KB).
|
||||||
|
private const int Piece = 64 * 1024;
|
||||||
|
|
||||||
|
private readonly MemoryStream _pending = new();
|
||||||
|
private long _position;
|
||||||
|
|
||||||
|
public override bool CanRead => false;
|
||||||
|
|
||||||
|
public override bool CanSeek => false;
|
||||||
|
|
||||||
|
public override bool CanWrite => true;
|
||||||
|
|
||||||
|
public override long Length => throw new NotSupportedException();
|
||||||
|
|
||||||
|
public override long Position
|
||||||
|
{
|
||||||
|
get => _position;
|
||||||
|
set => throw new NotSupportedException();
|
||||||
|
}
|
||||||
|
|
||||||
|
public override void Flush()
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
public override async Task FlushAsync(CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
await SendPendingAsync(cancellationToken).ConfigureAwait(false);
|
||||||
|
await inner.FlushAsync(cancellationToken).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
public override int Read(byte[] buffer, int offset, int count) => throw new NotSupportedException();
|
||||||
|
|
||||||
|
public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException();
|
||||||
|
|
||||||
|
public override void SetLength(long value) => throw new NotSupportedException();
|
||||||
|
|
||||||
|
public override void Write(byte[] buffer, int offset, int count) => Write(buffer.AsSpan(offset, count));
|
||||||
|
|
||||||
|
public override void Write(ReadOnlySpan<byte> buffer)
|
||||||
|
{
|
||||||
|
if (_pending.Length + buffer.Length > MaxPending)
|
||||||
|
{
|
||||||
|
throw new NotSupportedException("Lo zip dei fotogrammi si scrive solo in modo asincrono.");
|
||||||
|
}
|
||||||
|
|
||||||
|
_pending.Write(buffer);
|
||||||
|
_position += buffer.Length;
|
||||||
|
}
|
||||||
|
|
||||||
|
public override void WriteByte(byte value) => Write([value]);
|
||||||
|
|
||||||
|
public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) =>
|
||||||
|
WriteAsync(buffer.AsMemory(offset, count), cancellationToken).AsTask();
|
||||||
|
|
||||||
|
public override async ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
await SendPendingAsync(cancellationToken).ConfigureAwait(false);
|
||||||
|
await GuardedAsync(buffer, cancellationToken).ConfigureAwait(false);
|
||||||
|
_position += buffer.Length;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Sends what was written synchronously and flushes: call it once the zip is complete.</summary>
|
||||||
|
public Task CompleteAsync(CancellationToken ct) => FlushAsync(ct);
|
||||||
|
|
||||||
|
private async Task SendPendingAsync(CancellationToken ct)
|
||||||
|
{
|
||||||
|
if (_pending.Length == 0)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
var bytes = _pending.ToArray();
|
||||||
|
_pending.SetLength(0);
|
||||||
|
await GuardedAsync(bytes, ct).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Sends <paramref name="buffer"/> in pieces of <see cref="Piece"/> bytes, each with its own time: a frame of
|
||||||
|
/// several megabytes on a slow link keeps going as long as every piece goes (a response write completes only once
|
||||||
|
/// the socket has taken nearly all of it), and stops after <c>stall</c> without one.
|
||||||
|
/// </summary>
|
||||||
|
private async Task GuardedAsync(ReadOnlyMemory<byte> buffer, CancellationToken ct)
|
||||||
|
{
|
||||||
|
for (var offset = 0; offset < buffer.Length; offset += Piece)
|
||||||
|
{
|
||||||
|
using var timer = new CancellationTokenSource(stall, time);
|
||||||
|
using var guard = CancellationTokenSource.CreateLinkedTokenSource(ct, timer.Token);
|
||||||
|
await inner.WriteAsync(buffer.Slice(offset, Math.Min(Piece, buffer.Length - offset)), guard.Token).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -4,6 +4,7 @@ using Febe.Core.Alerts;
|
|||||||
using Febe.Core.Engine;
|
using Febe.Core.Engine;
|
||||||
using Febe.Core.Export;
|
using Febe.Core.Export;
|
||||||
using Febe.Core.Import;
|
using Febe.Core.Import;
|
||||||
|
using Febe.Core.Library.Conversion;
|
||||||
using Febe.Core.Storage;
|
using Febe.Core.Storage;
|
||||||
using Febe.Web.Api;
|
using Febe.Web.Api;
|
||||||
using Febe.Web.Connection;
|
using Febe.Web.Connection;
|
||||||
@@ -90,6 +91,20 @@ public static class FebeWeb
|
|||||||
: ExportRootOptions.AnyFolder);
|
: ExportRootOptions.AnyFolder);
|
||||||
services.TryAddSingleton<IExportDisk>(sp => new SystemExportDisk(sp.GetRequiredService<ExportRootOptions>().Mounts));
|
services.TryAddSingleton<IExportDisk>(sp => new SystemExportDisk(sp.GetRequiredService<ExportRootOptions>().Mounts));
|
||||||
services.TryAddSingleton<ExportHub>();
|
services.TryAddSingleton<ExportHub>();
|
||||||
|
// The conversion of the library (tappa E3): the composition registers the worker it starts; without one (the
|
||||||
|
// demo, the tests) the endpoints get one that never runs, over the same database and gate.
|
||||||
|
services.TryAddSingleton(sp => new LibraryConversionQueue(sp.GetRequiredService<IFebeStorage>(), sp.GetRequiredService<IClock>()));
|
||||||
|
services.TryAddSingleton(sp => new LibraryConversionWorker(new LibraryConversionEnvironment
|
||||||
|
{
|
||||||
|
Storage = sp.GetRequiredService<IFebeStorage>(),
|
||||||
|
Layout = () => sp.GetRequiredService<FebeLibrary>().Layout,
|
||||||
|
Clock = sp.GetRequiredService<IClock>(),
|
||||||
|
Gate = sp.GetRequiredService<LongWorkGate>(),
|
||||||
|
Session = sp.GetRequiredService<IEngineSessionState>(),
|
||||||
|
}));
|
||||||
|
// Frames of videos (tappa E3): previews, single frames, «Scarica» of several in a zip.
|
||||||
|
services.TryAddSingleton<IConversionFileResolver, LibraryConversionFileResolver>();
|
||||||
|
services.TryAddSingleton<FrameService>();
|
||||||
services.AddHttpContextAccessor();
|
services.AddHttpContextAccessor();
|
||||||
if (options.Access == AccessMode.Password && !string.IsNullOrEmpty(options.Password))
|
if (options.Access == AccessMode.Password && !string.IsNullOrEmpty(options.Password))
|
||||||
{
|
{
|
||||||
@@ -152,6 +167,7 @@ public static class FebeWeb
|
|||||||
SettingsApi.Map(endpoints);
|
SettingsApi.Map(endpoints);
|
||||||
ImportApi.Map(endpoints);
|
ImportApi.Map(endpoints);
|
||||||
ExportApi.Map(endpoints);
|
ExportApi.Map(endpoints);
|
||||||
|
FramesApi.Map(endpoints);
|
||||||
DuplicatesApi.Map(endpoints);
|
DuplicatesApi.Map(endpoints);
|
||||||
SearchApi.Map(endpoints);
|
SearchApi.Map(endpoints);
|
||||||
RemoteViewSocket.Map(endpoints);
|
RemoteViewSocket.Map(endpoints);
|
||||||
|
|||||||