E3: correzioni della revisione di formati e fotogrammi

Le 16 osservazioni confermate della revisione, ognuna con la sua prova:

- JPEG: il controllo stima la memoria di lavoro del decodificatore
  (progressivo), così un file che non si decodifica esce «troppo
  grande» e non «illeggibile».
- Un EXIF che non si tiene lascia un EXIF minimo con l'orientamento,
  perché la foto convertita non esca girata.
- Fotogrammi: istanti in millisecondi interi; la copia trova l'indice
  del nome dall'istante, non dall'ordine delle righe.
- Video di durata sconosciuta misurati prima di registrare: contano
  nei limiti di 500 per richiesta e 5000 per video.
- Rimuxaggio: la durata del segmento di elst passa nell'MP4, la fine
  tagliata resta nascosta (anche nei fotogrammi).
- H.264: il punto di recupero vale come IDR solo con exact_match_flag.
- MP3 in MP4: objectTypeIndication 0x69 fino a 24 kHz, 0x6B oltre.
- Conversione della libreria: il lavoro toglie le righe di un formato
  spento o cambiato; spegnere toglie anche i «Non riuscito»; «Riprova»
  solo i formati di adesso; pausa per spazio prima di rileggere
  l'originale.
- «Anche i N» conta e mette in coda solo il tipo che si cambia; le
  impostazioni dell'esportazione si salvano una per volta.
- Eliminazione e «Tieni il più grande» scelgono i convertiti nella
  stessa transazione: nessun convertito orfano.
- Un file arrivato tardi in un elemento vecchio mette in coda solo sé
  (file nuovo = salvato da quando il formato è scelto).
- Zip dei fotogrammi a pezzi di 64 KB: un browser lento che legge non
  si interrompe, uno fermo sì.

Decisioni in docs/decisioni.md (28/11), §4.10 della specifica precisato.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-28 13:30:33 +01:00
1 parent eb79b05fda
commit 958cb71cd6
38 files changed
+1276 -222

No files matched your search

+1 -1
View File
@@ -289,7 +289,7 @@ Decisioni di Alberto del 18 novembre 2026 (issue #58, traguardo «0.3.0 — Espo
- **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. - **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). - **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. - **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 entra in coda dopo la sua riga di `_febe.jsonl`; 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). - **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.**
+6
View File
@@ -647,3 +647,9 @@ Ogni scelta tecnica presa strada facendo, con data e motivo (specifica §15).
| 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: **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: **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 | 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 |
@@ -282,6 +282,7 @@ public static class IsoBmffReader
internal long EditOffset; internal long EditOffset;
internal bool HasEdits; internal bool HasEdits;
internal long EmptyEditMovie; internal long EmptyEditMovie;
internal long EditSegmentMovie;
internal int EditCount; internal int EditCount;
internal string? Language; internal string? Language;
internal int ObjectType; internal int ObjectType;
@@ -417,6 +418,7 @@ public static class IsoBmffReader
leading = false; leading = false;
track.HasEdits = true; track.HasEdits = true;
track.EditOffset = mediaTime; // the first non-empty edit: media time shown at presentation zero 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. // A rate other than 1 (a slowed or still segment) is not an ordinary edit either.
@@ -1040,6 +1042,7 @@ public static class IsoBmffReader
Samples = video.Samples, Samples = video.Samples,
EditMediaTime = video.HasEdits ? video.EditOffset : null, EditMediaTime = video.HasEdits ? video.EditOffset : null,
EmptyEditDuration = EmptyEdit(video), EmptyEditDuration = EmptyEdit(video),
EditSegmentDuration = EditSegment(video),
EditCount = video.EditCount, EditCount = video.EditCount,
Language = video.Language, Language = video.Language,
}; };
@@ -1070,6 +1073,7 @@ public static class IsoBmffReader
Samples = audio.Samples, Samples = audio.Samples,
EditMediaTime = audio.HasEdits ? audio.EditOffset : null, EditMediaTime = audio.HasEdits ? audio.EditOffset : null,
EmptyEditDuration = EmptyEdit(audio), EmptyEditDuration = EmptyEdit(audio),
EditSegmentDuration = EditSegment(audio),
EditCount = audio.EditCount, EditCount = audio.EditCount,
Language = audio.Language, Language = audio.Language,
}; };
@@ -1096,6 +1100,21 @@ public static class IsoBmffReader
}; };
} }
/// <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> /// <summary>The leading empty edits of a track (movie units) in track units, rounded to the nearest.</summary>
private long EmptyEdit(Track track) private long EmptyEdit(Track track)
{ {
@@ -107,6 +107,13 @@ public abstract class MediaTrack
/// </summary> /// </summary>
public long EmptyEditDuration { get; init; } 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> /// <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; } public int EditCount { get; init; }
@@ -267,6 +267,7 @@ public static class Mp4Remuxer
Language = video.Language, Language = video.Language,
EditMediaTime = edit, EditMediaTime = edit,
EmptyEditDuration = video.EmptyEditDuration, EmptyEditDuration = video.EmptyEditDuration,
EditSegmentDuration = video.EditSegmentDuration,
LastSampleDuration = LastDuration(video), LastSampleDuration = LastDuration(video),
}; };
} }
@@ -287,6 +288,7 @@ public static class Mp4Remuxer
Language = audio.Language, Language = audio.Language,
EditMediaTime = edit, EditMediaTime = edit,
EmptyEditDuration = audio.EmptyEditDuration, EmptyEditDuration = audio.EmptyEditDuration,
EditSegmentDuration = audio.EditSegmentDuration,
LastSampleDuration = LastDuration(audio), LastSampleDuration = LastDuration(audio),
}; };
} }
+29 -9
View File
@@ -52,8 +52,8 @@ public sealed class Mp4OutputTrack
public string? SampleEntryType { get; init; } public string? SampleEntryType { get; init; }
/// <summary> /// <summary>
/// MPEG-1/2 audio layer III in an <c>mp4a</c> entry (objectTypeIndication 0x6B, ISO/IEC 14496-1): it has no /// MPEG-1/2 audio layer III in an <c>mp4a</c> entry (objectTypeIndication 0x6B, or 0x69 at 24 kHz and below,
/// AudioSpecificConfig, so <see cref="AacConfiguration"/> stays null. /// ISO/IEC 14496-1): it has no AudioSpecificConfig, so <see cref="AacConfiguration"/> stays null.
/// </summary> /// </summary>
public bool IsMp3 { get; init; } public bool IsMp3 { get; init; }
@@ -66,6 +66,12 @@ public sealed class Mp4OutputTrack
/// <summary>A delayed start in track units: an empty edit before the media (0: none).</summary> /// <summary>A delayed start in track units: an empty edit before the media (0: none).</summary>
public long EmptyEditDuration { get; init; } 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> /// <summary>The dates of the movie header; the modification date falls back to the creation date.</summary>
@@ -264,9 +270,15 @@ public static class Mp4Writer
return new Mp4Layout(tracks, chunks, head, payload); return new Mp4Layout(tracks, chunks, head, payload);
} }
/// <summary>Times of a track as the boxes need them; <paramref name="EmptyEdit"/> is in track units.</summary> /// <summary>
private sealed record Timing(long[] Durations, int[] CompositionOffsets, long MediaDuration, long EditMediaTime, bool AllKey, long EmptyEdit) /// Times of a track as the boxes need them; <paramref name="EmptyEdit"/> and <paramref name="Shown"/> (the media
/// the edit shows, from <paramref name="EditMediaTime"/>) are in track units.
/// </summary>
private sealed record Timing(long[] Durations, int[] CompositionOffsets, long MediaDuration, long EditMediaTime, bool AllKey, long EmptyEdit, long Shown)
{ {
/// <summary>Whether the edit hides the end of the media (it must then be written).</summary>
public bool TrimsEnd => Shown < MediaDuration - EditMediaTime;
internal static Timing Of(Mp4OutputTrack track) internal static Timing Of(Mp4OutputTrack track)
{ {
var samples = track.Samples; var samples = track.Samples;
@@ -313,7 +325,13 @@ public static class Mp4Writer
editTime = 0; editTime = 0;
} }
return new Timing(durations, offsets, total, editTime, allKey, empty); var shown = Math.Max(0, total - editTime);
if (track.EditSegmentDuration is { } segment && segment > 0)
{
shown = Math.Min(shown, segment);
}
return new Timing(durations, offsets, total, editTime, allKey, empty, shown);
} }
} }
@@ -358,7 +376,7 @@ public static class Mp4Writer
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, EmptyMovie(timing[t], tracks[t].Timescale) + 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");
@@ -433,7 +451,7 @@ 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 Created, ulong Modified) 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 segment = ToMovie(timing.MediaDuration - timing.EditMediaTime, track.Timescale); var segment = ToMovie(timing.Shown, track.Timescale);
var empty = EmptyMovie(timing, track.Timescale); var empty = EmptyMovie(timing, track.Timescale);
var duration = empty + segment; var duration = empty + segment;
var wide = duration > uint.MaxValue || Wide(time); var wide = duration > uint.MaxValue || Wide(time);
@@ -466,7 +484,7 @@ 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 || empty > 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");
@@ -734,7 +752,9 @@ public static class Mp4Writer
var decoderSpecific = track.IsMp3 ? [] : Descriptor(0x05, track.AacConfiguration!); var decoderSpecific = track.IsMp3 ? [] : Descriptor(0x05, track.AacConfiguration!);
var config = new byte[13 + decoderSpecific.Length]; var config = new byte[13 + decoderSpecific.Length];
config[0] = track.IsMp3 ? (byte)0x6B : (byte)0x40; // MPEG-1 audio (layer III) or 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])];
+12 -3
View File
@@ -217,8 +217,9 @@ public sealed partial class H264Decoder
} }
/// <summary> /// <summary>
/// Whether the access unit carries a recovery point SEI (H.264 §D.1.8) with recovery_frame_cnt 0: decoding from it /// Whether the access unit carries a recovery point SEI (H.264 §D.1.8) with recovery_frame_cnt 0 and exact_match_flag
/// gives exact pictures from it on in output order, as from an IDR picture. Only the SEI before the first slice counts. /// 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> /// </summary>
internal static bool HasExactRecoveryPoint(ReadOnlySpan<byte> accessUnit, int lengthSize) internal static bool HasExactRecoveryPoint(ReadOnlySpan<byte> accessUnit, int lengthSize)
{ {
@@ -281,7 +282,15 @@ public sealed partial class H264Decoder
payloadSize += data[p++]; payloadSize += data[p++];
if (payloadType == 6) if (payloadType == 6)
{ {
return payloadSize > 0 && new RbspReader(data, Math.Min(length, p + payloadSize), p).ReadUe() == 0; // 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; p += payloadSize;
@@ -86,6 +86,52 @@ internal static class ExifOrientation
return ifd >= 8 && ifd <= (uint)(tiff.Length - 2); 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);
+16 -2
View File
@@ -202,6 +202,10 @@ public static class ImageConverter
var tooLarge = target == ImageFormat.WebP var tooLarge = target == ImageFormat.WebP
? pixels > MaxWebPPixels || info.Width > WebPEncoder.MaxDimension || info.Height > WebPEncoder.MaxDimension ? pixels > MaxWebPPixels || info.Width > WebPEncoder.MaxDimension || info.Height > WebPEncoder.MaxDimension
: pixels > ImageLimits.Default.MaxPixels; : 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; return tooLarge ? ImageConversionLosses.AsIsTooLarge : null;
} }
@@ -279,7 +283,7 @@ public static class ImageConverter
{ {
notCarried.Add("l'EXIF (rovinato: non è una struttura TIFF leggibile)"); notCarried.Add("l'EXIF (rovinato: non è una struttura TIFF leggibile)");
losses.Add(ImageConversionLosses.LostExifUnreadable); losses.Add(ImageConversionLosses.LostExifUnreadable);
exif = null; exif = OrientationOnly(metadata);
} }
var icc = metadata.IccProfile; var icc = metadata.IccProfile;
@@ -364,7 +368,7 @@ public static class ImageConverter
{ {
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)");
losses.Add(ImageConversionLosses.LostExifTooLarge); losses.Add(ImageConversionLosses.LostExifTooLarge);
exif = null; 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)
@@ -431,6 +435,16 @@ public static class ImageConverter
return data; 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)
{ {
@@ -71,4 +71,11 @@ public sealed record ImageInfo(ImageFormat Format, int Width, int Height, int Fr
/// <summary>Whether the pixels are stored as CMYK or YCCK (a JPEG with four components).</summary> /// <summary>Whether the pixels are stored as CMYK or YCCK (a JPEG with four components).</summary>
public bool IsCmyk { get; init; } 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; }
} }
+35 -20
View File
@@ -332,7 +332,12 @@ internal sealed partial class JpegFile : IDisposable
Texts = _texts ?? [], Texts = _texts ?? [],
Unread = _unread ?? [], Unread = _unread ?? [],
}; };
return new ImageInfo(ImageFormat.Jpeg, Width, Height, 1, false, metadata) { BitsPerSample = Precision, IsCmyk = Components.Length == 4 }; 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()
@@ -478,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)
@@ -833,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)
{ {
+20 -3
View File
@@ -603,13 +603,26 @@ public sealed class ExportCopier(ExportEnvironment env)
await using (stream.ConfigureAwait(false)) await using (stream.ConfigureAwait(false))
{ {
var (reader, info) = await Task.Run( var knownLength = library.Media.Duration;
var (reader, info, length) = await Task.Run(
() => () =>
{ {
// «N in tutto» names a frame by its position among the N instants, from the length the job used
// (the library's, or the one read from the file when the library has none: ExportService).
var probed = knownLength;
if (mode == FrameMode.Count && probed is null)
{
probed = VideoFrameReader.ProbeDuration(stream);
stream.Position = 0;
}
var opened = VideoFrameReader.Open(stream, out var found); var opened = VideoFrameReader.Open(stream, out var found);
return (opened, found); return (opened, found, probed);
}, },
ct).ConfigureAwait(false); ct).ConfigureAwait(false);
IReadOnlyList<TimeSpan> spread = mode == FrameMode.Count && length is { } d && d > TimeSpan.Zero && count is >= 1 and <= ExportFrames.MaxCount
? ExportFrames.Spread(d, count)
: [];
using (reader) using (reader)
{ {
var targets = info.Available ? reader.Locate([.. batch.Select(i => i.FrameAt ?? TimeSpan.Zero)]) : []; var targets = info.Available ? reader.Locate([.. batch.Select(i => i.FrameAt ?? TimeSpan.Zero)]) : [];
@@ -637,7 +650,11 @@ public sealed class ExportCopier(ExportEnvironment env)
followers[k] = []; followers[k] = [];
var at = TimeSpan.FromMilliseconds(ExportFrames.ActualMs(target.Actual)); var at = TimeSpan.FromMilliseconds(ExportFrames.ActualMs(target.Actual));
var identity = new ExportCopyIdentity(destination.Id, library.Account.Id, sha, ExportVariant.Frame, format, at); var identity = new ExportCopyIdentity(destination.Id, library.Account.Id, sha, ExportVariant.Frame, format, at);
var index = mode == FrameMode.Count ? (int)Math.Clamp(batch[k].Id - firstId, 0, int.MaxValue) : k; // The position among the N instants (two on one millisecond are one item: ids skip nothing then);
// by the ids only when the instant is not one of them (the library's length changed meanwhile).
var index = mode == FrameMode.Count
? ExportFrames.IndexOf(spread, batch[k].FrameAt ?? TimeSpan.Zero) ?? (int)Math.Clamp(batch[k].Id - firstId, 0, int.MaxValue)
: k;
var plan = new FramePlan(identity, ExportFrames.Suffix(mode, target.Actual, index, count), null); var plan = new FramePlan(identity, ExportFrames.Suffix(mode, target.Actual, index, count), null);
var current = await exports.FindCurrentCopyAsync(identity, ct).ConfigureAwait(false); var current = await exports.FindCurrentCopyAsync(identity, ct).ConfigureAwait(false);
if (current is { State: ExportCopyState.Copied }) if (current is { State: ExportCopyState.Copied })
+28 -3
View File
@@ -72,13 +72,16 @@ public static class ExportFrames
var instants = new TimeSpan[count]; var instants = new TimeSpan[count];
for (var i = 0; i < count; i++) for (var i = 0; i < count; i++)
{ {
instants[i] = TimeSpan.FromTicks(step.Ticks * i); instants[i] = WholeMs(TimeSpan.FromTicks(step.Ticks * i));
} }
return instants; return instants;
} }
/// <summary>«N in tutto»: (i + ½) · duration / N for i = 0…N − 1, in 100 ns ticks rounded down.</summary> /// <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) public static IReadOnlyList<TimeSpan> Spread(TimeSpan duration, int count)
{ {
if (count is < 1 or > MaxCount) if (count is < 1 or > MaxCount)
@@ -90,7 +93,7 @@ public static class ExportFrames
var instants = new TimeSpan[count]; var instants = new TimeSpan[count];
for (var i = 0; i < count; i++) for (var i = 0; i < count; i++)
{ {
instants[i] = TimeSpan.FromTicks((long)(((2 * i) + 1) * length / (2 * (Int128)count))); instants[i] = WholeMs(TimeSpan.FromTicks((long)(((2 * i) + 1) * length / (2 * (Int128)count))));
} }
return instants; return instants;
@@ -128,6 +131,28 @@ public static class ExportFrames
: label + "," + fraction.ToString("D3", CultureInfo.InvariantCulture).TrimEnd('0'); : 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> /// <summary>The identity of a frame's instant: its shown time in milliseconds, rounded up.</summary>
public static long ActualMs(TimeSpan shown) => public static long ActualMs(TimeSpan shown) =>
shown <= TimeSpan.Zero ? 0 : (shown.Ticks + TimeSpan.TicksPerMillisecond - 1) / TimeSpan.TicksPerMillisecond; shown <= TimeSpan.Zero ? 0 : (shown.Ticks + TimeSpan.TicksPerMillisecond - 1) / TimeSpan.TicksPerMillisecond;
+34 -11
View File
@@ -116,15 +116,20 @@ public sealed class ExportPlanner(ExportEnvironment env)
/// once (a story and its highlight entry, two files with the same bytes); with «Una copia sola» the same file counts /// once (a story and its highlight entry, two files with the same bytes); with «Una copia sola» the same file counts
/// once across accounts. /// 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) if (request.Frames is { } frames)
{ {
await foreach (var frame in EnumerateFramesAsync(request, frames, effective, ct).ConfigureAwait(false)) await foreach (var frame in EnumerateFramesAsync(request, frames, effective, lengthOf, ct).ConfigureAwait(false))
{ {
yield return frame; yield return frame;
} }
@@ -237,18 +242,21 @@ public sealed class ExportPlanner(ExportEnvironment env)
/// <summary> /// <summary>
/// A frames job (D12, D14 of tappa E3): photos are skipped, videos not due are counted as in «Copia in…», each due /// 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 gives one planned file /// video gives one planned frame per instant of the request. A video of unknown length is measured by
/// without an instant (<see cref="PlannedFile.UnknownDuration"/>): its instants are found when the job is recorded. /// <paramref name="lengthOf"/> (the job: before anything is recorded, so that its frames count against the caps of
/// Frames are not checked for «già copiato» here: the copy looks at each one's exact instant. /// 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> /// </summary>
private async IAsyncEnumerable<PlannedFile> EnumerateFramesAsync( private async IAsyncEnumerable<PlannedFile> EnumerateFramesAsync(
ExportJobRequest request, ExportJobRequest request,
ExportFramesRequest frames, ExportFramesRequest frames,
IReadOnlyDictionary<long, EffectiveDestination> effective, IReadOnlyDictionary<long, EffectiveDestination> effective,
Func<ExportCandidate, CancellationToken, Task<TimeSpan?>>? lengthOf,
[EnumeratorCancellation] CancellationToken ct) [EnumeratorCancellation] CancellationToken ct)
{ {
var exports = _env.Storage.Exports; var exports = _env.Storage.Exports;
var seen = new HashSet<(long Destination, long Account, string Sha256, long Ticks, ExportFormat Format)>(); var seen = new HashSet<(long Destination, long Account, string Sha256, long Ms, ExportFormat Format)>();
long after = 0; long after = 0;
while (true) while (true)
{ {
@@ -286,13 +294,27 @@ public sealed class ExportPlanner(ExportEnvironment env)
Prediction = ExportPrediction.Converted, Prediction = ExportPrediction.Converted,
FirstOfVideo = true, FirstOfVideo = true,
}; };
if (frames.Mode != FrameMode.At && c.Duration is not { } known) var duration = c.Duration ?? TimeSpan.Zero;
if (frames.Mode != FrameMode.At && c.Duration is null)
{ {
yield return frame with { UnknownDuration = true }; if (lengthOf is null)
continue; {
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;
} }
var duration = c.Duration ?? TimeSpan.Zero;
if (ExportFrames.FrameCount(duration, frames) > ExportFrames.MaxPerVideo) if (ExportFrames.FrameCount(duration, frames) > ExportFrames.MaxPerVideo)
{ {
yield return frame with { Action = PlannedCopy.OverCap }; yield return frame with { Action = PlannedCopy.OverCap };
@@ -304,7 +326,8 @@ public sealed class ExportPlanner(ExportEnvironment env)
{ {
var planned = frame with { FrameAt = at, FirstOfVideo = first }; var planned = frame with { FrameAt = at, FirstOfVideo = first };
first = false; first = false;
if (!seen.Add((destination, c.AccountId, c.Sha256!, at.Ticks, frames.Format))) // 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 }; planned = planned with { Action = PlannedCopy.AlreadyCopied };
} }
+48 -44
View File
@@ -167,11 +167,26 @@ 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) 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. // 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(); var count = new PlanTally();
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))
{ {
count.Add(file); count.Add(file);
} }
@@ -187,9 +202,10 @@ public sealed class ExportService : IAsyncDisposable
} }
} }
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 or PlannedCopy.PhotoSkipped or PlannedCopy.OverCap) if (file.DestinationId is not { } destination || file.Action is PlannedCopy.Missing or PlannedCopy.NotExported or PlannedCopy.PhotoSkipped or PlannedCopy.OverCap)
@@ -207,24 +223,24 @@ public sealed class ExportService : IAsyncDisposable
} }
// Frame items of one video are added together, in instant order (the copy takes them as one batch). // Frame items of one video are added together, in instant order (the copy takes them as one batch).
IReadOnlyList<TimeSpan?> instants = file.UnknownDuration && request.Frames is { } frames // The first pass already refused more than 20.000: this only guards that it saw the same files.
? await FrameInstantsAsync(file.Candidate, frames, ct).ConfigureAwait(false) if (file.Variant == ExportVariant.Frame && file.Action == PlannedCopy.Write && ++frameItems > ExportFrames.MaxPerRequest)
: [file.FrameAt];
foreach (var at in instants)
{ {
pending.Add(new ExportItem throw new ArgumentException(TooManyFramesText, nameof(request));
{
RunId = run.Id,
MediaId = file.Candidate.MediaId,
AccountId = file.Candidate.AccountId,
SourceSha256 = file.Candidate.Sha256,
Variant = file.Variant,
Format = file.Format,
FrameAt = at,
State = ExportItemState.Pending,
});
} }
pending.Add(new ExportItem
{
RunId = run.Id,
MediaId = file.Candidate.MediaId,
AccountId = file.Candidate.AccountId,
SourceSha256 = file.Candidate.Sha256,
Variant = file.Variant,
Format = file.Format,
FrameAt = file.FrameAt,
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);
@@ -299,44 +315,32 @@ public sealed class ExportService : IAsyncDisposable
} }
/// <summary> /// <summary>
/// The instants of a video whose length the library does not know: its headers are read now (only the library /// The length of a video the library does not know, from its headers (only the library file, never the
/// file, never the destination). A video that cannot be read gets one instant, and the copy says «Fotogramma non /// destination); null when it cannot be read now (the job then gives it one instant, and the copy tells).
/// disponibile per questo video».
/// </summary> /// </summary>
private async Task<IReadOnlyList<TimeSpan?>> FrameInstantsAsync(ExportCandidate candidate, ExportFramesRequest frames, CancellationToken ct) private async Task<TimeSpan?> ProbeLengthAsync(ExportCandidate candidate, CancellationToken ct)
{ {
TimeSpan? duration = null;
var media = await _env.Storage.Media.GetAsync(candidate.MediaId, ct).ConfigureAwait(false); var media = await _env.Storage.Media.GetAsync(candidate.MediaId, ct).ConfigureAwait(false);
var account = await _env.Storage.Accounts.GetAsync(candidate.AccountId, ct).ConfigureAwait(false); var account = await _env.Storage.Accounts.GetAsync(candidate.AccountId, ct).ConfigureAwait(false);
if (media is not null && account is not null && _env.ResolveSourcePath(account, media) is { } path) if (media is null || account is null || _env.ResolveSourcePath(account, media) is not { } path)
{ {
try return null;
{
duration = 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)
{
// Not readable now: one instant, the copy tells.
}
} }
if (duration is not { } d || d <= TimeSpan.Zero) try
{ {
return [TimeSpan.Zero]; 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)
if (ExportFrames.FrameCount(d, frames) > ExportFrames.MaxPerVideo)
{ {
throw new ArgumentException(ExportFrames.OverCapMessage, nameof(frames)); return null; // not readable now: one instant, the copy tells
} }
return [.. ExportFrames.Instants(d, frames).Select(at => (TimeSpan?)at)];
} }
/// <summary> /// <summary>
@@ -1,3 +1,4 @@
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;
@@ -19,24 +20,49 @@ public sealed class LibraryConversionQueue(IFebeStorage storage, IClock clock)
/// <summary>«In pausa» (<c>1</c>): the worker converts nothing until it is resumed.</summary> /// <summary>«In pausa» (<c>1</c>): the worker converts nothing until it is resumed.</summary>
public const string PausedKey = "esportazione.libreria-sospesa"; 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 readonly Lock SignalGate = new();
private static TaskCompletionSource _signal = NewSignal(); 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> /// <summary>The files «Anche i N già in libreria» would queue for the library formats of <paramref name="settings"/>.</summary>
public async Task<LibraryConversionPreview> PreviewExistingAsync(ExportSettings settings, CancellationToken ct = default) public Task<LibraryConversionPreview> PreviewExistingAsync(ExportSettings settings, CancellationToken ct = default)
{ {
ArgumentNullException.ThrowIfNull(settings); ArgumentNullException.ThrowIfNull(settings);
var (files, bytes) = await storage.Conversions.CountExistingAsync( return PreviewExistingAsync(LibraryConversionRules.FormatFor(MediaKind.Photo, settings), LibraryConversionRules.FormatFor(MediaKind.Video, settings), ct);
LibraryConversionRules.FormatFor(MediaKind.Photo, settings), LibraryConversionRules.FormatFor(MediaKind.Video, settings), ct).ConfigureAwait(false); }
/// <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); return new LibraryConversionPreview(files, bytes);
} }
/// <summary>«Anche i N già in libreria»: queues the present files that convert, in one statement per kind. Returns how many.</summary> /// <summary>«Anche i N già in libreria» for both library formats of <paramref name="settings"/>. Returns how many.</summary>
public async Task<int> EnqueueExistingAsync(ExportSettings settings, CancellationToken ct = default) public Task<int> EnqueueExistingAsync(ExportSettings settings, CancellationToken ct = default)
{ {
ArgumentNullException.ThrowIfNull(settings); ArgumentNullException.ThrowIfNull(settings);
var added = await storage.Conversions.EnqueueExistingAsync( return EnqueueExistingAsync(LibraryConversionRules.FormatFor(MediaKind.Photo, settings), LibraryConversionRules.FormatFor(MediaKind.Video, settings), ct);
LibraryConversionRules.FormatFor(MediaKind.Photo, settings), LibraryConversionRules.FormatFor(MediaKind.Video, settings), clock.Now, ct).ConfigureAwait(false); }
/// <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) if (added > 0)
{ {
Signal(); Signal();
@@ -46,7 +72,8 @@ public sealed class LibraryConversionQueue(IFebeStorage storage, IClock clock)
} }
/// <summary> /// <summary>
/// The settings changed: a library format turned off or changed loses its queue (its converted files and rows stay). /// The settings changed: a library format turned off or changed loses its queue and its failures that «Riprova»
/// would put back (its converted files and rows stay).
/// Turning one on queues nothing here: the interface asks, then calls <see cref="EnqueueExistingAsync"/> only for /// Turning one on queues nothing here: the interface asks, then calls <see cref="EnqueueExistingAsync"/> only for
/// «Anche i N già in libreria». /// «Anche i N già in libreria».
/// </summary> /// </summary>
@@ -57,17 +84,35 @@ public sealed class LibraryConversionQueue(IFebeStorage storage, IClock clock)
foreach (var kind in new[] { MediaKind.Photo, MediaKind.Video }) foreach (var kind in new[] { MediaKind.Photo, MediaKind.Video })
{ {
var old = LibraryConversionRules.FormatFor(kind, before); var old = LibraryConversionRules.FormatFor(kind, before);
if (old is { } format && old != LibraryConversionRules.FormatFor(kind, after)) var now = LibraryConversionRules.FormatFor(kind, after);
if (old == now)
{ {
await storage.Conversions.DeletePendingAsync(format, ct).ConfigureAwait(false); continue;
} }
if (old is { } format)
{
await storage.Conversions.DeleteQueueAsync(format, ct).ConfigureAwait(false);
}
// The files of the library before now are «già in libreria»: only «Anche i N» queues them.
var since = now is null ? null : clock.Now.ToUnixTimeMilliseconds().ToString(CultureInfo.InvariantCulture);
await storage.Settings.SetAsync(SinceKey(kind), since, ct).ConfigureAwait(false);
} }
} }
/// <summary>«Riprova»: the failed files go back to the queue, except those that never convert (<c>AsIs*</c>). Returns how many.</summary> /// <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) public async Task<int> RetryFailedAsync(CancellationToken ct = default)
{ {
var reset = await storage.Conversions.ResetFailedAsync(clock.Now, ct).ConfigureAwait(false); 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) if (reset > 0)
{ {
Signal(); Signal();
@@ -94,8 +139,10 @@ public sealed class LibraryConversionQueue(IFebeStorage storage, IClock clock)
} }
/// <summary> /// <summary>
/// Queues the present files of an entry by the library formats set now, after its journal line (the hook of /// Queues the new files of an entry by the library formats set now, after its journal line (the hook of
/// <see cref="LibraryIngest"/>). Nothing when both formats are «Originale». Returns how many rows were added. /// <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> /// </summary>
public static async Task<int> EnqueueEntryAsync(IFebeStorage storage, IReadOnlyList<Media> media, DateTimeOffset at, CancellationToken ct) public static async Task<int> EnqueueEntryAsync(IFebeStorage storage, IReadOnlyList<Media> media, DateTimeOffset at, CancellationToken ct)
{ {
@@ -107,7 +154,12 @@ public sealed class LibraryConversionQueue(IFebeStorage storage, IClock clock)
return 0; return 0;
} }
var requests = LibraryConversionRules.RequestsFor(media, settings); var photoSince = await SinceAsync(storage.Settings, MediaKind.Photo, ct).ConfigureAwait(false);
var videoSince = await SinceAsync(storage.Settings, MediaKind.Video, ct).ConfigureAwait(false);
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) if (requests.Count == 0)
{ {
return 0; return 0;
@@ -122,6 +174,12 @@ public sealed class LibraryConversionQueue(IFebeStorage storage, IClock clock)
return added; 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 async Task<long?> SinceAsync(ISettingsStore settings, MediaKind kind, CancellationToken ct) =>
long.TryParse(await settings.GetAsync(SinceKey(kind), ct).ConfigureAwait(false), NumberStyles.Integer, CultureInfo.InvariantCulture, out var ms) ? ms : null;
/// <summary>Wakes the worker: something entered the queue (or the pause ended).</summary> /// <summary>Wakes the worker: something entered the queue (or the pause ended).</summary>
public static void Signal() public static void Signal()
{ {
@@ -245,6 +245,15 @@ public sealed class LibraryConversionWorker(LibraryConversionEnvironment env)
return Outcome.Skipped; 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 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); var account = entry is null ? null : await storage.Accounts.GetAsync(entry.AccountId, token).ConfigureAwait(false);
if (entry is null || account is null) if (entry is null || account is null)
@@ -269,6 +278,13 @@ public sealed class LibraryConversionWorker(LibraryConversionEnvironment env)
return Outcome.Settled; return Outcome.Settled;
} }
// A disk already below the threshold stays below it with the file: the pause starts before the original is read
// (hashed, decoded or remuxed) again at every wake-up (D17). The exact check with the file's length follows.
if (_env.FreeSpace.Measure(folder) is { } before && _env.Thresholds.IsLow(before))
{
return Outcome.LowSpace;
}
var source = media.Sha256.ToLowerInvariant(); var source = media.Sha256.ToLowerInvariant();
if (!string.Equals(row.SourceSha256, source, StringComparison.Ordinal)) if (!string.Equals(row.SourceSha256, source, StringComparison.Ordinal))
{ {
@@ -136,25 +136,26 @@ public static class MediaConverter
return Whole(bytes, extension, sha, check.NoteCode is { } note ? [note] : []); return Whole(bytes, extension, sha, check.NoteCode is { } note ? [note] : []);
} }
var converted = await throttle.RunAsync(token => var (converted, refusal) = await throttle.RunAsync((ImageConversionResult? Result, string? Refusal) (CancellationToken token) =>
{ {
token.ThrowIfCancellationRequested(); token.ThrowIfCancellationRequested();
try try
{ {
return ImageConverter.Convert(bytes, format); return (ImageConverter.Convert(bytes, format), null);
} }
catch (ImageLimitException) catch (ImageLimitException)
{ {
return null; // Readable, but over what the decoder or the target allows: «troppo grande», never «non si legge».
return (null, ImageConversionLosses.AsIsTooLarge);
} }
catch (ImageDecodeException) catch (ImageDecodeException)
{ {
return null; return (null, ImageConversionLosses.AsIsNotDecodable);
} }
}, ct).ConfigureAwait(false); }, ct).ConfigureAwait(false);
if (converted is null) if (converted is null)
{ {
return Whole(bytes, extension, sha, [ImageConversionLosses.AsIsNotDecodable]); return Whole(bytes, extension, sha, [refusal!]);
} }
var data = converted.Data; var data = converted.Data;
@@ -283,14 +283,11 @@ public sealed class DownloadDuplicateReview(
var folder = layout.AccountFolder(account); var folder = layout.AccountFolder(account);
// Its converted files of the library (tappa E3) go with it: the queue and the failures are dropped, the rows // Its converted files of the library (tappa E3) go with it, in the transaction that deletes the file: the queue
// with a file become «Tolto». No supersession for the loser. // and the failures are dropped, the rows with a file become «Tolto» and their files are deleted below (one the
var conversions = await storage.Conversions.ListByMediaAsync(media.Id, ct).ConfigureAwait(false); // worker records meanwhile is among them). No supersession for the loser.
var withFiles = conversions var removed = await storage.Conversions.ForgetDeletedMediaAsync(media.Id, clock.Now, ct).ConfigureAwait(false);
.Where(c => c.State is MediaConversionState.Converted or MediaConversionState.Superseded && c.RelativePath is not null && c.Sha256 is not null) var withFiles = removed.Where(LibraryDeletion.HasFile).ToList();
.ToList();
await storage.Media.UpdateAsync(media with { State = MediaState.Deleted }, ct).ConfigureAwait(false);
await storage.Conversions.ForgetDeletedMediaAsync(media.Id, clock.Now, ct).ConfigureAwait(false);
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();
+7 -14
View File
@@ -65,9 +65,6 @@ public sealed class LibraryDeletion(
var folder = layout.AccountFolder(account); var folder = layout.AccountFolder(account);
var present = stored.Media.Where(m => m.RelativePath is not null && EntryStateRules.IsPresent(m.State)).ToList(); var present = stored.Media.Where(m => m.RelativePath is not null && EntryStateRules.IsPresent(m.State)).ToList();
// The converted files of the library (tappa E3) go with their originals; only the explicit choice deletes them.
var conversions = await storage.Conversions.ListByEntryAsync(entryId, ct).ConfigureAwait(false);
ct.ThrowIfCancellationRequested(); ct.ThrowIfCancellationRequested();
// From here the deletion goes to the end: a half-done deletion is worse than a late one. // From here the deletion goes to the end: a half-done deletion is worse than a late one.
@@ -75,16 +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);
IReadOnlyList<MediaConversion> withFiles; // The converted files of the library (tappa E3) go with their originals; only the explicit choice deletes them.
if (mode == DeletionMode.Remember) // Their rows are chosen in the transaction that deletes the entry: one the worker records meanwhile is among them.
{ var removed = mode == DeletionMode.Remember
withFiles = conversions.Where(HasFile).ToList(); ? await storage.Entries.MarkDeletedWithConversionsAsync(entryId, clock.Now, none).ConfigureAwait(false)
await storage.Entries.MarkDeletedAsync(entryId, clock.Now, withFiles.Select(c => c.Id).ToList(), none).ConfigureAwait(false); : await storage.Entries.RemoveWithConversionsAsync(entryId, none).ConfigureAwait(false);
} IReadOnlyList<MediaConversion> withFiles = removed.Where(HasFile).ToList();
else
{
withFiles = (await storage.Entries.RemoveWithConversionsAsync(entryId, none).ConfigureAwait(false)).Where(HasFile).ToList();
}
foreach (var media in stored.Media) foreach (var media in stored.Media)
{ {
@@ -141,7 +134,7 @@ public sealed class LibraryDeletion(
} }
/// <summary>A conversion whose file is (or was last known to be) on disk.</summary> /// <summary>A conversion whose file is (or was last known to be) on disk.</summary>
private static bool HasFile(MediaConversion c) => internal static bool HasFile(MediaConversion c) =>
c.State is MediaConversionState.Converted or MediaConversionState.Superseded && c.RelativePath is not null && c.Sha256 is not null; c.State is MediaConversionState.Converted or MediaConversionState.Superseded && c.RelativePath is not null && c.Sha256 is not null;
/// <summary> /// <summary>
+2 -1
View File
@@ -373,7 +373,8 @@ public sealed class LibraryIngest(
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 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); await LibraryConversionQueue.EnqueueEntryAsync(storage, stored.Media, clock.Now, CancellationToken.None).ConfigureAwait(false);
} }
+4 -2
View File
@@ -83,8 +83,10 @@ public sealed class VideoFrameReader : IDisposable
shown[i] = samples[i].PresentationTime + video.EmptyEditDuration; shown[i] = samples[i].PresentationTime + video.EmptyEditDuration;
} }
// Samples shown before the start (cut by the edit list) are not chosen, unless nothing else is. // Samples shown before the start or from the end of the edit on (cut by the edit list) are not chosen, unless
var visible = Enumerable.Range(0, samples.Count).Where(i => shown[i] >= 0).ToArray(); // 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)]; 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)); Array.Sort(order, (a, b) => shown[a] != shown[b] ? shown[a].CompareTo(shown[b]) : a.CompareTo(b));
} }
+8
View File
@@ -67,6 +67,14 @@ public interface IEntryStore
/// </summary> /// </summary>
Task MarkDeletedAsync(long entryId, DateTimeOffset at, IReadOnlyCollection<long> removedConversionIds, CancellationToken ct = default); 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> /// <summary>
/// «Eliminalo e lascia che torni»: removes the record (files records and highlight links by cascade). Conversions /// «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 /// without a file left (Pending, Failed, Removed) go with it; a Converted or Superseded one makes it fail with
+15 -7
View File
@@ -50,10 +50,12 @@ public interface IMediaConversionStore
Task<int> MarkRemovedAsync(IReadOnlyCollection<long> ids, DateTimeOffset at, CancellationToken ct = default); Task<int> MarkRemovedAsync(IReadOnlyCollection<long> ids, DateTimeOffset at, CancellationToken ct = default);
/// <summary> /// <summary>
/// A library file left its entry («Tieni il più grande» on a file of a series): its queue and failures go, its rows /// A library file leaves its entry («Tieni il più grande» on a file of a series), in one transaction: the file
/// with a file become «Tolto», in one transaction. Returns the rows marked «Tolto». /// 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> /// </summary>
Task<int> ForgetDeletedMediaAsync(long mediaId, DateTimeOffset at, CancellationToken ct = default); Task<IReadOnlyList<MediaConversion>> ForgetDeletedMediaAsync(long mediaId, DateTimeOffset at, CancellationToken ct = default);
/// <summary> /// <summary>
/// The account's file changed from <paramref name="oldSha256"/> to <paramref name="newSha256"/> (spec §4.10 /// The account's file changed from <paramref name="oldSha256"/> to <paramref name="newSha256"/> (spec §4.10
@@ -63,8 +65,11 @@ public interface IMediaConversionStore
/// </summary> /// </summary>
Task<IReadOnlyList<long>> SupersedeAsync(long accountId, string oldSha256, string newSha256, DateTimeOffset at, CancellationToken ct = default); 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 (Converted rows and their files stay).</summary> /// <summary>
Task<int> DeletePendingAsync(ExportFormat format, CancellationToken ct = default); /// The setting of a format went off or changed: its queue is emptied, with its failures that «Riprova» would put
/// back (Converted rows and their files stay, and so do the <c>AsIs*</c> verdicts). Returns how many rows went.
/// </summary>
Task<int> DeleteQueueAsync(ExportFormat format, 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> /// <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); Task<bool> DeletePendingRowAsync(long id, CancellationToken ct = default);
@@ -97,8 +102,11 @@ public interface IMediaConversionStore
/// </summary> /// </summary>
Task<MediaConversionCommitOutcome> CommitAsync(MediaConversionCommit commit, CancellationToken ct = default); Task<MediaConversionCommitOutcome> CommitAsync(MediaConversionCommit commit, CancellationToken ct = default);
/// <summary>«Riprova»: Failed rows go back to Pending, except those with an <c>AsIs*</c> code (they never convert). Returns how many.</summary> /// <summary>
Task<int> ResetFailedAsync(DateTimeOffset at, CancellationToken ct = default); /// «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> /// <summary>One file to queue in one format, made from these bytes.</summary>
+46 -16
View File
@@ -150,6 +150,28 @@ internal sealed class EntryStore(FebeDatabase db) : IEntryStore
public Task MarkDeletedAsync(long entryId, DateTimeOffset at, CancellationToken ct = default) => MarkDeletedAsync(entryId, at, [], ct); public Task MarkDeletedAsync(long entryId, DateTimeOffset at, CancellationToken ct = default) => MarkDeletedAsync(entryId, at, [], ct);
/// <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) public Task MarkDeletedAsync(long entryId, DateTimeOffset at, IReadOnlyCollection<long> removedConversionIds, CancellationToken ct = default)
{ {
ArgumentNullException.ThrowIfNull(removedConversionIds); ArgumentNullException.ThrowIfNull(removedConversionIds);
@@ -157,23 +179,9 @@ internal sealed class EntryStore(FebeDatabase db) : IEntryStore
return db.WriteAsync( 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)
{
throw new KeyNotFoundException($"Elemento {entryId} non trovato.");
}
w.Command(""" // The converted files that go (or are gone) are «Tolto», the others stay as they are.
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();
// The conversions for the library of its files (tappa E3): nothing left to convert or retry; the
// converted files that go (or are gone) are «Tolto», the others stay as they are.
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();
if (removed.Count > 0) if (removed.Count > 0)
{ {
var own = new HashSet<long>(); var own = new HashSet<long>();
@@ -192,6 +200,28 @@ internal sealed class EntryStore(FebeDatabase db) : IEntryStore
ct); 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));
}
}
MarkDeleted(w, entryId, at);
MediaConversionStore.MarkRemoved(w, withFiles.Select(c => c.Id).ToList(), at);
return withFiles;
},
ct);
public Task RemoveAsync(long entryId, CancellationToken ct = default) => public Task RemoveAsync(long entryId, CancellationToken ct = default) =>
db.WriteAsync( db.WriteAsync(
w => w =>
@@ -115,14 +115,18 @@ internal sealed partial class MediaConversionStore
return changed; return changed;
} }
public Task<int> ForgetDeletedMediaAsync(long mediaId, DateTimeOffset at, CancellationToken ct = default) => public Task<IReadOnlyList<MediaConversion>> ForgetDeletedMediaAsync(long mediaId, DateTimeOffset at, CancellationToken ct = default) =>
db.WriteAsync( db.WriteAsync<IReadOnlyList<MediaConversion>>(
w => 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(); w.Command("DELETE FROM media_conversion WHERE media_id = @m AND state IN ('Pending', 'Failed')").With("@m", mediaId).ExecuteNonQuery();
return w.Command(""" var removed = ReadAll(w.Command($"""
UPDATE media_conversion SET state = 'Removed', state_changed_at = @at WHERE media_id = @m AND state IN ('Converted', 'Superseded') SELECT {JoinedColumns} FROM media_conversion mc JOIN media m ON m.id = mc.media_id
""").With("@m", mediaId).With("@at", Sql.Time(at)).ExecuteNonQuery(); 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); ct);
@@ -183,9 +187,12 @@ internal sealed partial class MediaConversionStore
ct); ct);
} }
public Task<int> DeletePendingAsync(ExportFormat format, CancellationToken ct = default) => public Task<int> DeleteQueueAsync(ExportFormat format, CancellationToken ct = default) =>
db.WriteAsync( db.WriteAsync(
w => w.Command("DELETE FROM media_conversion WHERE state = 'Pending' AND format = @f").With("@f", Sql.Enum(format)).ExecuteNonQuery(), w => 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(),
ct); ct);
public Task<bool> DeletePendingRowAsync(long id, CancellationToken ct = default) => public Task<bool> DeletePendingRowAsync(long id, CancellationToken ct = default) =>
@@ -454,11 +461,25 @@ internal sealed partial class MediaConversionStore
return MediaConversionCommitOutcome.Upserted; return MediaConversionCommitOutcome.Upserted;
} }
public Task<int> ResetFailedAsync(DateTimeOffset at, CancellationToken ct = default) => public Task<int> ResetFailedAsync(IReadOnlyCollection<ExportFormat> formats, DateTimeOffset at, CancellationToken ct = default)
db.WriteAsync( {
w => w.Command($""" ArgumentNullException.ThrowIfNull(formats);
UPDATE media_conversion SET state = 'Pending', last_error = NULL, state_changed_at = @at if (formats.Count == 0)
WHERE state = 'Failed' AND (last_error IS NULL OR NOT ({AsIsCondition})) {
""").With("@at", Sql.Time(at)).ExecuteNonQuery(), 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); ct);
}
} }
+94 -36
View File
@@ -32,6 +32,12 @@ 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);
@@ -42,41 +48,7 @@ public static class ExportApi
endpoints.MapPut("/api/export/settings", async (HttpContext context, ExportHub hub, IFebeStorage storage, FebeLibrary library, LibraryConversionQueue queue, LibraryChanges changes, IClock clock, IServiceProvider services, CancellationToken ct) => endpoints.MapPut("/api/export/settings", async (HttpContext context, ExportHub hub, IFebeStorage storage, FebeLibrary library, LibraryConversionQueue queue, LibraryChanges changes, IClock clock, IServiceProvider services, CancellationToken ct) =>
{ {
var body = await ApiHttp.BodyAsync(context, FebeJsonContext.Default.ExportSettingsRequest).ConfigureAwait(false); var body = await ApiHttp.BodyAsync(context, FebeJsonContext.Default.ExportSettingsRequest).ConfigureAwait(false);
var before = await ExportSettings.LoadAsync(storage.Settings, ct).ConfigureAwait(false); var (before, after, queued) = await SaveSettingsAsync(body, storage, queue, 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.");
}
await after.SaveAsync(storage.Settings, ct).ConfigureAwait(false);
await queue.OnSettingsChangedAsync(before, after, ct).ConfigureAwait(false);
var queued = 0;
if (body.ConvertExisting == true && after.ConvertsLibrary)
{
queued = await queue.EnqueueExistingAsync(after, ct).ConfigureAwait(false);
}
changes.Publish(new LibraryChange(clock.Now, null, "export")); changes.Publish(new LibraryChange(clock.Now, null, "export"));
var overview = await OverviewAsync(context, hub, storage, library, clock, services, ct).ConfigureAwait(false); var overview = await OverviewAsync(context, hub, storage, library, clock, services, ct).ConfigureAwait(false);
return ApiHttp.Json(new ExportSettingsSavedDto(SettingsMessage(before, after, body, queued), overview, queued), FebeJsonContext.Default.ExportSettingsSavedDto); return ApiHttp.Json(new ExportSettingsSavedDto(SettingsMessage(before, after, body, queued), overview, queued), FebeJsonContext.Default.ExportSettingsSavedDto);
@@ -93,7 +65,17 @@ public static class ExportApi
LibraryPhotoFormat = ParseFormat(photo, MediaKind.Photo) ?? settings.LibraryPhotoFormat, LibraryPhotoFormat = ParseFormat(photo, MediaKind.Photo) ?? settings.LibraryPhotoFormat,
LibraryVideoFormat = ParseFormat(video, MediaKind.Video) ?? settings.LibraryVideoFormat, LibraryVideoFormat = ParseFormat(video, MediaKind.Video) ?? settings.LibraryVideoFormat,
}; };
var preview = settings.ConvertsLibrary ? await queue.PreviewExistingAsync(settings, ct).ConfigureAwait(false) : new LibraryConversionPreview(0, 0);
// 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); return ApiHttp.Json(new LibraryConversionPreviewDto(preview.Files, preview.Bytes, PreviewText(preview)), FebeJsonContext.Default.LibraryConversionPreviewDto);
}); });
@@ -658,6 +640,82 @@ public static class ExportApi
/// <summary>The wire name of a format (D21): <c>original</c>, <c>jpg</c>, <c>png</c>, <c>webplossless</c>, <c>mp4</c>.</summary> /// <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(); 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.");
}
await after.SaveAsync(storage.Settings, ct).ConfigureAwait(false);
await queue.OnSettingsChangedAsync(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, ct).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> /// <summary>
/// A format of <paramref name="kind"/> from its wire name; null for null or empty (nothing chosen). 400 for a name /// 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. /// that is not a format of that kind.
+2 -1
View File
@@ -80,7 +80,8 @@ public sealed record LibraryConversionDto(int Pending, int Converted, int Failed
/// <summary> /// <summary>
/// <c>PUT /api/export/settings</c>, every field optional (null keeps it): «Lo stesso post in due account» /// <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). /// (<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. /// <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> /// </summary>
public sealed record ExportSettingsRequest( public sealed record ExportSettingsRequest(
string? SamePost = null, string? SamePost = null,
+18 -4
View File
@@ -71,7 +71,10 @@ public sealed class FrameService(IClock clock)
/// <summary>The time a preview or a single frame may take, waiting included.</summary> /// <summary>The time a preview or a single frame may take, waiting included.</summary>
public TimeSpan Budget { get; init; } = TimeSpan.FromSeconds(30); public TimeSpan Budget { get; init; } = TimeSpan.FromSeconds(30);
/// <summary>A write of the zip that makes no progress for this long aborts the download.</summary> /// <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); public TimeSpan WriteStall { get; init; } = TimeSpan.FromSeconds(60);
/// <summary>What a video allows, from the cache by SHA-256 when known (the file is opened only the first time).</summary> /// <summary>What a video allows, from the cache by SHA-256 when known (the file is opened only the first time).</summary>
@@ -371,6 +374,9 @@ public sealed class FrameService(IClock clock)
// A data descriptor is 16 or 24 bytes; anything far larger written synchronously is a change of the BCL. // 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; 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 readonly MemoryStream _pending = new();
private long _position; private long _position;
@@ -444,11 +450,19 @@ public sealed class FrameService(IClock clock)
await GuardedAsync(bytes, ct).ConfigureAwait(false); 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) private async Task GuardedAsync(ReadOnlyMemory<byte> buffer, CancellationToken ct)
{ {
using var guard = CancellationTokenSource.CreateLinkedTokenSource(ct); for (var offset = 0; offset < buffer.Length; offset += Piece)
guard.CancelAfter(stall); {
await inner.WriteAsync(buffer, guard.Token).ConfigureAwait(false); using var guard = CancellationTokenSource.CreateLinkedTokenSource(ct);
guard.CancelAfter(stall);
await inner.WriteAsync(buffer.Slice(offset, Math.Min(Piece, buffer.Length - offset)), guard.Token).ConfigureAwait(false);
}
} }
} }
} }
@@ -1,4 +1,5 @@
using Febe.Core.Abstractions; using Febe.Core.Abstractions;
using Febe.Core.Codecs.Containers;
using Febe.Core.Domain; using Febe.Core.Domain;
using Febe.Core.Export; using Febe.Core.Export;
using Febe.Core.Library; using Febe.Core.Library;
@@ -234,6 +235,101 @@ public sealed class ExportFramesTests
Assert.IsEmpty(Fingerprint.Of(bed.Usb)); Assert.IsEmpty(Fingerprint.Of(bed.Usb));
} }
[TestMethod]
public async Task NInAllOnAVideoShorterThanNMillisecondsNamesEachFrameByItsPosition()
{
var ct = TestContext.CancellationToken;
await using var bed = await ExportTestBed.CreateAsync();
var still = TestVideos.Mp4(Stream.FirstPictureRepeated(18)); // 0,6 s: 1.000 instants cannot all be a millisecond apart
var video = (await SaveVideoAsync(bed, bed.Marta, "993", still, ".mp4")).Media[0];
await bed.GeneralAsync(ct: ct);
const int N = 1000;
// The instants are whole milliseconds (the item, the preview and the download locate the same one); the first of
// those on one millisecond is the item, the others are counted as already there.
var instants = ExportFrames.Spread(Duration(still), N);
Assert.IsTrue(instants.All(t => t.Ticks % TimeSpan.TicksPerMillisecond == 0));
var firsts = instants.Select((t, i) => (Ms: (long)t.TotalMilliseconds, Index: i)).GroupBy(x => x.Ms).Select(g => g.First()).ToList();
Assert.IsLessThan(N, firsts.Count);
var start = await bed.CopyAsync(Frames(video, new ExportFramesRequest(FrameMode.Count, null, null, N, ExportFormat.Png)), ct);
Assert.AreEqual((firsts.Count, N - firsts.Count), (start.Plan.Frames, start.Plan.AlreadyCopied), "the plan says what is recorded");
var items = await bed.ItemsAsync(start.Runs.Single().Id, ct);
CollectionAssert.AreEqual(firsts.Select(f => (TimeSpan?)TimeSpan.FromMilliseconds(f.Ms)).ToArray(), items.Select(i => i.FrameAt).ToArray());
// Each frame written is named by its position among the N instants, as «Scarica» names it, not by its row.
var targets = Locate(still, [.. firsts.Select(f => TimeSpan.FromMilliseconds(f.Ms))]);
var stem = Path.ChangeExtension(video.RelativePath!, null);
var leaders = targets.Select((t, k) => (t.Sample, k)).GroupBy(x => x.Sample).Select(g => g.First().k).ToList();
Assert.HasCount(leaders.Count, Fingerprint.Of(bed.Usb));
foreach (var k in leaders)
{
Assert.AreEqual(ExportItemState.Copied, items[k].State);
Assert.AreEqual("marta.demo/" + stem + ExportFrames.Suffix(FrameMode.Count, targets[k].Actual, firsts[k].Index, N) + ".png", items[k].RelativePath, $"frame {k}");
}
Assert.AreNotEqual(leaders.Count - 1, firsts[leaders[^1]].Index, "the positions skip the instants on one millisecond");
}
[TestMethod]
public async Task VideosOfUnknownLengthCountAgainstTheCapsBeforeAnythingIsRecorded()
{
var ct = TestContext.CancellationToken;
await using var bed = await ExportTestBed.CreateAsync();
await bed.GeneralAsync(ct: ct);
// One video of 200 s the library has no length for, one every 0,1 s: 2.000 frames, refused before any run.
var long200 = (await SaveVideoAsync(bed, bed.Marta, "980", LongStill(200), ".mp4")).Media[0];
var every = Frames(long200, new ExportFramesRequest(FrameMode.Every, null, TimeSpan.FromMilliseconds(100), null, ExportFormat.Png));
var overCap = await Assert.ThrowsExactlyAsync<ArgumentException>(() => bed.Service.StartAsync(every, ct));
StringAssert.StartsWith(overCap.Message, ExportFrames.OverCapMessage);
Assert.IsEmpty(await bed.Db.Exports.ListRunsAsync(ct));
// 21 videos of a second without a length, 1.000 each: 21.000 frames, over the 20.000 of a request.
var still = Stream.FirstPictureRepeated(30);
var ids = new List<long>();
for (var i = 0; i < 21; i++)
{
ids.Add((await SaveVideoAsync(bed, bed.Marta, $"96{i:D2}", TestVideos.Mp4(still, Make.T0.AddDays(-i)), ".mp4")).Media[0].Id);
}
var many = new ExportJobRequest(new ExportSelection.Media(ids), Frames: new ExportFramesRequest(FrameMode.Count, null, null, 1000, ExportFormat.Png));
var tooMany = await Assert.ThrowsExactlyAsync<ArgumentException>(() => bed.Service.StartAsync(many, ct));
StringAssert.StartsWith(tooMany.Message, ExportService.TooManyFramesText);
Assert.IsEmpty(await bed.Db.Exports.ListRunsAsync(ct));
Assert.IsEmpty(Fingerprint.Of(bed.Usb));
Assert.AreEqual(21, (await bed.Service.PlanAsync(many, ct)).Frames, "the dialog does not read the files: «circa» one a video");
// Two of them, 3 each: measured when the job is recorded, the plan of the start says what was recorded.
var two = new ExportJobRequest(new ExportSelection.Media(ids.Take(2).ToList()), Frames: new ExportFramesRequest(FrameMode.Count, null, null, 3, ExportFormat.Png));
var started = await bed.CopyAsync(two, ct);
Assert.AreEqual((2, 6), (started.Plan.Videos, started.Plan.Frames));
Assert.HasCount(6, await bed.ItemsAsync(started.Runs.Single().Id, ct));
}
/// <summary>A video of one still picture shown for <paramref name="seconds"/>.</summary>
private static byte[] LongStill(int seconds)
{
var es = Stream.FirstPictureRepeated(1);
var bytes = es.LengthPrefixed(0);
var track = new Mp4OutputTrack
{
IsVideo = true,
Timescale = TestVideos.Timescale,
Samples = [new Mp4OutputSample(bytes.Length, 0, 0, true)],
WriteSample = (_, s) => s.Write(bytes),
Width = es.Width,
Height = es.Height,
AvcConfiguration = es.AvcC,
LastSampleDuration = (long)seconds * TestVideos.Timescale,
};
using var output = new MemoryStream();
Mp4Writer.Write(output, [track]);
return output.ToArray();
}
private static ExportJobRequest Frames(Media video, ExportFramesRequest frames) => new(new ExportSelection.Media([video.Id]), Frames: frames); private static ExportJobRequest Frames(Media video, ExportFramesRequest frames) => new(new ExportSelection.Media([video.Id]), Frames: frames);
/// <summary>A video whose length the library does not know (it is read when the job is recorded).</summary> /// <summary>A video whose length the library does not know (it is read when the job is recorded).</summary>
@@ -161,4 +161,57 @@ public sealed class ImageConversionCheckTests
Assert.AreEqual(ImageConversionLosses.AsIsTooLarge, ImageConverter.Check(huge, ImageFormat.Jpeg).NoteCode); Assert.AreEqual(ImageConversionLosses.AsIsTooLarge, ImageConverter.Check(huge, ImageFormat.Jpeg).NoteCode);
Assert.AreEqual(ImageConversionLosses.AsIsTooLarge, ImageConverter.Check(huge, ImageFormat.WebP).NoteCode); Assert.AreEqual(ImageConversionLosses.AsIsTooLarge, ImageConverter.Check(huge, ImageFormat.WebP).NoteCode);
} }
/// <summary>A JPEG of only its header (SOI, SOF, SOS, EOI): enough for the check, which never decodes.</summary>
private static byte[] JpegHeader(int frameMarker, int width, int height, byte lumaSampling)
{
return
[
0xFF, 0xD8,
0xFF, (byte)frameMarker, 0, 17, 8, (byte)(height >> 8), (byte)height, (byte)(width >> 8), (byte)width, 3,
1, lumaSampling, 0, 2, 0x11, 1, 3, 0x11, 1,
0xFF, 0xDA, 0, 12, 3, 1, 0x00, 2, 0x11, 3, 0x11, 0, 0, 0,
0xFF, 0xD9,
];
}
[TestMethod]
public async Task AProgressiveJpegTheDecoderWouldRefuseIsTooLargeNotUnreadable()
{
// 8000 × 8000 = 64 MP, within the 100 MP of PNG and JPG. Baseline it needs 3 bytes a pixel besides the picture;
// progressive 4:4:4 keeps its coefficients too, 9 bytes a pixel: 576 MB, over the decoder's 512 MiB.
var baseline = JpegHeader(0xC0, 8000, 8000, 0x11);
var progressive = JpegHeader(0xC2, 8000, 8000, 0x11);
var progressive420 = JpegHeader(0xC2, 8000, 8000, 0x22);
Assert.AreEqual(ImageConversionAction.Convert, ImageConverter.Check(baseline, ImageFormat.Png).Action);
Assert.AreEqual(ImageConversionAction.Convert, ImageConverter.Check(progressive420, ImageFormat.Png).Action, "4:2:0: 4,5 byte a pixel");
Assert.AreEqual(new ImageConversionCheck(ImageConversionAction.CopyOriginal, ImageFormat.Jpeg, ImageConversionLosses.AsIsTooLarge),
ImageConverter.Check(progressive, ImageFormat.Png));
Assert.AreEqual(576_000_000L, ImageDecoder.Identify(progressive).DecodeWorkingBytes);
// The copy and the library conversion say «troppo grande», never «Febe non riesce a leggere l'immagine».
var sha = Convert.ToHexStringLower(SHA256.HashData(progressive));
using var prepared = await MediaConverter.PrepareAsync(() => new MemoryStream(progressive), "post/grande.jpg", MediaKind.Photo,
ExportFormat.Png, sha, new ConversionThrottle(), CancellationToken.None);
Assert.AreEqual(ExportVariant.Whole, prepared.Variant);
CollectionAssert.AreEqual(new[] { ImageConversionLosses.AsIsTooLarge }, prepared.Notes.ToArray());
}
[TestMethod]
public void WhatTheCheckLetsThroughTheDecoderConverts()
{
// A real progressive 4:4:4 JPEG of 64 × 64 under a working budget between the 3 bytes a pixel of a baseline
// decode and the 9 of a progressive one: the check sends it as it is, so the conversion never throws.
using var picture = Gradient(64, 64, seed: 3);
var baseline = ImageConverter.Encode(picture, ImageFormat.Jpeg, null, new ImageConversionOptions { JpegSubsampling = JpegSubsampling.Ratio444 });
var progressive = JpegTestEncoder.Write(JpegDecoder.DecodeCoefficients(baseline), new JpegTestOptions { Progressive = true });
var options = new ImageConversionOptions { Limits = new ImageLimits { MaxWorkingBytes = 64 * 64 * 6 } };
Assert.AreEqual(ImageConversionAction.Convert, ImageConverter.Check(baseline, ImageFormat.Png, options).Action);
Assert.AreEqual(ImageFormat.Png, ImageFormatSniffer.Detect(ImageConverter.Convert(baseline, ImageFormat.Png, options).Data));
Assert.AreEqual(ImageConversionLosses.AsIsTooLarge, ImageConverter.Check(progressive, ImageFormat.Png, options).NoteCode);
Assert.ThrowsExactly<ImageLimitException>(() => ImageConverter.Convert(progressive, ImageFormat.Png, options));
Assert.AreEqual(ImageConversionAction.Convert, ImageConverter.Check(progressive, ImageFormat.Png).Action, "con i limiti di sempre");
Assert.AreEqual(ImageFormat.Png, ImageFormatSniffer.Detect(ImageConverter.Convert(progressive, ImageFormat.Png).Data));
}
} }
@@ -87,4 +87,51 @@ public sealed class ImageConversionTests
CollectionAssert.Contains(result.Losses.ToList(), ImageConversionLosses.TransparencyWhite); CollectionAssert.Contains(result.Losses.ToList(), ImageConversionLosses.TransparencyWhite);
CollectionAssert.AreEqual(before, picture.ToArray(), "Encode lavora su una copia."); CollectionAssert.AreEqual(before, picture.ToArray(), "Encode lavora su una copia.");
} }
[TestMethod]
[DataRow(true)]
[DataRow(false)]
public void AnExifTooLargeForJpgStillKeepsTheOrientation(bool littleEndian)
{
// 70 000 bytes of TIFF (a big maker note, say) with Orientation 6: more than one APP1 segment holds. The block is
// left behind, but the pixels are never turned (§4.10): without the tag the JPG would show turned.
var exif = new byte[70_000];
var tiff = exif.AsSpan();
tiff[0] = tiff[1] = littleEndian ? (byte)'I' : (byte)'M';
void W16(int at, ushort v)
{
if (littleEndian)
{
System.Buffers.Binary.BinaryPrimitives.WriteUInt16LittleEndian(exif.AsSpan(at), v);
}
else
{
System.Buffers.Binary.BinaryPrimitives.WriteUInt16BigEndian(exif.AsSpan(at), v);
}
}
W16(2, 42);
W16(littleEndian ? 4 : 6, 8); // first IFD at 8
W16(8, 1);
W16(10, 0x0112);
W16(12, 3);
W16(littleEndian ? 14 : 16, 1);
W16(18, 6);
using var picture = Gradient(4, 4, seed: 5);
var png = ImageConverter.Encode(picture, ImageFormat.Png, new ImageMetadata { Exif = exif, Orientation = 6 });
Assert.AreEqual(6, ImageDecoder.Identify(png).Metadata.Orientation);
var result = ImageConverter.Convert(png, ImageFormat.Jpeg);
CollectionAssert.Contains(result.Losses.ToList(), ImageConversionLosses.LostExifTooLarge);
var written = ImageDecoder.Identify(result.Data).Metadata;
Assert.AreEqual(6, written.Orientation);
Assert.AreEqual(6, result.Metadata.Orientation);
Assert.AreEqual(26, written.Exif!.Length);
Assert.AreEqual(littleEndian ? (byte)'I' : (byte)'M', written.Exif[0], "l'ordine dei byte della sorgente");
// Orientation 1 needs no block at all.
var upright = ImageConverter.Encode(picture, ImageFormat.Png, new ImageMetadata { Exif = exif.AsSpan(0, 8).ToArray().Concat(new byte[70_000]).ToArray(), Orientation = 1 });
Assert.IsNull(ImageDecoder.Identify(ImageConverter.Convert(upright, ImageFormat.Jpeg).Data).Metadata.Exif);
}
} }
@@ -81,6 +81,35 @@ public sealed class LibraryConversionTests
Assert.IsEmpty(await library.Db.Conversions.ListByMediaAsync(jpg.Media[0].Id, ct)); Assert.IsEmpty(await library.Db.Conversions.ListByMediaAsync(jpg.Media[0].Id, ct));
} }
[TestMethod]
public async Task ALateFileOfAnOldEntryQueuesItselfOnly()
{
var ct = TestContext.CancellationToken;
using var temp = new TempFolder();
await using var library = await TestLibrary.CreateAsync(temp);
var account = await library.Db.Accounts.AddAsync(Make.Account("marta.demo", "100"));
var added = await library.Db.Entries.AddAsync(Make.Entry(account.Id, "1", Make.T0), [Make.Photo(1), Make.Photo(2)], ct);
var (first, second) = (added.Stored.Media[0], added.Stored.Media[1]);
await StorePngAsync(library, account, added.Stored.Entry, first, 31);
await library.Ingest.AppendJournalAsync(added.Stored.Entry.Id, ct);
// Photos to JPG with «Solo i nuovi»: the PNG already in the library is left alone...
library.Clock.Now += TimeSpan.FromMinutes(5);
var settings = await TurnOnAsync(library, ExportFormat.Jpg);
await new LibraryConversionQueue(library.Db, library.Clock).OnSettingsChangedAsync(ExportSettings.Default, settings, ct);
// ...also when the second file of its series arrives later: only that one is new.
library.Clock.Now += TimeSpan.FromMinutes(5);
await StorePngAsync(library, account, added.Stored.Entry, second, 32);
await library.Ingest.AppendJournalAsync(added.Stored.Entry.Id, ct);
Assert.IsEmpty(await library.Db.Conversions.ListByMediaAsync(first.Id, ct), "the old file had its answer");
Assert.AreEqual(MediaConversionState.Pending, (await library.Db.Conversions.ListByMediaAsync(second.Id, ct)).Single().State);
// «Anche i N» still counts the old one.
Assert.AreEqual(1, (await new LibraryConversionQueue(library.Db, library.Clock).PreviewExistingAsync(settings, ct)).Files);
}
[TestMethod] [TestMethod]
public async Task TurningOffDropsThePendingRowsAndKeepsTheConvertedOnes() public async Task TurningOffDropsThePendingRowsAndKeepsTheConvertedOnes()
{ {
@@ -278,6 +307,108 @@ public sealed class LibraryConversionTests
Assert.AreEqual(MediaConversionState.Pending, (await library.Db.Conversions.ListByMediaAsync(entry.Media[0].Id, ct)).Single().State); Assert.AreEqual(MediaConversionState.Pending, (await library.Db.Conversions.ListByMediaAsync(entry.Media[0].Id, ct)).Single().State);
} }
[TestMethod]
public async Task ALowDiskPausesBeforeTheOriginalIsReadAgain()
{
var ct = TestContext.CancellationToken;
using var temp = new TempFolder();
await using var library = await TestLibrary.CreateAsync(temp);
await TurnOnAsync(library, ExportFormat.Jpg);
var (account, entry) = await SavePngAsync(library, "1", 23);
var space = new FakeFreeSpaceProbe();
space.Set(library.Layout.AccountFolder(account), 1024, 2 * FakeFreeSpaceProbe.GB);
var throttle = new ConversionThrottle();
var worker = new LibraryConversionWorker(Environment(library, throttle: throttle) with { FreeSpace = space });
// Another conversion holds the throttle: a pass that decoded the photo again would wait for it.
using var release = new ManualResetEventSlim();
var other = throttle.RunAsync(_ => release.Wait(TimeSpan.FromMinutes(1)), ct);
try
{
for (var wakeUp = 0; wakeUp < 3; wakeUp++)
{
var pass = await worker.RunOnceAsync(ct).WaitAsync(TimeSpan.FromSeconds(30), ct);
Assert.AreEqual((0, false), (pass.Done, pass.Again));
Assert.AreEqual(LibraryConversionText.LowSpace, (await worker.StatusAsync(ct)).Waiting);
}
}
finally
{
release.Set();
await other;
}
Assert.AreEqual(MediaConversionState.Pending, (await library.Db.Conversions.ListByMediaAsync(entry.Media[0].Id, ct)).Single().State);
space.Set(library.Layout.AccountFolder(account), 50 * FakeFreeSpaceProbe.GB, 100 * FakeFreeSpaceProbe.GB);
Assert.AreEqual(1, (await worker.RunOnceAsync(ct)).Converted, "space again: it converts");
}
[TestMethod]
public async Task AFormatTurnedOffOrChangedIsNeitherRetriedNorConverted()
{
var ct = TestContext.CancellationToken;
using var temp = new TempFolder();
await using var library = await TestLibrary.CreateAsync(temp);
var jpg = await TurnOnAsync(library, ExportFormat.Jpg);
var (account, entry) = await SavePngAsync(library, "1", 24);
var media = entry.Media[0];
var path = library.Layout.FullPath(account, media.RelativePath!);
var bytes = await File.ReadAllBytesAsync(path, ct);
File.Delete(path);
await Worker(library).RunOnceAsync(ct);
Assert.AreEqual(MediaConversionState.Failed, (await library.Db.Conversions.ListByMediaAsync(media.Id, ct)).Single().State);
await File.WriteAllBytesAsync(path, bytes, ct);
var queue = new LibraryConversionQueue(library.Db, library.Clock);
// Photos to PNG without the queue told (another way in): «Riprova» puts back only the formats set now.
var png = jpg with { LibraryPhotoFormat = ExportFormat.Png };
await png.SaveAsync(library.Db.Settings, ct);
Assert.AreEqual(0, await queue.RetryFailedAsync(ct));
// Told: the failures of the format changed go with its queue, they are neither counted nor retried.
await queue.OnSettingsChangedAsync(jpg, png, ct);
Assert.IsEmpty(await library.Db.Conversions.ListByMediaAsync(media.Id, ct));
Assert.AreEqual(0, (await library.Db.Conversions.CountByStateAsync(ct)).Failed);
// A row left in the old format (put back by a supersession, say) is dropped by the worker, never written.
await library.Db.Conversions.EnqueueAsync([new Febe.Core.Storage.MediaConversionRequest(media.Id, ExportFormat.Jpg, media.Sha256!)], library.Clock.Now, ct);
var pass = await Worker(library).RunOnceAsync(ct);
Assert.AreEqual(0, pass.Converted);
Assert.IsEmpty(await library.Db.Conversions.ListByMediaAsync(media.Id, ct));
Assert.IsFalse(File.Exists(Path.ChangeExtension(path, ".jpg")), "no JPG while the photos are set to PNG");
// Turned off altogether: the same.
var off = png with { LibraryPhotoFormat = ExportFormat.Original };
await off.SaveAsync(library.Db.Settings, ct);
await library.Db.Conversions.EnqueueAsync([new Febe.Core.Storage.MediaConversionRequest(media.Id, ExportFormat.Png, media.Sha256!)], library.Clock.Now, ct);
Assert.AreEqual(0, (await Worker(library).RunOnceAsync(ct)).Converted);
Assert.IsEmpty(await library.Db.Conversions.ListByMediaAsync(media.Id, ct));
Assert.HasCount(1, Directory.GetFiles(library.Layout.AccountFolder(account), "*.*", SearchOption.AllDirectories).Where(f => !f.EndsWith(AccountJournal.FileName, StringComparison.Ordinal)), "only the original");
}
[TestMethod]
public async Task AConversionRecordedWhileTheEntryIsDeletedGoesWithIt()
{
var ct = TestContext.CancellationToken;
using var temp = new TempFolder();
await using var library = await TestLibrary.CreateAsync(temp);
await TurnOnAsync(library, ExportFormat.Jpg);
var (account, entry) = await SavePngAsync(library, "1", 25);
var media = entry.Media[0];
var worker = Worker(library);
// The worker records its conversion while the deletion writes its journal line (the file is still there).
var clock = new HookClock(library.Clock.Now, () => worker.RunOnceAsync(ct));
var deletion = new LibraryDeletion(library.Db, library.Layout, new AccountJournal(clock), library.Clock);
var result = await deletion.DeleteAsync(entry.Entry.Id, DeletionMode.Remember, ct);
Assert.AreEqual(1, clock.Pass?.Converted, "converted during the deletion");
var row = (await library.Db.Conversions.ListByMediaAsync(media.Id, ct)).Single();
Assert.AreEqual(MediaConversionState.Removed, row.State, "the row says the truth");
Assert.IsFalse(File.Exists(library.Layout.FullPath(account, row.RelativePath!)), "the converted file goes with the entry");
Assert.AreEqual(1, result.ConvertedFiles);
}
[TestMethod] [TestMethod]
public async Task AnUnpluggedAccountFolderIsNotCreated() public async Task AnUnpluggedAccountFolderIsNotCreated()
{ {
@@ -532,6 +663,29 @@ public sealed class LibraryConversionTests
Assert.AreEqual(0, await bed.Library.Db.Duplicates.CountPendingAsync(DuplicateOrigin.Import, ct), "never a probable duplicate of its original"); Assert.AreEqual(0, await bed.Library.Db.Duplicates.CountPendingAsync(DuplicateOrigin.Import, ct), "never a probable duplicate of its original");
} }
/// <summary>A clock that runs <c>work</c> once, the first time it is read (inside the journal append of a deletion).</summary>
private sealed class HookClock(DateTimeOffset now, Func<Task<LibraryConversionPass>> work) : IClock
{
public LibraryConversionPass? Pass { get; private set; }
public DateTimeOffset Now
{
get
{
if (Pass is null)
{
Pass = Task.Run(work).GetAwaiter().GetResult();
}
return now;
}
}
public TimeZoneInfo LocalZone => TestZones.Rome;
public Task Delay(TimeSpan time, CancellationToken ct) => Task.CompletedTask;
}
private static LibraryConversionEnvironment Environment(TestLibrary library, LongWorkGate? gate = null, ConversionThrottle? throttle = null) => new() private static LibraryConversionEnvironment Environment(TestLibrary library, LongWorkGate? gate = null, ConversionThrottle? throttle = null) => new()
{ {
Storage = library.Db, Storage = library.Db,
@@ -552,6 +706,12 @@ public sealed class LibraryConversionTests
return settings; return settings;
} }
private static async Task StorePngAsync(TestLibrary library, Account account, Entry entry, Media media, int scene)
{
using var image = TestImages.Scene(scene, 64, 48);
await library.Ingest.SaveMediaAsync(account, entry, media, new MediaContent { Content = new MemoryStream(TestImages.Png(image)), Extension = ".png" });
}
private static Task<(Account Account, EntryWithMedia Entry)> SavePngAsync(TestLibrary library, string id, int scene) private static Task<(Account Account, EntryWithMedia Entry)> SavePngAsync(TestLibrary library, string id, int scene)
{ {
using var image = TestImages.Scene(scene, 64, 48); using var image = TestImages.Scene(scene, 64, 48);
@@ -63,6 +63,69 @@ public sealed class Mp4RemuxerTests
AssertSameSamples(before.Audio, source, after.Audio, output, "audio"); AssertSameSamples(before.Audio, source, after.Audio, output, "audio");
} }
[TestMethod]
public void ATrimmedEndStaysHiddenInTheMp4()
{
// A passthrough trim: the edits show 0,3 s of video and of audio, the rest of the media is hidden.
var es = ElementaryStream.Load("BA1_Sony_D");
const int ShownFrames = 9; // 0,3 s: a whole number of milliseconds, as the movie timescale keeps the edit
Assert.IsGreaterThan(ShownFrames + 3, es.Count);
var shownVideo = (long)ShownFrames * TestVideos.FrameTicks;
var mov = TestVideos.Mov(es, new MovOptions(Audio: true, AudioPriming: 1024, VideoTrim: shownVideo, AudioTrim: 13230));
using var source = new MemoryStream(mov);
var before = Read(source);
Assert.AreEqual(shownVideo, before.Video!.EditSegmentDuration);
Assert.AreEqual(13230L, before.Audio!.EditSegmentDuration);
Assert.AreEqual(TimeSpan.FromSeconds((double)shownVideo / TestVideos.Timescale), before.Duration);
Assert.AreEqual(RemuxRefusal.None, Mp4Remuxer.Check(source, "clip.mov", out var plan, CancellationToken.None));
using var output = new MemoryStream(Remux(plan!, source));
var after = Read(output);
Assert.AreEqual(shownVideo, after.Video!.EditSegmentDuration, "the edits are carried over");
Assert.AreEqual(13230L, after.Audio!.EditSegmentDuration);
Assert.AreEqual((before.Audio.EditMediaTime, before.Video.EditMediaTime ?? 0), (after.Audio.EditMediaTime, after.Video.EditMediaTime ?? 0));
Assert.AreEqual(before.Duration, after.Duration, "the MP4 lasts what the source shows");
AssertSameSamples(before.Video, source, after.Video, output, "video");
AssertSameSamples(before.Audio, source, after.Audio, output, "audio");
// A frame «oltre la fine» is the last one shown, never one the edit hides.
using var reader = Febe.Core.Library.VideoFrameReader.Open(output, out var info);
Assert.IsTrue(info.Available);
var last = reader.Locate([TimeSpan.FromHours(1)]).Single();
Assert.IsLessThan(TimeSpan.FromSeconds((double)shownVideo / TestVideos.Timescale), last.Actual);
Assert.AreEqual(ShownFrames - 1, last.Sample);
}
[TestMethod]
[DataRow(44100, 0x6B)]
[DataRow(32000, 0x6B)]
[DataRow(24000, 0x69)]
[DataRow(22050, 0x69)]
[DataRow(16000, 0x69)]
public void Mp3IsLabelledMpeg1OrMpeg2AudioByItsRate(int rate, int objectType)
{
// ISO/IEC 14496-1 Table 5: 0x6B is ISO/IEC 11172-3 (MPEG-1, 32-48 kHz), 0x69 ISO/IEC 13818-3 (the lower rates).
var mov = TestVideos.Mov(ElementaryStream.Load("BA1_Sony_D"), new MovOptions(Audio: true, Mp3: true, AudioRate: rate));
using var source = new MemoryStream(mov);
Assert.AreEqual(RemuxRefusal.None, Mp4Remuxer.Check(source, "clip.mov", out var plan, CancellationToken.None));
var mp4 = Remux(plan!, source);
Assert.AreEqual(objectType, ObjectTypeIndication(mp4));
using var output = new MemoryStream(mp4);
Assert.AreEqual((AudioCodec.Mp3, rate), (Read(output).Audio!.Codec, Read(output).Audio!.SampleRate));
}
/// <summary>The objectTypeIndication of the DecoderConfigDescriptor (tag 4) in the <c>esds</c> of a file.</summary>
private static int ObjectTypeIndication(byte[] file)
{
var esds = file.AsSpan().IndexOf("esds"u8);
Assert.IsGreaterThan(0, esds);
var config = file.AsSpan(esds).IndexOf((ReadOnlySpan<byte>)[0x04, 0x80, 0x80, 0x80]);
Assert.IsGreaterThan(0, config);
return file[esds + config + 5];
}
[TestMethod] [TestMethod]
public void ExtraTracksAreDroppedAndCountedAndMp3IsKept() public void ExtraTracksAreDroppedAndCountedAndMp3IsKept()
{ {
@@ -340,24 +340,27 @@ internal static class TestVideos
HevcConfiguration = es.Hevc ? es.AvcC : null, HevcConfiguration = es.Hevc ? es.AvcC : null,
Language = o.Language, Language = o.Language,
EmptyEditDuration = o.VideoEmptyEdit, EmptyEditDuration = o.VideoEmptyEdit,
EditMediaTime = o.VideoTrim > 0 ? 0 : null,
EditSegmentDuration = o.VideoTrim > 0 ? o.VideoTrim : null,
}, },
}; };
for (var track = 0; track < (o.Audio ? 1 : 0) + o.ExtraAudioTracks; track++) for (var track = 0; track < (o.Audio ? 1 : 0) + o.ExtraAudioTracks; track++)
{ {
var frames = (int)Math.Ceiling(es.Count / 30.0 * 44100 / 1024) + (o.AudioPriming > 0 ? 1 : 0); var frames = (int)Math.Ceiling(es.Count / 30.0 * o.AudioRate / 1024) + (o.AudioPriming > 0 ? 1 : 0);
var payload = new byte[] { 0x21, 0x10, 0x04, 0x60, 0x8C, 0x1C, (byte)track }; var payload = new byte[] { 0x21, 0x10, 0x04, 0x60, 0x8C, 0x1C, (byte)track };
tracks.Add(new Mp4OutputTrack tracks.Add(new Mp4OutputTrack
{ {
IsVideo = false, IsVideo = false,
Timescale = 44100, Timescale = o.AudioRate,
Samples = [.. Enumerable.Range(0, frames).Select(i => new Mp4OutputSample(payload.Length, i * 1024L, i * 1024L, true))], Samples = [.. Enumerable.Range(0, frames).Select(i => new Mp4OutputSample(payload.Length, i * 1024L, i * 1024L, true))],
WriteSample = (_, s) => s.Write(payload), WriteSample = (_, s) => s.Write(payload),
AacConfiguration = o.Mp3 ? null : [0x12, 0x10], // AAC LC, 44.1 kHz, stereo AacConfiguration = o.Mp3 ? null : [0x12, 0x10], // AAC LC, 44.1 kHz, stereo
IsMp3 = o.Mp3, IsMp3 = o.Mp3,
SampleRate = 44100, SampleRate = o.AudioRate,
Channels = 2, Channels = 2,
Language = o.Language, Language = o.Language,
EditMediaTime = o.AudioPriming > 0 ? o.AudioPriming : null, EditMediaTime = o.AudioPriming > 0 ? o.AudioPriming : null,
EditSegmentDuration = o.AudioTrim > 0 ? o.AudioTrim : null,
}); });
} }
@@ -624,6 +627,9 @@ internal static class TestVideos
/// <param name="ExtraAudioTracks">Further audio tracks (an MP4 of Febe keeps one).</param> /// <param name="ExtraAudioTracks">Further audio tracks (an MP4 of Febe keeps one).</param>
/// <param name="AudioPriming">Samples of AAC priming hidden by the audio edit (media time of the edit); 0: no edit.</param> /// <param name="AudioPriming">Samples of AAC priming hidden by the audio edit (media time of the edit); 0: no edit.</param>
/// <param name="VideoEmptyEdit">Ticks (of 30000 a second) before the video starts: an empty edit.</param> /// <param name="VideoEmptyEdit">Ticks (of 30000 a second) before the video starts: an empty edit.</param>
/// <param name="VideoTrim">Ticks (of 30000 a second) of video shown by its edit, the rest hidden (a trim); 0: all.</param>
/// <param name="AudioRate">The sample rate (and timescale) of the audio; the AAC configuration always says 44,1 kHz.</param>
/// <param name="AudioTrim">Samples (of 44100 a second) of audio shown by its edit after the priming; 0: all.</param>
internal sealed record MovOptions( internal sealed record MovOptions(
bool Audio = false, bool Audio = false,
bool Mp3 = false, bool Mp3 = false,
@@ -633,4 +639,7 @@ internal sealed record MovOptions(
DateTimeOffset? Created = null, DateTimeOffset? Created = null,
DateTimeOffset? Modified = null, DateTimeOffset? Modified = null,
long AudioPriming = 0, long AudioPriming = 0,
long VideoEmptyEdit = 0); long VideoEmptyEdit = 0,
long VideoTrim = 0,
long AudioTrim = 0,
int AudioRate = 44100);
@@ -0,0 +1,39 @@
using Febe.Core.Codecs.H264;
namespace Febe.Tests.Codecs.H264;
/// <summary>
/// The recovery point SEI (H.264 §D.1.8, §D.2.8) that lets an exact frame start at an I picture (D12 of tappa E3): only
/// with recovery_frame_cnt 0 and exact_match_flag 1. The access units are written by the test.
/// </summary>
[TestClass]
public sealed class H264RecoveryPointTests
{
[TestMethod]
public void OnlyAnExactMatchIsAnExactStart()
{
// payload: ue(recovery_frame_cnt) = 0 «1», exact_match_flag, broken_link_flag 0, changing_slice_group_idc 00,
// then the stop bit of the payload: 1 1 0 00 1 00 (exact) and 1 0 0 00 1 00 (not exact).
Assert.IsTrue(H264Decoder.HasExactRecoveryPoint(AccessUnit(0xC4), 4), "exact_match_flag 1");
Assert.IsFalse(H264Decoder.HasExactRecoveryPoint(AccessUnit(0x84), 4), "exact_match_flag 0: pictures may differ from the IDR's");
// recovery_frame_cnt 1 («010»), exact: the pictures are exact only one frame later.
Assert.IsFalse(H264Decoder.HasExactRecoveryPoint(AccessUnit(0x51), 4));
// Annex B carries the same.
Assert.IsTrue(H264Decoder.HasExactRecoveryPoint([0, 0, 0, 1, .. Sei(0xC4), 0, 0, 0, 1, .. Slice], 0));
Assert.IsFalse(H264Decoder.HasExactRecoveryPoint([0, 0, 0, 1, .. Sei(0x84), 0, 0, 0, 1, .. Slice], 0));
}
/// <summary>A non-IDR slice NAL header and a byte of data: where the SEIs of an access unit end.</summary>
private static readonly byte[] Slice = [0x41, 0x9A];
/// <summary>An SEI NAL unit with one recovery point message of one byte, and its RBSP trailing bits.</summary>
private static byte[] Sei(byte payload) => [0x06, 0x06, 0x01, payload, 0x80];
private static byte[] AccessUnit(byte payload)
{
var sei = Sei(payload);
return [0, 0, 0, (byte)sei.Length, .. sei, 0, 0, 0, (byte)Slice.Length, .. Slice];
}
}
@@ -364,6 +364,58 @@ public sealed class ExportFormatsApiTests
Assert.IsFalse(File.Exists(Path.ChangeExtension(WebLibrary.PathOf(server, marta, later.Media[0]), ".jpg"))); Assert.IsFalse(File.Exists(Path.ChangeExtension(WebLibrary.PathOf(server, marta, later.Media[0]), ".jpg")));
} }
[TestMethod]
[Timeout(120_000, CooperativeCancellation = true)]
public async Task TheQuestionOfOneKindNeitherCountsNorQueuesTheOther()
{
var ct = TestContext.CancellationToken;
await using var server = await StartAsync();
var marta = await server.Db.Accounts.AddAsync(Make.Account("marta.demo"));
var png = await WebLibrary.AddPostAsync(server, marta, "png", Make.T0.AddDays(-1), WebLibrary.Image(PngBytes(8), ".png"));
var video = WebLibrary.DemoVideo(3);
var mov = await WebLibrary.AddPostAsync(server, marta, "mov", Make.T0.AddDays(-2), video with { Extension = ".mov" });
// Photos to JPG, «Solo i nuovi»: the PNG already in the library is left alone.
var (status, saved) = await server.SendJsonAsync(HttpMethod.Put, "/api/export/settings", new { libraryPhotoFormat = "jpg", convertExisting = false });
Assert.AreEqual(HttpStatusCode.OK, status, saved.ToString());
Assert.AreEqual(0, saved.Int("queued"));
// Then videos to MP4: the question counts the MOV only, and «Anche i N» queues it only.
var preview = await server.GetJsonAsync("/api/export/library-conversion/preview?video=mp4");
Assert.AreEqual((1, (long)video.Bytes.Length), (preview.Int("files"), preview.Long("bytes")), preview.ToString());
(status, saved) = await server.SendJsonAsync(HttpMethod.Put, "/api/export/settings", new { libraryVideoFormat = "mp4", convertExisting = true });
Assert.AreEqual(HttpStatusCode.OK, status, saved.ToString());
Assert.AreEqual(1, saved.Int("queued"));
Assert.IsEmpty(await server.Db.Conversions.ListByMediaAsync(png.Media[0].Id, ct), "the photo refused with «Solo i nuovi» stays so");
Assert.AreEqual(ExportFormat.Mp4, (await server.Db.Conversions.ListByMediaAsync(mov.Media[0].Id, ct)).Single().Format);
// Asked about both (no kind named), the preview counts what both formats would add.
Assert.AreEqual(1, (await server.GetJsonAsync("/api/export/library-conversion/preview")).Int("files"), "the PNG");
}
[TestMethod]
[Timeout(120_000, CooperativeCancellation = true)]
public async Task TwoQuickChangesOfTheSettingsAreBothKept()
{
await using var server = await StartAsync();
for (var round = 0; round < 10; round++)
{
var (status, saved) = await server.SendJsonAsync(HttpMethod.Put, "/api/export/settings", new { photoFormat = "jpg", videoFormat = "mp4" });
Assert.AreEqual(HttpStatusCode.OK, status, saved.ToString());
// Two clicks one after the other: two requests at once, each changing one format.
var photo = server.SendJsonAsync(HttpMethod.Put, "/api/export/settings", new { photoFormat = "original" });
var video = server.SendJsonAsync(HttpMethod.Put, "/api/export/settings", new { videoFormat = "original" });
foreach (var (code, body) in await Task.WhenAll(photo, video))
{
Assert.AreEqual(HttpStatusCode.OK, code, body.ToString());
}
var overview = await server.GetJsonAsync("/api/export");
Assert.AreEqual(("original", "original"), (overview.Str("photoFormat"), overview.Str("videoFormat")), $"round {round}");
}
}
// ------------------------------------------------------------------------------------------------- support // ------------------------------------------------------------------------------------------------- support
/// <summary>A HEIC as far as its name and brand go: Febe copies it as it is, it never decodes it.</summary> /// <summary>A HEIC as far as its name and brand go: Febe copies it as it is, it never decodes it.</summary>
+113
View File
@@ -46,6 +46,119 @@ public sealed class FrameServiceTests
} }
} }
[TestMethod]
[Timeout(120_000, CooperativeCancellation = true)]
public async Task ASlowReaderThatKeepsReadingGetsTheWholeZip()
{
var ct = TestContext.CancellationToken;
using var temp = new TempFolder("fotogrammi-lento");
var path = temp.Combine("rumore.mp4");
await File.WriteAllBytesAsync(path, NoiseVideo(), ct);
var service = new FrameService(new ManualClock(Make.T0)) { WriteStall = TimeSpan.FromMilliseconds(400) };
var plan = new FrameDownloadPlan(FrameMode.At, ExportFormat.Png, [
new FrameDownloadVideo("marta.demo", path, "rumore", [TimeSpan.Zero], Make.T0),
]);
// 64 KB every 150 ms: a frame of a few hundred KB takes longer than the 400 ms of a stall, but every piece goes.
using var sent = new MemoryStream();
var link = new SlowStream(sent, TimeSpan.FromMilliseconds(150));
await service.WriteZipAsync(link, plan, publicationTime: false, ct);
using var archive = new ZipArchive(new MemoryStream(sent.ToArray()), ZipArchiveMode.Read);
var entry = archive.Entries.Single();
Assert.IsGreaterThan(64L * 1024 * 3, entry.Length, "a frame that takes more than a stall to send");
Assert.IsGreaterThan(TimeSpan.FromMilliseconds(400), link.Busy, "the link was slower than a stall for the frame");
}
[TestMethod]
[Timeout(120_000, CooperativeCancellation = true)]
public async Task AReaderThatStopsReadingAbortsTheZip()
{
var ct = TestContext.CancellationToken;
using var temp = new TempFolder("fotogrammi-fermo");
var path = temp.Combine("video.mp4");
await File.WriteAllBytesAsync(path, H264PcmWriter.DemoVideo(), ct);
var service = new FrameService(new ManualClock(Make.T0)) { WriteStall = TimeSpan.FromMilliseconds(300) };
var plan = new FrameDownloadPlan(FrameMode.At, ExportFormat.Png, [
new FrameDownloadVideo("marta.demo", path, "post", [TimeSpan.Zero], Make.T0),
]);
await Assert.ThrowsAsync<OperationCanceledException>(() => service.WriteZipAsync(new SlowStream(Stream.Null, Timeout.InfiniteTimeSpan), plan, false, ct));
Assert.IsFalse(ct.IsCancellationRequested);
}
/// <summary>A video of one picture of noise (320 × 320): its PNG frame is several hundred KB.</summary>
private static byte[] NoiseVideo()
{
var random = new Random(28);
using var output = new MemoryStream();
H264PcmWriter.WriteMp4(output, 320, 320, 1, 8, _ =>
{
var p = new H264PcmPicture(320, 320);
for (var i = 0; i < p.Y.Length; i++)
{
p.Y[i] = (byte)random.Next(16, 236);
}
for (var i = 0; i < p.Cb.Length; i++)
{
p.Cb[i] = (byte)random.Next(16, 241);
p.Cr[i] = (byte)random.Next(16, 241);
}
return p;
});
return output.ToArray();
}
/// <summary>
/// A response body on a slow link: asynchronous writes only, each taking <c>perPiece</c> for every 64 KB it holds
/// (a write completes once its bytes are sent); an infinite time is a reader that stopped.
/// </summary>
private sealed class SlowStream(Stream inner, TimeSpan perPiece) : Stream
{
public TimeSpan Busy { get; private set; }
public override bool CanRead => false;
public override bool CanSeek => false;
public override bool CanWrite => true;
public override long Length => throw new NotSupportedException();
public override long Position { get => throw new NotSupportedException(); set => throw new NotSupportedException(); }
public override void Flush() => throw new InvalidOperationException("synchronous flush");
public override Task FlushAsync(CancellationToken cancellationToken) => Task.CompletedTask;
public override int Read(byte[] buffer, int offset, int count) => throw new NotSupportedException();
public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException();
public override void SetLength(long value) => throw new NotSupportedException();
public override void Write(byte[] buffer, int offset, int count) => throw new InvalidOperationException("synchronous write");
public override void Write(ReadOnlySpan<byte> buffer) => throw new InvalidOperationException("synchronous write");
public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) =>
WriteAsync(buffer.AsMemory(offset, count), cancellationToken).AsTask();
public override async ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken = default)
{
var wait = perPiece == Timeout.InfiniteTimeSpan ? Timeout.InfiniteTimeSpan : perPiece * ((buffer.Length + 65535) / 65536);
await Task.Delay(wait, cancellationToken);
if (wait != Timeout.InfiniteTimeSpan)
{
Busy += wait;
}
await inner.WriteAsync(buffer, cancellationToken);
}
}
/// <summary>A response body: asynchronous writes only.</summary> /// <summary>A response body: asynchronous writes only.</summary>
private sealed class AsyncOnlyStream(Stream inner) : Stream private sealed class AsyncOnlyStream(Stream inner) : Stream
{ {