Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
81883dd7bc | ||
|
|
1266724bec | ||
|
|
b3c15da821 | ||
|
|
edc55e4e68 | ||
|
|
7cc61624f1 | ||
|
|
a3126bbde9 | ||
|
|
009e7d6710 | ||
|
|
30cc6b0068 | ||
|
|
f48384b7d4 | ||
|
|
7d2346dfca | ||
|
|
f8a45eb482 | ||
|
|
7025ddf831 | ||
|
|
c5d176656e | ||
|
|
2efb408957 | ||
|
|
958cb71cd6 | ||
|
|
eb79b05fda | ||
|
|
d197715fc7 | ||
|
|
f5e12c5d74 | ||
|
|
d06b587806 | ||
|
|
91f49cdbb9 | ||
|
|
ab0d717424 | ||
|
|
724c5bda6f | ||
|
|
b746aff45d | ||
|
|
704c1ed9cf |
No files matched your search
@@ -1,10 +1,9 @@
|
||||
#!/usr/bin/env bash
|
||||
# Prepara il contenitore Debian del lavoro «prove» (debian:trixie, Debian 13 senza nient'altro: nessuna azione
|
||||
# JavaScript, quindi niente Node) perché nessuna prova si salti: Chromium vero della distribuzione (su Ubuntu è uno
|
||||
# snap, che nei contenitori non va) con le sue lingue, Xvfb, la lingua it_IT.UTF-8, fusi orari e gli stessi caratteri
|
||||
# dell'immagine di Febe; ICU, OpenSSL, zlib e libstdc++ per l'SDK .NET (dotnet.sh). git, curl e i certificati li
|
||||
# installa il passo prima dei sorgenti. setpriv, getent e l'utente nobody (65534) vengono con Debian (prove
|
||||
# dell'avvio del contenitore).
|
||||
# Prepares the Debian container of the «prove» job (debian:trixie, plain Debian 13: no JavaScript action, hence no
|
||||
# Node) so that no test is skipped: the distribution's real Chromium (on Ubuntu it is a snap, which does not work in
|
||||
# containers) with its languages, Xvfb, the it_IT.UTF-8 locale, time zones and the same fonts as the Febe image; ICU,
|
||||
# OpenSSL, zlib and libstdc++ for the .NET SDK (dotnet.sh). git, curl and the certificates are installed by the step
|
||||
# before the sources. setpriv, getent and the nobody user (65534) come with Debian (tests of the container start).
|
||||
#
|
||||
# .gitea/scripts/ambiente-prove.sh
|
||||
set -euo pipefail
|
||||
|
||||
@@ -1,20 +1,20 @@
|
||||
#!/usr/bin/env bash
|
||||
# Artefatti della CI, al posto di actions/upload-artifact (un'azione JavaScript, che vuole Node): i file vanno nel
|
||||
# registro dei pacchetti di Gitea, pacchetto generico febe-ci, una versione per esecuzione:
|
||||
# CI artifacts, instead of actions/upload-artifact (a JavaScript action, which needs Node): the files go to the Gitea
|
||||
# package registry, generic package febe-ci, one version per run:
|
||||
#
|
||||
# <versione>-ci.<numero> dal flusso verifica (come Febe-Setup-<versione>-ci.<numero>.exe)
|
||||
# <versione>-rilascio.<numero> dal flusso rilascio
|
||||
# <versione>-ci.<numero> from the verifica workflow (like Febe-Setup-<versione>-ci.<numero>.exe)
|
||||
# <versione>-rilascio.<numero> from the rilascio workflow
|
||||
#
|
||||
# con <versione> da Directory.Build.props e <numero> il numero dell'esecuzione (NUMERO). Si scaricano dalla pagina del
|
||||
# pacchetto su Gitea (proprietario ▸ Pacchetti ▸ febe-ci). La pulizia del lunedì (pulizia-docker.sh completa) toglie le
|
||||
# versioni create più di 14 giorni prima, come faceva la scadenza degli artefatti.
|
||||
# with <versione> from Directory.Build.props and <numero> the run number (NUMERO). They are downloaded from the package
|
||||
# page on Gitea (owner ▸ Packages ▸ febe-ci). The Monday cleanup (full pulizia-docker.sh) removes the versions created
|
||||
# more than 14 days earlier, as the artifact expiry used to do.
|
||||
#
|
||||
# .gitea/scripts/artefatti.sh verifica|rilascio <file>...
|
||||
#
|
||||
# Variabili: REGISTRY_TOKEN (token con «package: read and write», solo nell'intestazione di curl, mai stampato), GITEA_URL
|
||||
# (l'indirizzo del server, gitea.server_url), PROPRIETARIO, NUMERO. Senza REGISTRY_TOKEN un avviso e nessun file
|
||||
# caricato: il lavoro resta verde, come per l'immagine. Un file che manca o un rifiuto del registro fanno fallire il
|
||||
# passo. Un file con lo stesso nome già caricato (un nuovo tentativo della stessa esecuzione) si sostituisce.
|
||||
# Variables: REGISTRY_TOKEN (token with «package: read and write», only in the curl header, never printed), GITEA_URL
|
||||
# (the server address, gitea.server_url), PROPRIETARIO, NUMERO. Without REGISTRY_TOKEN a warning and no file uploaded:
|
||||
# the job stays green, as for the image. A missing file or a refusal by the registry fails the step. A file with the
|
||||
# same name already uploaded (a new attempt of the same run) is replaced.
|
||||
set -euo pipefail
|
||||
|
||||
flusso="${1:-}"
|
||||
@@ -46,7 +46,7 @@ proprietario="${PROPRIETARIO:?Manca PROPRIETARIO.}"
|
||||
base="${GITEA_URL:?Manca GITEA_URL.}"
|
||||
base="${base%/}/api/packages/$proprietario/generic/febe-ci/$versione"
|
||||
|
||||
# Una chiamata al registro: il codice HTTP, 000 se Gitea non risponde. Il token sta solo nell'intestazione di curl.
|
||||
# One call to the registry: the HTTP code, 000 if Gitea does not answer. The token is only in the curl header.
|
||||
chiedi() {
|
||||
local codice
|
||||
codice=$(curl -sS --max-time 900 -H "Authorization: token $REGISTRY_TOKEN" -o /dev/null -w '%{http_code}' "$@") || true
|
||||
|
||||
@@ -1,18 +1,18 @@
|
||||
#!/usr/bin/env bash
|
||||
# Controlli veloci prima di compilare (lavoro «controlli» della CI): pochi secondi, e fermano subito gli errori che
|
||||
# altrimenti si scoprirebbero dopo mezz'ora di prove. Si lanciano anche a mano, dalla radice del repository:
|
||||
# Quick checks before building (the «controlli» job of the CI): a few seconds, and they stop at once the errors that
|
||||
# would otherwise be found after half an hour of tests. They can also be run by hand, from the repository root:
|
||||
#
|
||||
# bash .gitea/scripts/controlli.sh
|
||||
#
|
||||
# 1. ogni script di shell del repository è sintassi valida (bash -n; sh -n per quelli in sh) e ha le righe Unix, come
|
||||
# i programmi awk della CI;
|
||||
# 2. i flussi della CI si leggono come YAML a blocchi: niente tabulazioni né righe Windows, rientri di due spazi fuori
|
||||
# dai blocchi di testo, «on:» e «jobs:» presenti; e sono fatti solo di comandi: nessun «uses:», cioè nessuna
|
||||
# azione (le azioni JavaScript vogliono Node, e la CI di Febe è scritta in casa: decisione del 18 novembre 2026);
|
||||
# 3. nessun file contiene segni di conflitto rimasti da un'unione;
|
||||
# 4. la versione di Directory.Build.props è nella forma x.y.z[-qualcosa], quella che installer/costruisci.sh accetta;
|
||||
# 5. ogni progetto elencato in Febe.slnx esiste;
|
||||
# 6. ogni file JSON del repository si legge (configurazioni, campioni ripuliti, criteri di Chromium), con json.awk.
|
||||
# 1. every shell script of the repository is valid syntax (bash -n; sh -n for the sh ones) and has Unix line
|
||||
# endings, like the awk programs of the CI;
|
||||
# 2. the CI workflows read as block YAML: no tabs nor Windows line endings, two-space indentation outside text
|
||||
# blocks, «on:» and «jobs:» present; and they are made of commands only: no «uses:», that is no action
|
||||
# (JavaScript actions need Node, and the Febe CI is written in house: decision of 18 November 2026);
|
||||
# 3. no file contains conflict markers left over from a merge;
|
||||
# 4. the version in Directory.Build.props has the form x.y.z[-something], the one installer/costruisci.sh accepts;
|
||||
# 5. every project listed in Febe.slnx exists;
|
||||
# 6. every JSON file of the repository parses (configurations, cleaned samples, Chromium policies), with json.awk.
|
||||
set -uo pipefail
|
||||
|
||||
radice="$(git rev-parse --show-toplevel)" || exit 2
|
||||
@@ -51,8 +51,8 @@ while IFS= read -r -d '' flusso; do
|
||||
if grep -n $'\t' "$flusso" > /dev/null; then
|
||||
errore "$flusso contiene tabulazioni: in YAML il rientro si fa con gli spazi."
|
||||
fi
|
||||
# Un blocco di testo («run: |», «>-») tiene tutte le righe più rientrate della sua chiave; fuori, i rientri sono di
|
||||
# due spazi in due e nessuna riga chiama un'azione.
|
||||
# A text block («run: |», «>-») holds all the lines indented more than its key; outside, indentation goes two
|
||||
# spaces at a time and no line calls an action.
|
||||
if rilievi=$(awk '
|
||||
FNR == 1 { blocco = -1; on = 0; jobs = 0 }
|
||||
{
|
||||
@@ -104,7 +104,7 @@ done < <(sed -n 's:.*<Project Path="\([^"]*\)".*:\1:p' Febe.slnx)
|
||||
echo " $(grep -c '<Project Path=' Febe.slnx) progetti"
|
||||
|
||||
echo "== File JSON"
|
||||
# Un solo processo per tutti i file; stampa i file che non si leggono, uno per riga, con il motivo e la riga.
|
||||
# A single process for all files; prints the files that do not parse, one per line, with the reason and the line.
|
||||
mapfile -d '' json < <(git ls-files -z -- '*.json')
|
||||
if ((${#json[@]} > 0)); then
|
||||
if ! guasti=$(awk -f .gitea/scripts/json.awk -f .gitea/scripts/json-valido.awk "${json[@]}"); then
|
||||
|
||||
@@ -1,29 +1,29 @@
|
||||
#!/usr/bin/env bash
|
||||
# Costruzione dell'immagine Docker di Febe con il builder buildx dell'esecuzione (docker-container), sempre con gli
|
||||
# stessi argomenti e le stesse etichette: la costruzione che si pubblica esce intera dalla cache di quella che si è
|
||||
# provata e scansionata, quindi gli strati sono gli stessi.
|
||||
# Builds the Febe Docker image with the buildx builder of the run (docker-container), always with the same arguments
|
||||
# and the same labels: the build that is published comes entirely from the cache of the one that was tested and
|
||||
# scanned, so the layers are the same.
|
||||
#
|
||||
# costruisci-immagine.sh builder <registro> il builder buildx dell'esecuzione (BUILDER), con il
|
||||
# driver docker-container e la configurazione di
|
||||
# buildkit che dice che il registro di casa risponde in
|
||||
# HTTP (al posto di docker/setup-buildx-action, un'azione
|
||||
# JavaScript); lo toglie pulizia-docker.sh esecuzione
|
||||
# costruisci-immagine.sh archivio <file.tar> <nome locale> archivio dell'immagine, per docker load e per Trivy
|
||||
# costruisci-immagine.sh pubblica <nome:etichetta>... spinta sul registro REGISTRY da buildx, con
|
||||
# REGISTRO_UTENTE e REGISTRO_TOKEN in una configurazione
|
||||
# del client solo sua, tolta alla fine; il demone non
|
||||
# parla mai con il registro (proverebbe HTTPS)
|
||||
# costruisci-immagine.sh builder <registro> the buildx builder of the run (BUILDER), with the
|
||||
# docker-container driver and the buildkit configuration
|
||||
# that says the home registry answers in HTTP (instead
|
||||
# of docker/setup-buildx-action, a JavaScript action);
|
||||
# pulizia-docker.sh esecuzione removes it
|
||||
# costruisci-immagine.sh archivio <file.tar> <nome locale> archive of the image, for docker load and for Trivy
|
||||
# costruisci-immagine.sh pubblica <nome:etichetta>... push to the REGISTRY registry by buildx, with
|
||||
# REGISTRO_UTENTE and REGISTRO_TOKEN in a client
|
||||
# configuration of its own, removed at the end; the
|
||||
# daemon never talks to the registry (it would try HTTPS)
|
||||
#
|
||||
# L'immagine è un manifest semplice, senza attestazioni (--provenance=false --sbom=false). Con le attestazioni, che
|
||||
# buildx aggiunge da sé, sarebbe un indice: Gitea tiene ogni manifest figlio come una versione a sé, sha256:… senza
|
||||
# etichetta, con la configurazione e gli strati, e togliere dal registro un'etichetta :sha- toglierebbe solo l'indice.
|
||||
# Con un manifest semplice gli strati stanno nella versione dell'etichetta, e la pulizia del registro li libera davvero.
|
||||
# The image is a plain manifest, without attestations (--provenance=false --sbom=false). With the attestations, which
|
||||
# buildx adds by itself, it would be an index: Gitea keeps every child manifest as a version of its own, sha256:…
|
||||
# without a tag, with the configuration and the layers, and removing a :sha- tag from the registry would remove only
|
||||
# the index. With a plain manifest the layers belong to the tag's version, and the registry cleanup really frees them.
|
||||
#
|
||||
# Variabili richieste: BUILDER, VERSIONE, GIT_COMMIT, FLUSSO (verifica o rilascio), ESECUZIONE (gitea.run_id).
|
||||
# Le etichette febe.ci.* dicono quale flusso, esecuzione, ramo e commit hanno costruito l'immagine. Non servono alla
|
||||
# pulizia: stanno anche nelle immagini pubblicate e Docker le copia in ogni contenitore creato da quelle, anche in un
|
||||
# Febe vero. Per questo qui non si mette mai febe.ci.prova, il segno dei soli contenitori di prova (prova-immagine.sh):
|
||||
# lo controlla PipelineTests.
|
||||
# Required variables: BUILDER, VERSIONE, GIT_COMMIT, FLUSSO (verifica or rilascio), ESECUZIONE (gitea.run_id).
|
||||
# The febe.ci.* labels say which workflow, run, branch and commit built the image. They are not used by the cleanup:
|
||||
# they are also in the published images and Docker copies them into every container created from those, even in a
|
||||
# real Febe. That is why febe.ci.prova, the mark of test containers only (prova-immagine.sh), is never set here:
|
||||
# PipelineTests checks it.
|
||||
set -euo pipefail
|
||||
|
||||
modo="${1:?Indica il modo: builder, archivio o pubblica.}"
|
||||
@@ -32,11 +32,11 @@ cd "$(git rev-parse --show-toplevel)"
|
||||
|
||||
if [[ "$modo" == builder ]]; then
|
||||
registro="${1:?Indica il registro, per esempio 192.168.30.23:3000.}"
|
||||
# Solo un nome di host (o un indirizzo) con la porta: il valore finisce in un file TOML.
|
||||
# Only a host name (or an address) with the port: the value ends up in a TOML file.
|
||||
[[ "$registro" =~ ^[A-Za-z0-9.-]+(:[0-9]+)?$ ]] || { echo "Registro non valido: «$registro»." >&2; exit 2; }
|
||||
configurazione="${RUNNER_TEMP:-/tmp}/buildkitd-${BUILDER:?}.toml"
|
||||
printf '[registry."%s"]\n http = true\n insecure = true\n' "$registro" > "$configurazione"
|
||||
# --buildkitd-config da buildx 0.13; prima si chiamava --config.
|
||||
# --buildkitd-config since buildx 0.13; before, it was called --config.
|
||||
opzione=--buildkitd-config
|
||||
aiuto=$(docker buildx create --help 2> /dev/null) || true
|
||||
[[ "$aiuto" == *--buildkitd-config* ]] || opzione=--config
|
||||
@@ -69,11 +69,11 @@ case "$modo" in
|
||||
etichette+=(-t "$nome")
|
||||
done
|
||||
|
||||
# Le credenziali in una configurazione del client tutta nostra, solo per questa spinta e poi tolta: quella del
|
||||
# runner non si tocca mai (niente jq per modificarla, nessuna credenziale che resti nella sua cartella). buildx le
|
||||
# passa al builder; il demone non c'entra (proverebbe HTTPS). Del client originale restano i plugin, i contesti e
|
||||
# il contesto corrente; i builder buildx li trova con BUILDX_CONFIG. Il nome è fisso per l'esecuzione, così il passo
|
||||
# «Pulizia (sempre)» la toglie anche dopo un'interruzione che salta la trap.
|
||||
# The credentials in a client configuration entirely our own, only for this push and then removed: the runner's
|
||||
# one is never touched (no jq to modify it, no credential left in its folder). buildx passes them to the builder;
|
||||
# the daemon is not involved (it would try HTTPS). From the original client we keep the plugins, the contexts and
|
||||
# the current context; the buildx builders are found through BUILDX_CONFIG. The name is fixed for the run, so the
|
||||
# «Pulizia (sempre)» step removes it even after an interruption that skips the trap.
|
||||
originale="${DOCKER_CONFIG:-$HOME/.docker}"
|
||||
configurazione="${RUNNER_TEMP:-/tmp}/febe-docker-${ESECUZIONE}"
|
||||
rm -rf "$configurazione"
|
||||
@@ -88,7 +88,7 @@ case "$modo" in
|
||||
[[ "$contesto" =~ ^[A-Za-z0-9][A-Za-z0-9_.+-]*$ ]] || contesto=""
|
||||
fi
|
||||
credenziali=$(printf '%s:%s' "$REGISTRO_UTENTE" "$REGISTRO_TOKEN" | base64 -w0)
|
||||
# Solo caratteri di base64, e il registro controllato sopra: il JSON si scrive senza bisogno di escape.
|
||||
# Only base64 characters, and the registry checked above: the JSON is written without any need for escapes.
|
||||
[[ "$credenziali" =~ ^[A-Za-z0-9+/]+=*$ ]] || { echo "Credenziali del registro non codificabili." >&2; exit 2; }
|
||||
(
|
||||
umask 077
|
||||
|
||||
@@ -1,19 +1,19 @@
|
||||
#!/usr/bin/env bash
|
||||
# Installa l'SDK .NET per un lavoro della CI, al posto di actions/setup-dotnet (un'azione JavaScript, che vuole Node).
|
||||
# Come quella prende l'ultimo SDK del canale (predefinito 10.0, come «10.0.x»), ma lo verifica: la versione e
|
||||
# l'impronta SHA-512 dell'archivio vengono dai metadati dei rilasci di Microsoft (letti con json.awk e dotnet-sdk.awk,
|
||||
# awk POSIX), l'archivio da builds.dotnet.microsoft.com, e si installa solo se l'impronta coincide. Mai uno script di
|
||||
# installazione scaricato al volo.
|
||||
# Installs the .NET SDK for a CI job, instead of actions/setup-dotnet (a JavaScript action, which needs Node). Like
|
||||
# that action it takes the newest SDK of the channel (default 10.0, like «10.0.x»), but it verifies it: the version
|
||||
# and the SHA-512 hash of the archive come from Microsoft's release metadata (read with json.awk and dotnet-sdk.awk,
|
||||
# POSIX awk), the archive from builds.dotnet.microsoft.com, and it is installed only if the hash matches. Never an
|
||||
# install script downloaded on the fly.
|
||||
#
|
||||
# .gitea/scripts/dotnet.sh [canale]
|
||||
#
|
||||
# Dove: nella cache degli strumenti del runner (RUNNER_TOOL_CACHE, il volume act-toolcache che act_runner monta in ogni
|
||||
# lavoro, anche nei contenitori), in febe-dotnet/<versione>; senza, nella cartella temporanea del lavoro. Una versione
|
||||
# già installata e verificata non si riscarica; le versioni più vecchie di febe-dotnet si tolgono. Aggiunge dotnet al
|
||||
# PATH dei passi seguenti (GITHUB_PATH) e scrive DOTNET_ROOT (GITHUB_ENV); fuori dalla CI stampa solo la cartella.
|
||||
# Serve curl, tar, sha512sum e awk. Nel contenitore Debian delle prove le librerie di sistema dell'SDK (ICU, OpenSSL)
|
||||
# le installa ambiente-prove.sh; sull'immagine del runner ICU non è garantito, e i lavori che ci girano (installatore,
|
||||
# windows, release) usano DOTNET_SYSTEM_GLOBALIZATION_INVARIANT=true.
|
||||
# Where: in the runner's tool cache (RUNNER_TOOL_CACHE, the act-toolcache volume that act_runner mounts in every job,
|
||||
# containers included), in febe-dotnet/<versione>; without it, in the job's temporary folder. A version already
|
||||
# installed and verified is not downloaded again; older versions in febe-dotnet are removed. Adds dotnet to the PATH
|
||||
# of the following steps (GITHUB_PATH) and writes DOTNET_ROOT (GITHUB_ENV); outside the CI it only prints the folder.
|
||||
# Needs curl, tar, sha512sum and awk. In the Debian container of the tests the SDK's system libraries (ICU, OpenSSL)
|
||||
# are installed by ambiente-prove.sh; on the runner image ICU is not guaranteed, and the jobs that run there
|
||||
# (installatore, windows, release) use DOTNET_SYSTEM_GLOBALIZATION_INVARIANT=true.
|
||||
set -euo pipefail
|
||||
|
||||
canale="${1:-10.0}"
|
||||
@@ -56,7 +56,7 @@ else
|
||||
mv "$temporanea/sdk" "$cartella"
|
||||
fi
|
||||
|
||||
# Le versioni precedenti, che nessun lavoro userà più (la CI fa un lavoro alla volta), e gli scarichi interrotti.
|
||||
# The earlier versions, which no job will use any more (the CI runs one job at a time), and interrupted downloads.
|
||||
for vecchia in "$radice"/* "$radice"/.scarico-*; do
|
||||
[[ -d "$vecchia" && "$vecchia" != "$cartella" && "$vecchia" != "$temporanea" ]] || continue
|
||||
rm -rf "$vecchia"
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
#!/usr/bin/env bash
|
||||
# JSON per i passi della CI, senza programmi di terzi (niente jq, niente Node; decisione di Alberto del 18 novembre
|
||||
# 2026): legge con json.awk e json-campi.awk, scrive le stringhe con json-stringa.awk. awk POSIX, niente rete.
|
||||
# JSON for the CI steps, without third-party programs (no jq, no Node; decision of Alberto of 18 November 2026):
|
||||
# reads with json.awk and json-campi.awk, writes strings with json-stringa.awk. POSIX awk, no network.
|
||||
#
|
||||
# json.sh campi <percorso> <campo,campo...> <file.json>... per ogni oggetto a quel posto, una riga con i campi
|
||||
# separati da un TAB (json-campi.awk): percorso vuoto
|
||||
# per l'oggetto radice, «*» per ogni elemento di un
|
||||
# elenco, per esempio «Results/*/Vulnerabilities/*»
|
||||
# json.sh stringa <testo> il testo come stringa JSON, virgolette comprese
|
||||
# json.sh campi <percorso> <campo,campo...> <file.json>... for each object at that place, one line with the fields
|
||||
# separated by a TAB (json-campi.awk): empty path for
|
||||
# the root object, «*» for every element of a list,
|
||||
# for example «Results/*/Vulnerabilities/*»
|
||||
# json.sh stringa <testo> the text as a JSON string, quotes included
|
||||
#
|
||||
# Un file che non è JSON valido: niente in uscita, il motivo su stderr, uscita 2. Lo provano le PipelineTests.
|
||||
# A file that is not valid JSON: no output, the reason on stderr, exit status 2. PipelineTests tests it.
|
||||
set -euo pipefail
|
||||
|
||||
qui="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
|
||||
@@ -1,21 +1,21 @@
|
||||
#!/usr/bin/env bash
|
||||
# Prova dell'immagine appena costruita, sul demone Docker del runner. Ogni contenitore gira SENZA RETE
|
||||
# (--network none): Febe non può raggiungere alcun sito, tanto meno Instagram (regola 1), e il controllo di salute
|
||||
# passa dalla rete interna del contenitore.
|
||||
# Ogni contenitore porta l'etichetta febe.ci.prova=<esecuzione>, messa qui con «docker run --label» e mai in
|
||||
# un'immagine: è il segno con cui pulizia-docker.sh riconosce un contenitore di prova, insieme al nome
|
||||
# febe-prova-<esecuzione>. Le etichette febe.ci.* dell'immagine non bastano: Docker le copia in ogni contenitore, anche
|
||||
# in un Febe vero avviato da un'immagine pubblicata.
|
||||
# Test of the image just built, on the runner's Docker daemon. Every container runs WITHOUT NETWORK (--network none):
|
||||
# Febe cannot reach any site, let alone Instagram (rule 1), and the health check goes through the container's
|
||||
# internal network.
|
||||
# Every container carries the label febe.ci.prova=<esecuzione>, set here with «docker run --label» and never in an
|
||||
# image: it is the mark by which pulizia-docker.sh recognises a test container, together with the name
|
||||
# febe-prova-<esecuzione>. The febe.ci.* labels of the image are not enough: Docker copies them into every container,
|
||||
# even into a real Febe started from a published image.
|
||||
#
|
||||
# .gitea/scripts/prova-immagine.sh <immagine> [esecuzione]
|
||||
#
|
||||
# 1. Chromium della distribuzione risponde e i criteri di Febe (niente password salvate) sono al loro posto;
|
||||
# 2. la lingua it_IT.UTF-8 è generata;
|
||||
# 3. il contenitore parte come dice la guida (profilo seccomp di Febe, password dell'interfaccia, PUID/PGID
|
||||
# predefiniti), il controllo di salute dell'immagine diventa «healthy» e «febe --controllo-salute» risponde;
|
||||
# 4. il processo 1 è Febe (niente tini) e nel contenitore non restano processi orfani da raccogliere;
|
||||
# 5. allo stop si ferma da solo, entro i 30 secondi che la guida concede.
|
||||
# La password è casuale, vive solo nell'ambiente del client Docker e non si stampa mai.
|
||||
# 1. the distribution's Chromium answers and the Febe policies (no saved passwords) are in place;
|
||||
# 2. the it_IT.UTF-8 locale is generated;
|
||||
# 3. the container starts as the guide says (Febe's seccomp profile, interface password, default PUID/PGID), the
|
||||
# image's health check becomes «healthy» and «febe --controllo-salute» answers;
|
||||
# 4. process 1 is Febe (no tini) and no orphan processes are left in the container to be reaped;
|
||||
# 5. on stop it stops by itself, within the 30 seconds the guide allows.
|
||||
# The password is random, lives only in the Docker client's environment and is never printed.
|
||||
set -euo pipefail
|
||||
|
||||
immagine="${1:?Indica quale immagine provare.}"
|
||||
@@ -24,8 +24,8 @@ radice="$(git rev-parse --show-toplevel)"
|
||||
etichette=(--label "febe.ci.prova=$esecuzione")
|
||||
nome="febe-prova-$esecuzione"
|
||||
|
||||
# Toglie il contenitore di prova di questa esecuzione (anche quello di un tentativo precedente), ma solo se porta il
|
||||
# segno della prova: un contenitore con lo stesso nome e senza segno resta, e «docker run --name» si ferma.
|
||||
# Removes the test container of this run (also the one of an earlier attempt), but only if it carries the test mark:
|
||||
# a container with the same name and without the mark stays, and «docker run --name» stops.
|
||||
togli() {
|
||||
local segno
|
||||
segno=$(docker container inspect -f '{{index .Config.Labels "febe.ci.prova"}}' "$nome" 2> /dev/null) || return 0
|
||||
@@ -52,7 +52,7 @@ docker run -d --name "$nome" --network none "${etichette[@]}" \
|
||||
--stop-timeout 30 -e FEBE_PASSWORD "$immagine" > /dev/null
|
||||
unset FEBE_PASSWORD
|
||||
|
||||
# Il primo controllo di salute dell'immagine arriva 30 secondi dopo l'avvio (HEALTHCHECK --interval=30s): fino a 3 minuti.
|
||||
# The image's first health check comes 30 seconds after the start (HEALTHCHECK --interval=30s): up to 3 minutes.
|
||||
stato=""
|
||||
for _ in $(seq 1 36); do
|
||||
if [[ "$(docker inspect -f '{{.State.Running}}' "$nome")" != "true" ]]; then
|
||||
@@ -77,16 +77,16 @@ fi
|
||||
echo "salute: healthy, e febe --controllo-salute risponde"
|
||||
|
||||
echo "== Processo 1 e processi orfani"
|
||||
# Senza tini il processo 1 è Febe, e il runtime .NET da processo 1 raccoglie anche i figli di Chromium rimasti orfani.
|
||||
# Un processo appena finito può restare «zombie» per un istante: conta solo uno che resta tale per 10 secondi.
|
||||
# Without tini process 1 is Febe, and the .NET runtime as process 1 also reaps the orphaned children of Chromium.
|
||||
# A process that has just ended may stay a «zombie» for an instant: only one that stays so for 10 seconds counts.
|
||||
primo="$(docker exec "$nome" cat /proc/1/comm)"
|
||||
if [[ "$primo" != "febe" ]]; then
|
||||
echo "Il processo 1 del contenitore è «$primo» invece di febe. Registro:" >&2
|
||||
docker logs --tail 80 "$nome" >&2 || true
|
||||
exit 1
|
||||
fi
|
||||
# I numeri dei processi zombie figli del processo 1, ordinati: quelli che tocca a lui raccogliere (gli orfani finiscono
|
||||
# lì). Uno sparito durante la lettura non conta.
|
||||
# The ids of the zombie processes that are children of process 1, sorted: the ones it has to reap (orphans end up
|
||||
# there). One that vanishes while being read does not count.
|
||||
orfani_zombie='for f in /proc/[0-9]*/status; do
|
||||
awk '\''$1 == "State:" { z = $2 } $1 == "Pid:" { p = $2 } $1 == "PPid:" { q = $2 } END { if (z == "Z" && q == 1) print p }'\'' "$f" 2> /dev/null
|
||||
done'
|
||||
|
||||
@@ -1,71 +1,70 @@
|
||||
#!/usr/bin/env bash
|
||||
# Pulizia del demone Docker del runner e del registro dei container. Il demone è lo stesso che costruisce Encelado,
|
||||
# Mimante e gli altri progetti di Alberto (e molto probabilmente quello delle applicazioni di Unraid), e ci può girare
|
||||
# anche un Febe vero. Dal 21 ottobre 2026 (decisione di Alberto) la pulizia toglie anche ciò che non serve più a
|
||||
# nessuno, di qualunque progetto: le immagini che nessun contenitore usa, la cache di costruzione, i resti di
|
||||
# act_runner. Mai un contenitore, un volume o una rete che non sia della CI.
|
||||
# Cleanup of the runner's Docker daemon and of the container registry. The daemon is the same one that builds
|
||||
# Encelado, Mimante and Alberto's other projects (and very probably the one of the Unraid applications), and a real
|
||||
# Febe may run on it too. Since 21 October 2026 (decision of Alberto) the cleanup also removes what nobody needs any
|
||||
# more, of any project: the images no container uses, the build cache, the leftovers of act_runner. Never a
|
||||
# container, a volume or a network that does not belong to the CI.
|
||||
#
|
||||
# Della CI di Febe si toglie ciò che si può provare suo. Le etichette febe.ci.workflow, febe.ci.run, febe.ci.ref e
|
||||
# febe.ci.commit dicono da dove viene un'immagine, ma NON scelgono che cosa togliere: stanno anche nelle immagini
|
||||
# pubblicate (:main, :sha-, :X.Y.Z, :latest), e Docker le copia in ogni contenitore creato da quelle, quindi le porta
|
||||
# anche un Febe vero. Ciò che si toglie si riconosce così:
|
||||
# - contenitori di prova: l'etichetta febe.ci.prova=<esecuzione>, che mette solo prova-immagine.sh con
|
||||
# «docker run --label» e che nessuna immagine porta (lo controlla PipelineTests), E il nome esatto
|
||||
# febe-prova-<la stessa esecuzione> (gli altri contenitori della prova, senza nome, girano con --rm e Docker li
|
||||
# toglie da sé appena finiscono);
|
||||
# - immagini provate: il nome locale febe-ci:<esecuzione>, tolto per nome, mai per identificativo e mai con -f. Se la
|
||||
# stessa immagine ha anche un nome del registro, si toglie solo febe-ci:<esecuzione>; se un contenitore la usa, resta;
|
||||
# - builder buildx: il contenitore buildx_buildkit_febe-ci-<esecuzione>0, con l'immagine moby/buildkit, e il suo
|
||||
# volume …_state, che contengono la cache di costruzione di quell'esecuzione;
|
||||
# - l'immagine febe:ci lasciata dal vecchio flusso di verifica (prima del 20 ottobre 2026), se nessuno la usa.
|
||||
# Di act_runner si tolgono i resti dei lavori: act_runner chiama tutto ciò che crea per un lavoro
|
||||
# GITEA-ACTIONS-TASK-<numero del compito>… (il contenitore del lavoro, i suoi volumi <nome> e <nome>-env, la sua rete
|
||||
# <nome>-<lavoro>-network). Solo i contenitori fermi e i volumi e le reti che nessun contenitore usa, più vecchi di 90
|
||||
# minuti: un lavoro che parte li crea e li usa subito. Il volume act-toolcache (la cache degli strumenti, condivisa fra
|
||||
# i lavori) resta.
|
||||
# Of the Febe CI, what can be proven to be its own is removed. The labels febe.ci.workflow, febe.ci.run, febe.ci.ref
|
||||
# and febe.ci.commit say where an image comes from, but they do NOT choose what to remove: they are also in the
|
||||
# published images (:main, :sha-, :X.Y.Z, :latest), and Docker copies them into every container created from those,
|
||||
# so a real Febe carries them too. What is removed is recognised like this:
|
||||
# - test containers: the label febe.ci.prova=<esecuzione>, which only prova-immagine.sh sets with
|
||||
# «docker run --label» and which no image carries (PipelineTests checks it), AND the exact name
|
||||
# febe-prova-<the same run> (the other test containers, without a name, run with --rm and Docker removes them by
|
||||
# itself as soon as they end);
|
||||
# - tested images: the local name febe-ci:<esecuzione>, removed by name, never by id and never with -f. If the same
|
||||
# image also has a registry name, only febe-ci:<esecuzione> is removed; if a container uses it, it stays;
|
||||
# - buildx builders: the container buildx_buildkit_febe-ci-<esecuzione>0, with the moby/buildkit image, and its
|
||||
# …_state volume, which hold the build cache of that run;
|
||||
# - the febe:ci image left by the old verification workflow (before 20 October 2026), if nobody uses it.
|
||||
# Of act_runner, the leftovers of the jobs are removed: act_runner names everything it creates for a job
|
||||
# GITEA-ACTIONS-TASK-<task number>… (the job container, its volumes <nome> and <nome>-env, its network
|
||||
# <nome>-<lavoro>-network). Only stopped containers, and volumes and networks no container uses, older than 90
|
||||
# minutes: a job that starts creates them and uses them at once. The act-toolcache volume (the tool cache, shared
|
||||
# among the jobs) stays.
|
||||
#
|
||||
# pulizia-docker.sh esecuzione <id> tutto ciò che ha creato l'esecuzione <id> (all'inizio e alla fine del suo
|
||||
# lavoro «immagine», sempre)
|
||||
# pulizia-docker.sh penzolanti le immagini senza nome che nessun contenitore usa e la cache di costruzione
|
||||
# penzolante del demone (quella che nessuna immagine condivide) non usata da
|
||||
# 24 ore, di tutti i progetti (alla fine di ogni lavoro «immagine», dopo
|
||||
# «esecuzione»)
|
||||
# pulizia-docker.sh residui [minuti] i resti di esecuzioni interrotte, più vecchi di N minuti (predefinito 90: un
|
||||
# lavoro dura al massimo 60 minuti, quindi nessuno di essi è ancora vivo)
|
||||
# pulizia-docker.sh settimanale residui, febe:ci, immagini senza nome più vecchie di 72 ore: la pulizia
|
||||
# stretta di prima del 21 ottobre 2026, ora solo a mano
|
||||
# pulizia-docker.sh completa residui, febe:ci, resti di act_runner, le immagini che nessun contenitore
|
||||
# usa create più di 24 ore fa, la cache di costruzione non usata da 24 ore e,
|
||||
# con REGISTRY_TOKEN, le etichette sha- del registro oltre le 10 più recenti e
|
||||
# gli artefatti della CI (febe-ci) di più di 14 giorni (flusso «pulizia», ogni
|
||||
# lunedì e a mano)
|
||||
# pulizia-docker.sh <modo> --prova elenca che cosa toglierebbe e non toglie nulla: solo comandi che leggono
|
||||
# (sul registro solo GET)
|
||||
# pulizia-docker.sh esecuzione <id> everything the run <id> created (at the start and at the end of its
|
||||
# «immagine» job, always)
|
||||
# pulizia-docker.sh penzolanti the unnamed images no container uses and the daemon's dangling build cache
|
||||
# (the part no image shares) unused for 24 hours, of all projects (at the end
|
||||
# of every «immagine» job, after «esecuzione»)
|
||||
# pulizia-docker.sh residui [minuti] the leftovers of interrupted runs, older than N minutes (default 90: a job
|
||||
# lasts at most 60 minutes, so none of them is still alive)
|
||||
# pulizia-docker.sh settimanale residui, febe:ci, unnamed images older than 72 hours: the narrow cleanup of
|
||||
# before 21 October 2026, now only by hand
|
||||
# pulizia-docker.sh completa residui, febe:ci, act_runner leftovers, the images no container uses
|
||||
# created more than 24 hours ago, the build cache unused for 24 hours and,
|
||||
# with REGISTRY_TOKEN, the registry's sha- tags beyond the 10 most recent and
|
||||
# the CI artifacts (febe-ci) older than 14 days («pulizia» workflow, every
|
||||
# Monday and by hand)
|
||||
# pulizia-docker.sh <modo> --prova lists what it would remove and removes nothing: only commands that read
|
||||
# (on the registry only GET)
|
||||
#
|
||||
# Gli argomenti si controllano tutti prima di toccare Docker: un'opzione diversa da --prova (--dry-run, -n, --Prova) o
|
||||
# un argomento in più (prova senza trattini) fermano tutto con codice 2, invece di far partire la pulizia vera al posto
|
||||
# della prova.
|
||||
# All the arguments are checked before touching Docker: an option other than --prova (--dry-run, -n, --Prova) or an
|
||||
# extra argument (prova without dashes) stops everything with code 2, instead of starting the real cleanup in place
|
||||
# of the dry run.
|
||||
#
|
||||
# Mai docker system prune, container prune, volume prune o network prune; mai image prune -a o builder prune -a senza
|
||||
# il filtro delle 24 ore; mai un contenitore, un volume o una rete che non sia della CI. Le immagini le toglie Docker
|
||||
# stesso (image prune), che non toglie mai un'immagine usata da un contenitore, nemmeno fermo; con -a, però, le toglie i
|
||||
# nomi in più, e lo script li scrive (nella prova li stima, secondo lo store). Sul registro mai main, latest o una
|
||||
# versione X.Y.Z: solo le etichette sha-<esadecimale> della verifica e gli artefatti <x.y.z>-ci.<n> e
|
||||
# <x.y.z>-rilascio.<n> del pacchetto generico febe-ci.
|
||||
# Never docker system prune, container prune, volume prune or network prune; never image prune -a or builder prune -a
|
||||
# without the 24-hour filter; never a container, a volume or a network that does not belong to the CI. The images are
|
||||
# removed by Docker itself (image prune), which never removes an image used by a container, not even a stopped one;
|
||||
# with -a, though, it removes their extra names, and the script writes them out (in the dry run it estimates them,
|
||||
# depending on the store). On the registry never main, latest or an X.Y.Z version: only the sha-<hexadecimal> tags of
|
||||
# the verification and the <x.y.z>-ci.<n> and <x.y.z>-rilascio.<n> artifacts of the generic febe-ci package.
|
||||
#
|
||||
# Nei modi «residui», «settimanale» e «completa» un contenitore di prova si toglie solo se è fermo. Uno ancora acceso
|
||||
# dopo 90 minuti (il suo lavoro è stato ucciso proprio durante la prova del contenitore) resta dov'è: lo si segnala, con
|
||||
# il comando per toglierlo a mano. I builder sono l'eccezione: sono sempre accesi e la loro cache se ne va solo
|
||||
# togliendo il contenitore; si riconoscono dal nome esatto e dall'immagine di buildkit, mai da un'etichetta.
|
||||
# In the «residui», «settimanale» and «completa» modes a test container is removed only if it is stopped. One still
|
||||
# running after 90 minutes (its job was killed right during the container test) stays where it is: it is reported,
|
||||
# with the command to remove it by hand. The builders are the exception: they are always running and their cache goes
|
||||
# away only by removing the container; they are recognised by the exact name and the buildkit image, never by a label.
|
||||
#
|
||||
# Un oggetto già sparito non è un errore: la pulizia si può ripetere. Nei modi «esecuzione», «penzolanti» e «residui»
|
||||
# un problema diventa un avviso (un lavoro verde non diventa rosso per la pulizia, che il flusso del lunedì ripete); nei
|
||||
# modi «settimanale» e «completa» fa fallire il lavoro, perché qualcuno lo guardi. Il registro è l'eccezione: un
|
||||
# rifiuto della sua API è solo un avviso, e il lunedì dopo si riprova.
|
||||
# An object already gone is not an error: the cleanup can be repeated. In the «esecuzione», «penzolanti» and «residui»
|
||||
# modes a problem becomes a warning (a green job does not turn red because of the cleanup, which the Monday workflow
|
||||
# repeats); in the «settimanale» and «completa» modes it fails the job, so that someone looks at it. The registry is
|
||||
# the exception: a refusal by its API is only a warning, and the following Monday it is tried again.
|
||||
#
|
||||
# Variabili per il registro (modo «completa»): REGISTRY_TOKEN (token con «package: read and write», mai stampato),
|
||||
# GITEA_API (l'API del server, per esempio https://gitea.example/api/v1) e PROPRIETARIO (il proprietario del pacchetto
|
||||
# febe). La scelta delle versioni da togliere sta in versioni-registro.sh, accanto a questo script.
|
||||
# Variables for the registry («completa» mode): REGISTRY_TOKEN (token with «package: read and write», never printed),
|
||||
# GITEA_API (the server's API, for example https://gitea.example/api/v1) and PROPRIETARIO (the owner of the febe
|
||||
# package). The choice of the versions to remove lives in versioni-registro.sh, next to this script.
|
||||
set -uo pipefail
|
||||
|
||||
uso() {
|
||||
@@ -93,21 +92,21 @@ esac
|
||||
cartella_script="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
problemi=0
|
||||
|
||||
# In prova: i contenitori (identificativo e nome) e i nomi di immagine che la pulizia vera toglierebbe, perché gli
|
||||
# elenchi che seguono li trattino come già tolti (un volume usato solo da un contenitore che se ne andrebbe, per
|
||||
# esempio, se ne andrebbe anche lui).
|
||||
# In a dry run: the containers (id and name) and the image names the real cleanup would remove, so that the lists
|
||||
# that follow treat them as already removed (a volume used only by a container that would go away, for example,
|
||||
# would go away too).
|
||||
previsti=()
|
||||
nomi_previsti=()
|
||||
|
||||
# Per il riepilogo: quanti oggetti per tipo, nell'ordine in cui compaiono, e lo spazio recuperato da Docker.
|
||||
# For the summary: how many objects per kind, in the order they appear, and the space reclaimed by Docker.
|
||||
declare -A conteggi=()
|
||||
tipi=()
|
||||
note=()
|
||||
|
||||
# La cache di costruzione che si pota è quella del builder del demone, «default». docker builder è un alias di docker
|
||||
# buildx quando c'è il plugin, e buildx lavora sul builder corrente: se qualcuno avesse reso corrente il builder
|
||||
# dell'esecuzione (costruisci-immagine.sh builder non lo fa), il modo «esecuzione» l'avrebbe appena tolto. Gli altri
|
||||
# comandi buildx di questo script indicano il builder per nome.
|
||||
# The build cache that is pruned is the one of the daemon's builder, «default». docker builder is an alias of docker
|
||||
# buildx when the plugin is there, and buildx works on the current builder: if someone had made the run's builder
|
||||
# current (costruisci-immagine.sh builder does not), the «esecuzione» mode would have just removed it. The other
|
||||
# buildx commands of this script name the builder explicitly.
|
||||
export BUILDX_BUILDER=default
|
||||
|
||||
avviso() {
|
||||
@@ -115,7 +114,7 @@ avviso() {
|
||||
problemi=$((problemi + 1))
|
||||
}
|
||||
|
||||
# Un avviso che non fa diventare rosso il lavoro: per il registro.
|
||||
# A warning that does not turn the job red: for the registry.
|
||||
segnala() {
|
||||
echo "::warning::$*"
|
||||
}
|
||||
@@ -125,7 +124,7 @@ conta() {
|
||||
conteggi[$1]=$((${conteggi[$1]:-0} + 1))
|
||||
}
|
||||
|
||||
# Vero se la prima parola è fra quelle che seguono.
|
||||
# True if the first word is among the ones that follow.
|
||||
fra() {
|
||||
local cercata="$1" voce
|
||||
shift
|
||||
@@ -135,9 +134,9 @@ fra() {
|
||||
return 1
|
||||
}
|
||||
|
||||
# Minuti trascorsi da un istante RFC 3339 come lo scrive Docker (Created di un contenitore o di un'immagine, CreatedAt
|
||||
# di un volume, {{json .Created}} di una rete, fra virgolette), con o senza frazioni di secondo, con «Z» o con lo scarto
|
||||
# dall'ora universale (+02:00). Se non si legge, 0: nel dubbio l'oggetto è giovane e resta.
|
||||
# Minutes elapsed since an RFC 3339 instant as Docker writes it (Created of a container or an image, CreatedAt of a
|
||||
# volume, {{json .Created}} of a network, in quotes), with or without fractions of a second, with «Z» or with the
|
||||
# offset from universal time (+02:00). If it cannot be read, 0: when in doubt the object is young and stays.
|
||||
eta_minuti() {
|
||||
local creato="${1:-}" secondi
|
||||
creato="${creato//\"/}"
|
||||
@@ -158,8 +157,8 @@ durata() {
|
||||
fi
|
||||
}
|
||||
|
||||
# Fra i contenitori dati (identificativi, uno per riga), quelli che restano dopo questa pulizia: in prova senza quelli
|
||||
# che la pulizia vera toglierebbe.
|
||||
# Among the given containers (ids, one per line), those that remain after this cleanup: in a dry run without the ones
|
||||
# the real cleanup would remove.
|
||||
restanti() {
|
||||
local id
|
||||
while read -r id; do
|
||||
@@ -168,9 +167,9 @@ restanti() {
|
||||
done <<< "${1:-}"
|
||||
}
|
||||
|
||||
# I contenitori di prova della CI, uno per riga «id nome»: l'etichetta febe.ci.prova (dell'esecuzione indicata, o di
|
||||
# qualunque se il primo argomento è vuoto) e il nome esatto febe-prova-<valore dell'etichetta>. Gli stati che seguono
|
||||
# restringono la scelta (Docker li unisce in OR). Esce con 1 se Docker non risponde.
|
||||
# The CI test containers, one per line «id name»: the label febe.ci.prova (of the given run, or of any run if the
|
||||
# first argument is empty) and the exact name febe-prova-<label value>. The states that follow narrow the choice
|
||||
# (Docker joins them with OR). Exits with 1 if Docker does not answer.
|
||||
contenitori_di_prova() {
|
||||
local run="$1"
|
||||
shift
|
||||
@@ -185,8 +184,8 @@ contenitori_di_prova() {
|
||||
done <<< "$elenco"
|
||||
}
|
||||
|
||||
# Toglie un contenitore con i suoi volumi anonimi (in prova lo elenca soltanto). Con «forza» anche se è acceso: solo
|
||||
# per quelli dell'esecuzione stessa e per i builder. Esce con 0 se il contenitore se ne va (o se ne andrebbe).
|
||||
# Removes a container with its anonymous volumes (in a dry run it only lists it). With «forza» even if it is running:
|
||||
# only for those of the run itself and for the builders. Exits with 0 if the container goes away (or would).
|
||||
togli_contenitore() {
|
||||
local id="$1" nome="$2" opzioni=(-v)
|
||||
[[ "${3:-}" == forza ]] && opzioni=(-f -v)
|
||||
@@ -203,8 +202,8 @@ togli_contenitore() {
|
||||
return 1
|
||||
}
|
||||
|
||||
# Toglie il nome locale febe-ci:<esecuzione> (o febe:ci), mai l'immagine per identificativo e mai con -f: se l'immagine
|
||||
# ha anche un altro nome (del registro, per esempio) quello resta; se un contenitore la usa, resta tutto.
|
||||
# Removes the local name febe-ci:<esecuzione> (or febe:ci), never the image by id and never with -f: if the image also
|
||||
# has another name (a registry one, for example) that one stays; if a container uses it, everything stays.
|
||||
togli_immagine() {
|
||||
local riferimento="$1" nomi
|
||||
[[ "$riferimento" =~ ^febe-ci:[0-9]+$ ]] || [[ "$riferimento" == febe:ci ]] \
|
||||
@@ -227,9 +226,9 @@ togli_immagine() {
|
||||
return 1
|
||||
}
|
||||
|
||||
# Un builder buildx della CI: prima con buildx (se questo client lo conosce), poi contenitore e volume per nome, perché
|
||||
# un lavoro diverso da quello che l'ha creato non ne ha la configurazione. Il contenitore si toglie solo se gira
|
||||
# l'immagine di buildkit, e il volume solo quando il contenitore non c'è più.
|
||||
# A CI buildx builder: first with buildx (if this client knows it), then container and volume by name, because a job
|
||||
# other than the one that created it does not have its configuration. The container is removed only if it runs the
|
||||
# buildkit image, and the volume only when the container is gone.
|
||||
togli_builder() {
|
||||
local builder="$1"
|
||||
[[ "$builder" =~ ^febe-ci-[0-9]+$ ]] || { avviso "Nome di builder inatteso: «$builder»."; return 1; }
|
||||
@@ -262,8 +261,8 @@ togli_builder() {
|
||||
return "$esito"
|
||||
}
|
||||
|
||||
# Un volume o una rete di act_runner. Docker stesso non toglie un volume che un contenitore usa, né una rete con un
|
||||
# contenitore acceso collegato.
|
||||
# A volume or a network of act_runner. Docker itself does not remove a volume a container uses, nor a network with a
|
||||
# running container attached.
|
||||
togli_volume() {
|
||||
local nome="$1"
|
||||
if ((prova)); then
|
||||
@@ -292,8 +291,8 @@ togli_rete() {
|
||||
return 1
|
||||
}
|
||||
|
||||
# Vero se nessun contenitore, acceso o fermo, usa il volume o la rete (in prova: nessuno che la pulizia vera
|
||||
# lascerebbe). Nel dubbio (Docker non risponde) falso: resta.
|
||||
# True if no container, running or stopped, uses the volume or the network (in a dry run: none that the real cleanup
|
||||
# would leave). When in doubt (Docker does not answer) false: it stays.
|
||||
nessuno_usa() {
|
||||
local tipo="$1" nome="$2" utenti
|
||||
if [[ "$tipo" == volume ]]; then
|
||||
@@ -326,7 +325,7 @@ residui() {
|
||||
echo "== Resti di esecuzioni interrotte della CI di Febe, più vecchi di $minuti minuti"
|
||||
local elenco id nome eta riferimento builder
|
||||
|
||||
# Contenitori di prova fermi: si tolgono. Senza -f: se nel frattempo uno ripartisse, Docker lo lascia stare.
|
||||
# Stopped test containers: they are removed. Without -f: if one started again in the meantime, Docker leaves it alone.
|
||||
if elenco=$(contenitori_di_prova "" exited created dead); then
|
||||
while read -r id nome; do
|
||||
[[ -n "${id:-}" ]] || continue
|
||||
@@ -337,7 +336,7 @@ residui() {
|
||||
avviso "Non riesco a elencare i contenitori di prova fermi."
|
||||
fi
|
||||
|
||||
# Contenitori di prova ancora accesi: non si toccano, si segnalano.
|
||||
# Test containers still running: they are not touched, they are reported.
|
||||
if elenco=$(contenitori_di_prova "" running restarting paused); then
|
||||
while read -r id nome; do
|
||||
[[ -n "${id:-}" ]] || continue
|
||||
@@ -350,7 +349,7 @@ residui() {
|
||||
avviso "Non riesco a elencare i contenitori di prova accesi."
|
||||
fi
|
||||
|
||||
# Immagini provate: solo i nomi febe-ci:<esecuzione>.
|
||||
# Tested images: only the febe-ci:<esecuzione> names.
|
||||
if elenco=$(docker image ls --filter "reference=febe-ci" --format '{{.Repository}}:{{.Tag}}'); then
|
||||
while read -r riferimento; do
|
||||
[[ "${riferimento:-}" =~ ^febe-ci:[0-9]+$ ]] || continue
|
||||
@@ -361,7 +360,7 @@ residui() {
|
||||
avviso "Non riesco a elencare le immagini febe-ci."
|
||||
fi
|
||||
|
||||
# Builder buildx. Il filtro per nome di Docker cerca una parte del nome: il nome esatto si controlla qui.
|
||||
# buildx builders. Docker's name filter matches part of the name: the exact name is checked here.
|
||||
if elenco=$(docker ps -a --no-trunc --filter "name=buildx_buildkit_febe-ci-" --format '{{.ID}} {{.Names}}'); then
|
||||
while read -r id nome; do
|
||||
[[ -n "${id:-}" ]] || continue
|
||||
@@ -376,7 +375,7 @@ residui() {
|
||||
fi
|
||||
}
|
||||
|
||||
# I resti della CI di Febe e l'immagine febe:ci del vecchio flusso (modi «settimanale» e «completa»).
|
||||
# The leftovers of the Febe CI and the febe:ci image of the old workflow («settimanale» and «completa» modes).
|
||||
resti_della_ci() {
|
||||
residui 90
|
||||
echo "== Immagine febe:ci del vecchio flusso di verifica"
|
||||
@@ -385,16 +384,16 @@ resti_della_ci() {
|
||||
fi
|
||||
}
|
||||
|
||||
# act_runner chiama i suoi oggetti GITEA-ACTIONS-TASK-<numero del compito>, seguito da «_WORKFLOW-…» o, nelle versioni
|
||||
# più vecchie, da «-WORKFLOW-…» con un'impronta in fondo.
|
||||
# act_runner names its objects GITEA-ACTIONS-TASK-<task number>, followed by «_WORKFLOW-…» or, in older versions, by
|
||||
# «-WORKFLOW-…» with a hash at the end.
|
||||
nome_act='^GITEA-ACTIONS-TASK-[0-9]+[-_]'
|
||||
|
||||
resti_di_act_runner() {
|
||||
local minuti="$1" elenco id nome eta
|
||||
echo "== Resti di act_runner (GITEA-ACTIONS-TASK-…) più vecchi di $minuti minuti: contenitori fermi, volumi e reti che nessun contenitore usa"
|
||||
|
||||
# Contenitori fermi. Il filtro per nome di Docker cerca una parte del nome: l'inizio esatto si controlla qui. Senza
|
||||
# -f: Docker non toglie un contenitore acceso.
|
||||
# Stopped containers. Docker's name filter matches part of the name: the exact start is checked here. Without -f:
|
||||
# Docker does not remove a running container.
|
||||
if elenco=$(docker ps -a --no-trunc --filter "name=GITEA-ACTIONS-TASK-" --filter "status=exited" \
|
||||
--filter "status=created" --filter "status=dead" --format '{{.ID}} {{.Names}}'); then
|
||||
while read -r id nome; do
|
||||
@@ -408,7 +407,7 @@ resti_di_act_runner() {
|
||||
avviso "Non riesco a elencare i contenitori di act_runner."
|
||||
fi
|
||||
|
||||
# Volumi che nessun contenitore usa, nemmeno fermo.
|
||||
# Volumes no container uses, not even a stopped one.
|
||||
if elenco=$(docker volume ls -q --filter "name=GITEA-ACTIONS-TASK-"); then
|
||||
while read -r nome; do
|
||||
[[ -n "${nome:-}" && "$nome" =~ $nome_act ]] || continue
|
||||
@@ -420,8 +419,8 @@ resti_di_act_runner() {
|
||||
avviso "Non riesco a elencare i volumi di act_runner."
|
||||
fi
|
||||
|
||||
# Reti a cui nessun contenitore è collegato, nemmeno fermo. Created di una rete è un istante di Go, che il modello
|
||||
# stampa come «2026-10-21 06:17:03 +0200 CEST»: in JSON è RFC 3339.
|
||||
# Networks no container is attached to, not even a stopped one. Created of a network is a Go time, which the template
|
||||
# prints as «2026-10-21 06:17:03 +0200 CEST»: in JSON it is RFC 3339.
|
||||
if elenco=$(docker network ls --no-trunc --filter "name=GITEA-ACTIONS-TASK-" --format '{{.ID}} {{.Name}}'); then
|
||||
while read -r id nome; do
|
||||
[[ -n "${id:-}" && "${nome:-}" =~ $nome_act ]] || continue
|
||||
@@ -434,9 +433,8 @@ resti_di_act_runner() {
|
||||
fi
|
||||
}
|
||||
|
||||
# Le immagini dei contenitori, accesi o fermi, tranne quelli che la pulizia toglierebbe: «identificativo immagine» una
|
||||
# per riga, l'immagine come la si è data a docker run (un nome o un identificativo). Solo lettura: serve all'elenco
|
||||
# della prova.
|
||||
# The images of the containers, running or stopped, except those the cleanup would remove: «id image» one per line,
|
||||
# the image as it was given to docker run (a name or an id). Read only: it serves the dry-run listing.
|
||||
immagini_in_uso() {
|
||||
local elenco id nome
|
||||
elenco=$(docker ps -a --no-trunc --format '{{.ID}} {{.Names}}') || return 1
|
||||
@@ -449,8 +447,8 @@ immagini_in_uso() {
|
||||
return 0
|
||||
}
|
||||
|
||||
# Il nome completo di un nome d'immagine, come lo ordina Docker: docker.io/library/ o docker.io/ davanti ai nomi di
|
||||
# Docker Hub scritti senza dominio, :latest se manca l'etichetta.
|
||||
# The full name of an image name, as Docker sorts it: docker.io/library/ or docker.io/ in front of Docker Hub names
|
||||
# written without a domain, :latest if the tag is missing.
|
||||
nome_completo() {
|
||||
local nome="$1" primo
|
||||
[[ "${nome##*/}" == *:* ]] || nome="$nome:latest"
|
||||
@@ -466,13 +464,13 @@ nome_completo() {
|
||||
fi
|
||||
}
|
||||
|
||||
# In prova: i nomi che «image prune -a» toglierebbe a un'immagine che un contenitore usa (i nomi e le immagini dei
|
||||
# contenitori, come li scrivono docker image ls e docker container inspect), uno per riga. L'immagine resta, ma i nomi
|
||||
# in più no (moby). Con lo store classico Docker toglie i nomi in ordine alfabetico del nome completo e si ferma
|
||||
# all'ultimo, l'unico che rifiuta di togliere perché un contenitore usa l'immagine (daemon/images/image_prune.go e
|
||||
# image_delete.go, isSingleReference): può andarsene anche il nome da cui il contenitore è stato creato. Con containerd
|
||||
# restano i nomi da cui i contenitori sono stati creati e, se uno la usa per identificativo e nessun nome resterebbe,
|
||||
# l'ultimo in ordine alfabetico (daemon/containerd/image_prune.go).
|
||||
# In a dry run: the names «image prune -a» would remove from an image a container uses (the names and the images of
|
||||
# the containers, as docker image ls and docker container inspect write them), one per line. The image stays, but the
|
||||
# extra names do not (moby). With the classic store Docker removes the names in alphabetical order of the full name
|
||||
# and stops at the last one, the only one it refuses to remove because a container uses the image
|
||||
# (daemon/images/image_prune.go and image_delete.go, isSingleReference): even the name the container was created from
|
||||
# may go. With containerd the names the containers were created from stay and, if one uses it by id and no name would
|
||||
# stay, the last one in alphabetical order (daemon/containerd/image_prune.go).
|
||||
nomi_che_perde() {
|
||||
local id="$1" nomi="$2" configurazioni="$3" nome completo configurazione resto per_id=0 ordinati quanti
|
||||
local -A protetti=()
|
||||
@@ -508,10 +506,10 @@ nomi_che_perde() {
|
||||
return 0
|
||||
}
|
||||
|
||||
# In prova: le immagini che la potatura toglierebbe, con dimensione ed età. Nessun contenitore le usa (a parte quelli
|
||||
# che questa pulizia toglierebbe) e sono state create più di N minuti fa; con «senza-nome» solo quelle senza nome. Con
|
||||
# «tutte», di un'immagine che un contenitore usa, i nomi in più che Docker le toglierebbe. È una stima fatta qui: nella
|
||||
# pulizia vera decide Docker (image prune).
|
||||
# In a dry run: the images the pruning would remove, with size and age. No container uses them (apart from those this
|
||||
# cleanup would remove) and they were created more than N minutes ago; with «senza-nome» only the unnamed ones. With
|
||||
# «tutte», for an image a container uses, the extra names Docker would remove from it. It is an estimate made here: in
|
||||
# the real cleanup Docker decides (image prune).
|
||||
elenca_immagini() {
|
||||
local minimo="$1" quali="$2" usate elenco id nome breve dimensione eta quante=0 configurazione
|
||||
local -A nomi=() elenco_nomi=() dimensioni=() aveva_nomi=() usata_da=()
|
||||
@@ -543,11 +541,11 @@ elenca_immagini() {
|
||||
[[ "$nome" == *":<none>" ]] || elenco_nomi[$id]+="$nome"$'\n'
|
||||
done <<< "$elenco"
|
||||
for id in "${ordine[@]}"; do
|
||||
# Un'immagine i cui nomi la pulizia toglie qui sopra se ne va già con l'ultimo.
|
||||
# An image whose names the cleanup removes above already goes away with the last one.
|
||||
[[ -n "${aveva_nomi[$id]:-}" && -z "${nomi[$id]}" ]] && continue
|
||||
breve="${id#sha256:}"
|
||||
if [[ -n "${usata_da[$id]+x}" ]]; then
|
||||
# Un contenitore la usa: resta. Con -a, però, Docker le toglie i nomi in più.
|
||||
# A container uses it: it stays. With -a, though, Docker removes its extra names.
|
||||
[[ "$quali" == tutte && -n "${elenco_nomi[$id]}" ]] || continue
|
||||
eta=$(eta_minuti "$(docker image inspect -f '{{.Created}}' "$id" 2> /dev/null)")
|
||||
((eta >= minimo)) || continue
|
||||
@@ -575,8 +573,8 @@ elenca_immagini() {
|
||||
((quante > 0)) || echo " nessuna"
|
||||
}
|
||||
|
||||
# In prova: quanta cache di costruzione ha il demone. Quanta ne toglierebbe la potatura Docker non lo dice senza
|
||||
# toglierla: al più quella che nessuno sta usando («RECLAIMABLE» di docker system df).
|
||||
# In a dry run: how much build cache the daemon has. How much of it the pruning would remove Docker does not say
|
||||
# without removing it: at most the part nobody is using («RECLAIMABLE» of docker system df).
|
||||
elenca_cache() {
|
||||
local riga tipo dimensione recuperabile
|
||||
riga=$(docker system df --format '{{.Type}}|{{.Size}}|{{.Reclaimable}}' 2> /dev/null | grep '^Build Cache|')
|
||||
@@ -589,11 +587,11 @@ elenca_cache() {
|
||||
note+=("cache di costruzione: $dimensione in tutto, al più $recuperabile da togliere")
|
||||
}
|
||||
|
||||
# Lo store delle immagini del demone: «containerd» (io.containerd.snapshotter.v1, predefinito nelle installazioni nuove
|
||||
# di Docker Engine dalla 29) o «classico» (overlay2 e gli altri driver di prima). Ne dipende da quando contano le 24 ore
|
||||
# di image prune --filter until: con lo store classico dalla costruzione dell'immagine (Created della configurazione),
|
||||
# con containerd da quando il nome è arrivato sul demone (CreatedAt del suo record, che un nuovo pull dello stesso nome
|
||||
# non cambia).
|
||||
# The daemon's image store: «containerd» (io.containerd.snapshotter.v1, the default in new Docker Engine installations
|
||||
# since 29) or «classico» (overlay2 and the other earlier drivers). It decides from when the 24 hours of image prune
|
||||
# --filter until count: with the classic store from the image build (Created of the configuration), with containerd
|
||||
# from when the name arrived on the daemon (CreatedAt of its record, which a new pull of the same name does not
|
||||
# change).
|
||||
store=""
|
||||
rileva_store() {
|
||||
local stato
|
||||
@@ -611,21 +609,21 @@ rileva_store() {
|
||||
esac
|
||||
}
|
||||
|
||||
# Ogni immagine con ciascuno dei suoi nomi, «identificativo nome» una per riga (<none>:<none> se non ne ha).
|
||||
# Every image with each of its names, «id name» one per line (<none>:<none> if it has none).
|
||||
immagini_e_nomi() {
|
||||
docker image ls --no-trunc --format '{{.ID}} {{.Repository}}:{{.Tag}}' 2> /dev/null
|
||||
}
|
||||
|
||||
# Lo spazio recuperato secondo Docker: «Total reclaimed space: 1.2GB» (docker) o «Total: 1.2GB» (buildx).
|
||||
# The space reclaimed according to Docker: «Total reclaimed space: 1.2GB» (docker) or «Total: 1.2GB» (buildx).
|
||||
spazio_recuperato() {
|
||||
local riga
|
||||
riga=$(grep -E '^Total' <<< "$1" | tail -n 1 | sed -E 's/^Total( reclaimed space)?:[[:space:]]*//')
|
||||
echo "${riga:-0B}"
|
||||
}
|
||||
|
||||
# Una potatura di immagini di Docker: i nomi tolti, quante immagini e quanto spazio. Un errore è un avviso. I nomi si
|
||||
# confrontano prima e dopo: con -a Docker toglie anche i nomi in più di un'immagine che un contenitore usa e che resta,
|
||||
# e il registro del lavoro lo dice.
|
||||
# A Docker image pruning: the names removed, how many images and how much space. An error is a warning. The names are
|
||||
# compared before and after: with -a Docker also removes the extra names of an image a container uses and that stays,
|
||||
# and the job log says so.
|
||||
pota_immagini() {
|
||||
local cosa="$1" uscita prima dopo recuperato prima_nomi dopo_nomi dopo_id id nome breve
|
||||
shift
|
||||
@@ -659,7 +657,7 @@ pota_immagini() {
|
||||
fi
|
||||
}
|
||||
|
||||
# Una potatura della cache di costruzione: quanto spazio. Un errore è un avviso.
|
||||
# A build cache pruning: how much space. An error is a warning.
|
||||
pota_cache() {
|
||||
local cosa="$1" uscita recuperato
|
||||
shift
|
||||
@@ -672,8 +670,8 @@ pota_cache() {
|
||||
note+=("$cosa: $recuperato recuperati")
|
||||
}
|
||||
|
||||
# Una chiamata all'API di Gitea con il token del registro, che sta solo nell'intestazione di curl e mai nel registro
|
||||
# del lavoro. Stampa il codice HTTP: 000 se Gitea non risponde.
|
||||
# A call to the Gitea API with the registry token, which is only in the curl header and never in the job log. Prints
|
||||
# the HTTP code: 000 if Gitea does not answer.
|
||||
chiedi() {
|
||||
local metodo="$1" indirizzo="$2" uscita="$3" codice
|
||||
codice=$(curl -sS --max-time 30 -X "$metodo" -H "Authorization: token $REGISTRY_TOKEN" -H "Accept: application/json" \
|
||||
@@ -690,21 +688,22 @@ spiega() {
|
||||
esac
|
||||
}
|
||||
|
||||
# Le etichette sha- del pacchetto febe oltre le 10 più recenti, con l'API dei pacchetti di Gitea 28:
|
||||
# GET /api/v1/packages/{proprietario}/container/febe?page=N&limit=50 le versioni, una pagina alla volta finché
|
||||
# ne arriva una vuota (il server può darne
|
||||
# meno di 50 per pagina)
|
||||
# DELETE /api/v1/packages/{proprietario}/container/febe/{versione} una versione (risponde 204)
|
||||
# Quali togliere lo sceglie versioni-registro.sh (awk POSIX con json.awk: niente Node, niente jq); qui si ricontrolla
|
||||
# la forma sha-<esadecimale> prima di ogni DELETE. Ogni rifiuto dell'API è un avviso che non fa diventare rosso il
|
||||
# lavoro, e dopo un rifiuto il registro non si tocca più (il token è lo stesso). Le versioni sha256:… senza etichetta (i
|
||||
# manifest figli di un indice, con gli strati) non si toccano mai: l'API non dice se un'etichetta le usa ancora. Si
|
||||
# dice solo quante sono; la CI pubblica manifest semplici (costruisci-immagine.sh), quindi non dovrebbero essercene, e
|
||||
# quelle che nessuna etichetta usa le toglie una regola di pulizia di Gitea (docs/processo.md, «Registro dei container»).
|
||||
# Poi gli artefatti della CI (artefatti.sh): le versioni del pacchetto generico febe-ci create più di 14 giorni fa,
|
||||
# The sha- tags of the febe package beyond the 10 most recent, with the package API of Gitea 28:
|
||||
# GET /api/v1/packages/{proprietario}/container/febe?page=N&limit=50 the versions, one page at a time until an
|
||||
# empty one arrives (the server may give
|
||||
# fewer than 50 per page)
|
||||
# DELETE /api/v1/packages/{proprietario}/container/febe/{versione} one version (answers 204)
|
||||
# Which ones to remove is chosen by versioni-registro.sh (POSIX awk with json.awk: no Node, no jq); here the
|
||||
# sha-<hexadecimal> form is checked again before every DELETE. Every refusal by the API is a warning that does not
|
||||
# turn the job red, and after a refusal the registry is not touched any more (the token is the same). The sha256:…
|
||||
# versions without a tag (the child manifests of an index, with the layers) are never touched: the API does not say
|
||||
# whether a tag still uses them. Only their number is reported; the CI publishes plain manifests
|
||||
# (costruisci-immagine.sh), so there should be none, and those no tag uses are removed by a Gitea cleanup rule
|
||||
# (docs/processo.md, «Registro dei container»).
|
||||
# Then the CI artifacts (artefatti.sh): the versions of the generic febe-ci package created more than 14 days ago,
|
||||
# GET /api/v1/packages/{proprietario}/generic/febe-ci?page=N&limit=50
|
||||
# DELETE /api/v1/packages/{proprietario}/generic/febe-ci/{versione} la versione con i suoi file (204)
|
||||
# solo con la forma <x.y.z>-ci.<n> o <x.y.z>-rilascio.<n>, ricontrollata prima di ogni DELETE.
|
||||
# DELETE /api/v1/packages/{proprietario}/generic/febe-ci/{versione} the version with its files (204)
|
||||
# only with the form <x.y.z>-ci.<n> or <x.y.z>-rilascio.<n>, checked again before every DELETE.
|
||||
registro() {
|
||||
local tenere=10
|
||||
echo "== Registro: le etichette sha- del pacchetto febe oltre le $tenere più recenti"
|
||||
@@ -737,9 +736,9 @@ registro() {
|
||||
artefatti_della_ci
|
||||
}
|
||||
|
||||
# Le pagine delle versioni di un pacchetto nella cartella, pagina-<n>.json, fino alla prima vuota (il server può darne
|
||||
# meno di 50 per pagina). Esce con 0 se le ha lette, 1 se il pacchetto non c'è (404 alla prima pagina), 2 se l'API
|
||||
# rifiuta (e lo segnala).
|
||||
# The pages of the versions of a package in the folder, pagina-<n>.json, up to the first empty one (the server may give
|
||||
# fewer than 50 per page). Exits with 0 if it read them, 1 if the package is not there (404 on the first page), 2 if
|
||||
# the API refuses (and reports it).
|
||||
pagine() {
|
||||
local base="$1" cartella="$2" nome="$3" pagina codice
|
||||
for ((pagina = 1; ; pagina++)); do
|
||||
@@ -761,7 +760,7 @@ pagine() {
|
||||
done
|
||||
}
|
||||
|
||||
# Le etichette sha- del contenitore febe, dalle pagine già lette.
|
||||
# The sha- tags of the febe container, from the pages already read.
|
||||
contenitore() {
|
||||
local base="$1" cartella="$2" scelte senza_etichetta quante codice
|
||||
if ! scelte=$(bash "$cartella_script/versioni-registro.sh" "$tenere" "$cartella"/pagina-*.json) \
|
||||
@@ -800,8 +799,8 @@ contenitore() {
|
||||
done <<< "$scelte"
|
||||
}
|
||||
|
||||
# Gli artefatti della CI (artefatti.sh): le versioni del pacchetto generico febe-ci create più di 14 giorni fa, come la
|
||||
# scadenza degli artefatti di una volta.
|
||||
# The CI artifacts (artefatti.sh): the versions of the generic febe-ci package created more than 14 days ago, like the
|
||||
# artifact expiry of the old days.
|
||||
artefatti_della_ci() {
|
||||
local giorni=14 base="${GITEA_API%/}/packages/$PROPRIETARIO/generic/febe-ci" cartella esito scelte versione creata codice
|
||||
echo "== Registro: gli artefatti della CI (pacchetto febe-ci) creati più di $giorni giorni fa"
|
||||
@@ -841,8 +840,8 @@ artefatti_della_ci() {
|
||||
done <<< "$scelte"
|
||||
}
|
||||
|
||||
# La cache con lo stesso limite del lunedì: senza, a ogni push di ogni ramo se ne andrebbero gli strati intermedi e le
|
||||
# cache montate (RUN --mount=type=cache) che le costruzioni degli altri progetti hanno appena usato.
|
||||
# The cache with the same limit as on Monday: without it, every push of every branch would remove the intermediate
|
||||
# layers and the mounted caches (RUN --mount=type=cache) that the builds of the other projects have just used.
|
||||
penzolanti() {
|
||||
echo "== Immagini senza nome che nessun contenitore usa e cache di costruzione penzolante non usata da 24 ore, di tutti i progetti"
|
||||
if ((prova)); then
|
||||
@@ -864,9 +863,9 @@ settimanale() {
|
||||
fi
|
||||
}
|
||||
|
||||
# Tutto ciò che fa «settimanale» (le immagini senza nome più vecchie di 72 ore sono fra quelle che nessun contenitore
|
||||
# usa create più di 24 ore fa) e in più i resti di act_runner, le immagini e la cache di tutti e il registro. Prima i
|
||||
# contenitori, così le loro immagini, i loro volumi e le loro reti restano senza nessuno che li usi.
|
||||
# Everything «settimanale» does (the unnamed images older than 72 hours are among those no container uses created
|
||||
# more than 24 hours ago) plus the act_runner leftovers, everyone's images and cache, and the registry. Containers
|
||||
# first, so that their images, volumes and networks are left with nobody using them.
|
||||
completa() {
|
||||
resti_della_ci
|
||||
resti_di_act_runner 90
|
||||
|
||||
@@ -1,15 +1,15 @@
|
||||
#!/usr/bin/env bash
|
||||
# Riepilogo dei risultati delle prove (file .trx di «dotnet test --logger trx»): superate, fallite e saltate per ogni
|
||||
# file, i nomi delle fallite e i motivi delle saltate. Lo scrive nel registro e, se il runner lo offre, nel riepilogo
|
||||
# del lavoro (GITHUB_STEP_SUMMARY). Nessun corpo di risposta né dato personale: solo nomi di prove e messaggi.
|
||||
# Summary of the test results (.trx files of «dotnet test --logger trx»): passed, failed and skipped for each file,
|
||||
# the names of the failed ones and the reasons of the skipped ones. It writes it to the log and, if the runner offers
|
||||
# it, to the job summary (GITHUB_STEP_SUMMARY). No response body nor personal data: only test names and messages.
|
||||
#
|
||||
# .gitea/scripts/riepilogo-prove.sh <cartella dei .trx> [saltate ammesse]
|
||||
#
|
||||
# Esce con 1 se una prova è fallita, se le saltate sono più di quelle ammesse (predefinito 0: nella CI ci sono
|
||||
# Chromium e Xvfb, quindi nessuna prova ha motivo di saltarsi) o se non c'è nessun risultato. Fa eccezione solo la
|
||||
# categoria «da fare»: le inconclusive di FeaturesStillToDo (flussi di conformità H.264 delle parti che il
|
||||
# decodificatore non gestisce ancora) il cui motivo comincia con «da fare: » si elencano e non contano fra le saltate.
|
||||
# Qualunque altra inconclusiva, anche con «da fare: » nel messaggio, è una saltata.
|
||||
# Exits with 1 if a test failed, if the skipped ones are more than those allowed (default 0: the CI has Chromium and
|
||||
# Xvfb, so no test has a reason to be skipped) or if there is no result at all. The only exception is the «da fare»
|
||||
# category: the inconclusive results of FeaturesStillToDo (H.264 conformance streams for the parts the decoder does
|
||||
# not handle yet) whose reason starts with «da fare: » are listed and do not count among the skipped ones.
|
||||
# Any other inconclusive result, even with «da fare: » in its message, is a skipped one.
|
||||
set -euo pipefail
|
||||
|
||||
cartella="${1:?Indica la cartella con i file .trx.}"
|
||||
@@ -29,10 +29,10 @@ trap 'rm -f "$riepilogo"' EXIT
|
||||
fallite_totali=0
|
||||
saltate_totali=0
|
||||
dafare_totali=0
|
||||
# «Da fare»: una inconclusiva di FeaturesStillToDo il cui motivo comincia con «da fare: » subito dopo la cornice di MSTest
|
||||
# («Assert.Inconclusive. », «Assert.Inconclusive failed. », «Assert.Inconclusive non riuscito. »): segna una parte non
|
||||
# ancora scritta, non un ambiente rotto, e si conta a parte. Il nome della prova e l'inizio del motivo sono entrambi
|
||||
# vincolati: nessun'altra prova può saltarsi in silenzio scrivendo «da fare: » nel messaggio.
|
||||
# «Da fare»: an inconclusive result of FeaturesStillToDo whose reason starts with «da fare: » right after the MSTest
|
||||
# frame («Assert.Inconclusive. », «Assert.Inconclusive failed. », «Assert.Inconclusive non riuscito. »): it marks a part
|
||||
# not written yet, not a broken environment, and is counted apart. Both the test name and the start of the reason are
|
||||
# constrained: no other test can skip silently by writing «da fare: » in its message.
|
||||
da_fare='$1 != "Passed" && $1 != "Failed" && $1 != "Error" && $1 != "Timeout" && $1 != "Aborted" && $2 ~ /^FeaturesStillToDo( |\(|$)/ && $3 ~ /^Assert\.Inconclusive[^.]*\. *da fare: /'
|
||||
{
|
||||
echo "### Prove"
|
||||
@@ -43,7 +43,7 @@ da_fare='$1 != "Passed" && $1 != "Failed" && $1 != "Error" && $1 != "Timeout" &&
|
||||
|
||||
for trx in "${file[@]}"; do
|
||||
nome="$(basename "$trx")"
|
||||
# Un risultato per riga (i .trx sono XML su più righe), poi nome, esito e primo messaggio di ciascuno.
|
||||
# One result per line (the .trx files are XML over several lines), then name, outcome and first message of each.
|
||||
righe="$(tr '\r\n' ' ' < "$trx" | sed 's/<UnitTestResult /\n<UnitTestResult /g' | awk '
|
||||
function attributo(testo, chiave, inizio) {
|
||||
if (match(testo, chiave "=\"[^\"]*\"")) {
|
||||
@@ -83,14 +83,14 @@ for trx in "${file[@]}"; do
|
||||
|
||||
if (( fallite > 0 )); then
|
||||
echo " Fallite:"
|
||||
# Le righe in più si leggono e si scartano (niente «head»: con pipefail il SIGPIPE fermerebbe lo script).
|
||||
# The extra lines are read and discarded (no «head»: with pipefail the SIGPIPE would stop the script).
|
||||
printf '%s\n' "$righe" | awk -F'\t' '$1 == "Failed" || $1 == "Error" || $1 == "Timeout" || $1 == "Aborted" {
|
||||
if (++n > 50) next; m = $3; if (length(m) > 300) m = substr(m, 1, 300) "…"; print " - " $2 ": " m }'
|
||||
fi
|
||||
|
||||
if (( saltate > 0 )); then
|
||||
echo " Saltate, per motivo:"
|
||||
# Il motivo senza la cornice di MSTest («Il metodo … ha generato un'eccezione. Assert.Inconclusive.»).
|
||||
# The reason without the MSTest frame («Il metodo … ha generato un'eccezione. Assert.Inconclusive.»).
|
||||
printf '%s\n' "$righe" | awk -F'\t' "!($da_fare)"' && $1 != "Passed" && $1 != "Failed" && $1 != "Error" && $1 != "Timeout" && $1 != "Aborted" {
|
||||
m = $3; sub(/^.*Assert\.Inconclusive\. */, "", m); if (m == "") m = "(nessun motivo)"; print m }' \
|
||||
| sort | uniq -c | sort -rn | awk 'NR <= 30 { sub(/^ */, " "); print }'
|
||||
|
||||
@@ -1,15 +1,15 @@
|
||||
#!/usr/bin/env bash
|
||||
# Scansione delle vulnerabilità dell'immagine Docker con Trivy, a versione fissa (strumento.sh), sull'archivio prodotto
|
||||
# dalla costruzione (docker save o buildx --output type=docker): non serve il demone, e si scansiona proprio
|
||||
# l'immagine provata. Pacchetti di Debian e dipendenze .NET di Febe (i file *.deps.json).
|
||||
# Vulnerability scan of the Docker image with Trivy, at a fixed version (strumento.sh), on the archive produced by
|
||||
# the build (docker save or buildx --output type=docker): no daemon is needed, and the very image that was tested is
|
||||
# scanned. Debian packages and Febe's .NET dependencies (the *.deps.json files).
|
||||
#
|
||||
# .gitea/scripts/scansione-immagine.sh <immagine.tar> [cartella dei rapporti]
|
||||
#
|
||||
# La regola (docs/processo.md, «Rilievi di sicurezza»):
|
||||
# - CRITICAL con una correzione disponibile: il lavoro fallisce e l'immagine non si pubblica;
|
||||
# - HIGH, e CRITICAL ancora senza correzione: si riportano nel registro e in trivy.json, senza fermare nulla.
|
||||
# Le eccezioni stanno solo in .trivyignore, alla radice del repository: un identificativo per riga, con la scadenza
|
||||
# (exp:AAAA-MM-GG) e, sulla riga sopra, il motivo scritto e chi l'ha deciso.
|
||||
# The rule (docs/processo.md, «Rilievi di sicurezza»):
|
||||
# - CRITICAL with a fix available: the job fails and the image is not published;
|
||||
# - HIGH, and CRITICAL still without a fix: reported in the log and in trivy.json, without stopping anything.
|
||||
# The exceptions live only in .trivyignore, at the repository root: one identifier per line, with the expiry
|
||||
# (exp:AAAA-MM-GG) and, on the line above, the written reason and who decided it.
|
||||
set -euo pipefail
|
||||
|
||||
radice="$(git rev-parse --show-toplevel)"
|
||||
@@ -22,7 +22,7 @@ strumenti="$lavoro/febe-strumenti"
|
||||
bash "$radice/.gitea/scripts/strumento.sh" trivy "$strumenti"
|
||||
mkdir -p "$rapporti"
|
||||
|
||||
# Niente barre di avanzamento, niente controllo di versioni nuove, niente dati d'uso.
|
||||
# No progress bars, no check for new versions, no usage data.
|
||||
export TRIVY_NO_PROGRESS=true TRIVY_SKIP_VERSION_CHECK=true TRIVY_DISABLE_TELEMETRY=true
|
||||
export TRIVY_CACHE_DIR="$lavoro/febe-trivy-cache"
|
||||
comuni=(image --input "$archivio" --scanners vuln --timeout 20m)
|
||||
@@ -35,8 +35,8 @@ echo "== Vulnerabilità HIGH e CRITICAL (rapporto: non fermano il lavoro)"
|
||||
"$strumenti/trivy" "${comuni[@]}" --severity HIGH,CRITICAL --format json --output "$rapporti/trivy.json" --exit-code 0
|
||||
"$strumenti/trivy" convert --format table "$rapporti/trivy.json"
|
||||
|
||||
# Il conteggio con il lettore JSON nostro (json.sh, awk): niente jq. Una riga per vulnerabilità, gravità e versione
|
||||
# che la corregge (vuota o null se non c'è). Un rapporto illeggibile non ferma nulla: lo dice e basta.
|
||||
# The count with our own JSON reader (json.sh, awk): no jq. One line per vulnerability, severity and the version that
|
||||
# fixes it (empty or null if there is none). An unreadable report stops nothing: it just says so.
|
||||
if vulnerabilita=$(bash "$radice/.gitea/scripts/json.sh" campi "Results/*/Vulnerabilities/*" Severity,FixedVersion "$rapporti/trivy.json"); then
|
||||
conteggio=$(awk -F '\t' '
|
||||
$1 == "HIGH" { alte++ }
|
||||
|
||||
@@ -1,14 +1,15 @@
|
||||
#!/usr/bin/env bash
|
||||
# Cerca segreti (gettoni, chiavi, password) con gitleaks, a versione fissa (strumento.sh), in tutta la storia del
|
||||
# commit verificato: ogni commit da cui discende, non solo l'ultimo. Ogni ramo si controlla al suo push (main a ogni
|
||||
# unione), così un rilievo su un ramo non blocca gli altri. Un segreto non compare mai per intero: --redact lo
|
||||
# sostituisce con REDACTED nel registro e nel rapporto, e qui si stampano solo regola, file, riga, commit e impronta.
|
||||
# Looks for secrets (tokens, keys, passwords) with gitleaks, at a fixed version (strumento.sh), in the whole history
|
||||
# of the commit being verified: every commit it descends from, not only the last one. Each branch is checked on its
|
||||
# own push (main at every merge), so a finding on one branch does not block the others. A secret never appears in
|
||||
# full: --redact replaces it with REDACTED in the log and in the report, and here only rule, file, line, commit and
|
||||
# fingerprint are printed.
|
||||
#
|
||||
# .gitea/scripts/segreti.sh [cartella del rapporto]
|
||||
#
|
||||
# Che cosa fare con un rilievo: docs/processo.md, «Rilievi di sicurezza». In breve: un segreto vero si revoca subito
|
||||
# (toglierlo dalla storia non basta); un falso allarme già controllato (un dato di prova finto) si mette in
|
||||
# .gitleaksignore con la sua impronta e, sulla riga sopra, un commento che dice che cos'è e chi l'ha controllato.
|
||||
# What to do with a finding: docs/processo.md, «Rilievi di sicurezza». In short: a real secret is revoked at once
|
||||
# (removing it from the history is not enough); a false alarm already checked (fake test data) goes into
|
||||
# .gitleaksignore with its fingerprint and, on the line above, a comment saying what it is and who checked it.
|
||||
set -euo pipefail
|
||||
|
||||
radice="$(git rev-parse --show-toplevel)"
|
||||
@@ -37,7 +38,7 @@ if ((stato == 0)); then
|
||||
exit 0
|
||||
fi
|
||||
|
||||
# Il riassunto con il lettore JSON nostro (json.sh, awk): niente jq.
|
||||
# The summary with our own JSON reader (json.sh, awk): no jq.
|
||||
if [[ -s "$rapporto" ]] \
|
||||
&& rilievi=$(bash "$radice/.gitea/scripts/json.sh" campi "*" RuleID,File,StartLine,Commit,Fingerprint "$rapporto"); then
|
||||
quanti=0
|
||||
|
||||
@@ -1,15 +1,15 @@
|
||||
#!/usr/bin/env bash
|
||||
# Installa uno dei due strumenti esterni della CI, gli unici approvati da Alberto e solo per la CI (20 ottobre 2026):
|
||||
# gitleaks (segreti nella storia) e Trivy (vulnerabilità dell'immagine). Versione fissa, archivio scaricato dalla
|
||||
# release del progetto e installato solo se la sua impronta SHA-256 coincide con quella scritta qui. Le impronte sono
|
||||
# quelle dei file *_checksums.txt delle release, ricontrollate il 20 ottobre 2026 sull'archivio scaricato e
|
||||
# sull'impronta che GitHub mostra per l'allegato.
|
||||
# Installs one of the two external tools of the CI, the only ones Alberto approved and only for the CI (20 October
|
||||
# 2026): gitleaks (secrets in the history) and Trivy (image vulnerabilities). Fixed version, archive downloaded from
|
||||
# the project's release and installed only if its SHA-256 hash matches the one written here. The hashes are those of
|
||||
# the releases' *_checksums.txt files, checked again on 20 October 2026 against the downloaded archive and the hash
|
||||
# GitHub shows for the attachment.
|
||||
#
|
||||
# .gitea/scripts/strumento.sh gitleaks|trivy <cartella>
|
||||
#
|
||||
# Per aggiornare uno strumento si cambiano versione e impronta insieme, in un commit solo, con una riga in
|
||||
# docs/decisioni.md. Mai «latest», mai le azioni di terzi (trivy-action fu compromessa a marzo 2026, CVE-2026-33634),
|
||||
# mai uno script di installazione scaricato al volo.
|
||||
# To update a tool, version and hash change together, in a single commit, with a line in docs/decisioni.md. Never
|
||||
# «latest», never third-party actions (trivy-action was compromised in March 2026, CVE-2026-33634), never an install
|
||||
# script downloaded on the fly.
|
||||
set -euo pipefail
|
||||
|
||||
nome="${1:?Indica lo strumento: gitleaks o trivy.}"
|
||||
|
||||
@@ -1,23 +1,24 @@
|
||||
#!/usr/bin/env bash
|
||||
# Sceglie le versioni da togliere dal registro dei pacchetti di Gitea (pulizia-docker.sh, modo «completa»). Legge solo
|
||||
# i file che riceve, con json.awk e versioni-registro.awk (awk POSIX: niente jq, niente Node): niente rete, niente
|
||||
# scritture, quindi si prova con un file JSON (PipelineTests).
|
||||
# Chooses the versions to remove from Gitea's package registry (pulizia-docker.sh, «completa» mode). It reads only the
|
||||
# files it is given, with json.awk and versioni-registro.awk (POSIX awk: no jq, no Node): no network, no writes, so it
|
||||
# is tested with a JSON file (PipelineTests).
|
||||
#
|
||||
# versioni-registro.sh <quante tenere> <pagina.json>... le etichette sha-<da 7 a 40 cifre esadecimali>
|
||||
# del contenitore febe oltre le N più recenti
|
||||
# versioni-registro.sh senza-etichetta <pagina.json>... le versioni sha256:<64 cifre> del contenitore
|
||||
# febe (i manifest di un indice: solo da contare)
|
||||
# versioni-registro.sh scadute <giorni> <adesso> <pagina.json>... le versioni <x.y.z>-ci.<n> e
|
||||
# <x.y.z>-rilascio.<n> del pacchetto generico
|
||||
# febe-ci (gli artefatti della CI, artefatti.sh)
|
||||
# create più di <giorni> giorni prima di <adesso>,
|
||||
# in secondi dal 1970
|
||||
# versioni-registro.sh <quante tenere> <pagina.json>... the sha-<7 to 40 hexadecimal digits> tags of
|
||||
# the febe container beyond the N most recent
|
||||
# versioni-registro.sh senza-etichetta <pagina.json>... the sha256:<64 digits> versions of the febe
|
||||
# container (the manifests of an index: only to
|
||||
# be counted)
|
||||
# versioni-registro.sh scadute <giorni> <adesso> <pagina.json>... the <x.y.z>-ci.<n> and <x.y.z>-rilascio.<n>
|
||||
# versions of the generic febe-ci package (the CI
|
||||
# artifacts, artefatti.sh) created more than
|
||||
# <giorni> days before <adesso>, in seconds since
|
||||
# 1970
|
||||
#
|
||||
# Ogni pagina è una risposta di GET /api/v1/packages/{proprietario}/{tipo}/{nome} di Gitea 28. Stampa, dalla più
|
||||
# vecchia e una per riga, «versione<TAB>creata». Tutto il resto resta sempre: main, latest, le versioni X.Y.Z (anche
|
||||
# X.Y.Z-rc.N), i digest, ogni altra etichetta, una sha- o un artefatto senza una data che si legga. Fra le sha- contano
|
||||
# le date, non il testo; a parità di data l'identificativo. Se un file non è un elenco JSON esce con 2 e non stampa
|
||||
# nulla: nel dubbio non si toglie niente.
|
||||
# Each page is a response of GET /api/v1/packages/{owner}/{type}/{name} of Gitea 28. Prints, oldest first and one per
|
||||
# line, «version<TAB>created». Everything else always stays: main, latest, the X.Y.Z versions (also X.Y.Z-rc.N), the
|
||||
# digests, every other tag, a sha- tag or an artifact without a readable date. Among the sha- tags the dates count,
|
||||
# not the text; with equal dates the identifier. If a file is not a JSON list it exits with 2 and prints nothing: when
|
||||
# in doubt nothing is removed.
|
||||
set -euo pipefail
|
||||
|
||||
qui="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
@@ -48,7 +49,7 @@ export LC_ALL=C
|
||||
tab=$'\t'
|
||||
versioni=$(awk -v tipo="$tipo" -v nome="$nome" -f "$qui/json.awk" -f "$qui/versioni-registro.awk" "$@") || exit 2
|
||||
|
||||
# Righe: millisecondi (o «-»), identificativo, ordine, versione, data come scritta.
|
||||
# Lines: milliseconds (or «-»), identifier, order, version, date as written.
|
||||
case "$modo" in
|
||||
senza-etichetta)
|
||||
awk -F "$tab" -v OFS="$tab" '$4 ~ /^sha256:[0-9a-f]+$/ && length($4) == 71 { if ($1 == "-") $1 = 0; print }' <<< "$versioni" \
|
||||
@@ -60,7 +61,7 @@ case "$modo" in
|
||||
| sort -t "$tab" -k1,1n -k2,2n -k3,3n | cut -f4,5
|
||||
;;
|
||||
*)
|
||||
# Le più recenti prima (data, poi identificativo), si saltano le prime N, il resto dalla più vecchia.
|
||||
# The most recent first (date, then identifier), the first N are skipped, the rest from the oldest.
|
||||
awk -F "$tab" '$1 != "-" && $4 ~ /^sha-[0-9a-f]+$/ && length($4) >= 11 && length($4) <= 44' <<< "$versioni" \
|
||||
| sort -t "$tab" -k1,1nr -k2,2nr -k3,3n | tail -n "+$((modo + 1))" \
|
||||
| awk '{ righe[NR] = $0 } END { for (i = NR; i > 0; i--) print righe[i] }' | cut -f4,5
|
||||
|
||||
@@ -1,22 +1,22 @@
|
||||
# Pulizia del lunedì (alle 4:17, ora del server di Gitea) e a mano (Actions ▸ pulizia ▸ Esegui) del demone Docker del
|
||||
# runner e del registro dei container. A mano, con «Solo prova» spuntato, elenca che cosa toglierebbe e non toglie
|
||||
# nulla: da lanciare prima della prima pulizia vera e dopo ogni cambio dello script.
|
||||
# Ogni esecuzione di verifica e di rilascio toglie già ciò che crea e, per tutti, le immagini senza nome e la cache di
|
||||
# costruzione penzolante non usata da 24 ore. Qui, dal 21 ottobre 2026 (decisione di Alberto: eliminare tutto ciò che
|
||||
# non serve più), si toglie anche ciò che non serve più a nessuno, di qualunque progetto (pulizia-docker.sh completa):
|
||||
# - i resti della CI di Febe: contenitori di prova fermi (etichetta febe.ci.prova e nome febe-prova-<esecuzione>, mai
|
||||
# le etichette febe.ci.* che un Febe vero eredita dall'immagine), nomi locali febe-ci:<esecuzione>, builder
|
||||
# febe-ci-<esecuzione>, l'immagine febe:ci del vecchio flusso;
|
||||
# - i resti di act_runner: contenitori fermi, volumi e reti GITEA-ACTIONS-TASK-… che nessun contenitore usa, più
|
||||
# vecchi di 90 minuti;
|
||||
# - le immagini che nessun contenitore usa, né acceso né fermo, create più di 24 ore fa (di un'immagine in uso Docker
|
||||
# toglie i nomi in più), e la cache di costruzione del demone non usata da 24 ore. Le immagini di base
|
||||
# (debian:trixie, moby/buildkit, …) si riscaricano alla prima esecuzione che le chiede;
|
||||
# - con il segreto REGISTRY_TOKEN, le etichette sha- del registro oltre le 10 più recenti, mai main, latest o X.Y.Z,
|
||||
# e gli artefatti della CI (pacchetto generico febe-ci, artefatti.sh) creati più di 14 giorni fa.
|
||||
# Mai system prune, container prune, volume prune o network prune; mai un contenitore, un volume o una rete che non sia
|
||||
# della CI. Un contenitore di prova ancora acceso si segnala e il lavoro diventa rosso; un rifiuto dell'API del
|
||||
# registro è solo un avviso. Dettagli in .gitea/scripts/pulizia-docker.sh e in docs/processo.md, «Pulizia».
|
||||
# Monday cleanup (at 4:17, Gitea server time) and by hand (Actions ▸ pulizia ▸ Esegui) of the runner's Docker daemon and
|
||||
# of the container registry. By hand, with «Solo prova» ticked, it lists what it would remove and removes nothing: to
|
||||
# be run before the first real cleanup and after every change to the script.
|
||||
# Every verification and release run already removes what it creates and, for everyone, the unnamed images and the
|
||||
# dangling build cache unused for 24 hours. Here, since 21 October 2026 (decision of Alberto: delete everything that
|
||||
# is no longer needed), what nobody needs any more is removed too, of any project (pulizia-docker.sh completa):
|
||||
# - the leftovers of the Febe CI: stopped test containers (label febe.ci.prova and name febe-prova-<esecuzione>,
|
||||
# never the febe.ci.* labels a real Febe inherits from the image), local names febe-ci:<esecuzione>, builders
|
||||
# febe-ci-<esecuzione>, the febe:ci image of the old workflow;
|
||||
# - the leftovers of act_runner: stopped containers, volumes and networks GITEA-ACTIONS-TASK-… no container uses,
|
||||
# older than 90 minutes;
|
||||
# - the images no container uses, running or stopped, created more than 24 hours ago (from an image in use Docker
|
||||
# removes the extra names), and the daemon's build cache unused for 24 hours. The base images (debian:trixie,
|
||||
# moby/buildkit, …) are downloaded again by the first run that asks for them;
|
||||
# - with the REGISTRY_TOKEN secret, the registry's sha- tags beyond the 10 most recent, never main, latest or X.Y.Z,
|
||||
# and the CI artifacts (generic package febe-ci, artefatti.sh) created more than 14 days ago.
|
||||
# Never system prune, container prune, volume prune or network prune; never a container, a volume or a network that
|
||||
# does not belong to the CI. A test container still running is reported and the job turns red; a refusal by the
|
||||
# registry API is only a warning. Details in .gitea/scripts/pulizia-docker.sh and in docs/processo.md, «Pulizia».
|
||||
name: pulizia
|
||||
|
||||
on:
|
||||
@@ -67,9 +67,10 @@ jobs:
|
||||
git checkout -q --force --detach "$GITHUB_SHA"
|
||||
git log -1 --format='Commit %h: %s'
|
||||
|
||||
# Gitea 28 mette nell'evento la casella «prova» come testo, "true" o "false"; il lunedì l'evento non ha input e
|
||||
# la pulizia è quella vera. Un avvio con l'API passa il valore così com'è: qualunque altro («True», «1») ferma il
|
||||
# lavoro senza toccare nulla. Il token del registro va solo nell'ambiente di questo passo e non si stampa mai.
|
||||
# Gitea 28 puts the «prova» checkbox in the event as text, "true" or "false"; on Monday the event has no inputs
|
||||
# and the cleanup is the real one. A start through the API passes the value as it is: any other («True», «1»)
|
||||
# stops the job without touching anything. The registry token goes only into this step's environment and is
|
||||
# never printed.
|
||||
- name: Pulizia completa del demone Docker e del registro
|
||||
env:
|
||||
PROVA: ${{ gitea.event.inputs.prova }}
|
||||
|
||||
@@ -1,43 +1,43 @@
|
||||
# Rilascio a ogni tag vX.Y.Z (anche vX.Y.Z-qualcosa per un'anteprima):
|
||||
# 1. prove: il tag coincide con <Version> di Directory.Build.props, la soluzione si compila con gli avvisi come errori
|
||||
# e tutte le prove passano, nello stesso contenitore Debian 13 della verifica (Chromium e Xvfb veri) e
|
||||
# senza nessuna prova saltata. Senza prove verdi non si costruisce né si rilascia nulla;
|
||||
# 2. windows: Febe.exe in un file solo, il programma di installazione nostro (src/Febe.Installer) e lo zip portabile
|
||||
# (installer/costruisci.sh, gira su Linux con il solo .NET SDK): il cancello prima dell'immagine;
|
||||
# 3. immagine: dopo l'installatore, l'immagine Docker (le prove girano anche dentro la build), provata senza rete e
|
||||
# scansionata con Trivy come nella verifica (una CRITICAL con correzione ferma tutto), poi pubblicata sul registro
|
||||
# dei container di Gitea come <registro>/<proprietario>/febe:X.Y.Z e :latest (solo per le versioni senza
|
||||
# trattino). Il lavoro dice se l'ha pubblicata, e alla fine toglie sempre immagini, contenitori, cache e builder
|
||||
# dell'esecuzione, poi le immagini senza nome e la cache di costruzione penzolante non usata da 24 ore di tutti i
|
||||
# progetti del demone;
|
||||
# 4. release: solo dopo le prove, l'installatore e l'immagine. Ricostruisce installatore e zip dallo stesso commit con
|
||||
# lo stesso script (senza azioni non c'è un passaggio di artefatti fra i lavori che non dipenda da REGISTRY_TOKEN,
|
||||
# e la release deve uscire anche senza), poi crea la release (o la completa, se esiste già) con installatore, zip
|
||||
# portabile, modello Unraid e l'archivio per Docker Compose (compose.yml con il profilo seccomp accanto); le note
|
||||
# dicono dove sta l'immagine, o che non è stata pubblicata.
|
||||
# Release at every vX.Y.Z tag (also vX.Y.Z-something for a preview):
|
||||
# 1. prove: the tag matches <Version> in Directory.Build.props, the solution builds with warnings as errors and all
|
||||
# the tests pass, in the same Debian 13 container as the verification (real Chromium and Xvfb) and without any
|
||||
# skipped test. Without green tests nothing is built or released;
|
||||
# 2. windows: Febe.exe in a single file, our own installer (src/Febe.Installer) and the portable zip
|
||||
# (installer/costruisci.sh, runs on Linux with the .NET SDK only): the gate before the image;
|
||||
# 3. immagine: after the installer, the Docker image (the tests also run inside the build), tested without network
|
||||
# and scanned with Trivy as in the verification (a CRITICAL with a fix stops everything), then published on the
|
||||
# Gitea container registry as <registro>/<proprietario>/febe:X.Y.Z and :latest (only for versions without a
|
||||
# dash). The job says whether it published it, and at the end it always removes the run's images, containers,
|
||||
# cache and builder, then the unnamed images and the dangling build cache unused for 24 hours of all the
|
||||
# daemon's projects;
|
||||
# 4. release: only after the tests, the installer and the image. It rebuilds installer and zip from the same commit
|
||||
# with the same script (without actions there is no way to pass artifacts between jobs that does not depend on
|
||||
# REGISTRY_TOKEN, and the release must come out without it too), then creates the release (or completes it, if
|
||||
# it already exists) with installer, portable zip, Unraid template and the Docker Compose archive (compose.yml
|
||||
# with the seccomp profile next to it); the notes say where the image is, or that it was not published.
|
||||
#
|
||||
# Niente azioni, come nella verifica (decisione del 18 novembre 2026): sorgenti con git e il gettone del lavoro, SDK con
|
||||
# .gitea/scripts/dotnet.sh, builder buildx con costruisci-immagine.sh builder, risultati delle prove e rapporto di Trivy
|
||||
# nel pacchetto generico febe-ci (versione <versione>-rilascio.<numero>, con REGISTRY_TOKEN; artefatti.sh).
|
||||
# No actions, as in the verification (decision of 18 November 2026): sources with git and the job token, SDK with
|
||||
# .gitea/scripts/dotnet.sh, buildx builder with costruisci-immagine.sh builder, test results and Trivy report in the
|
||||
# generic package febe-ci (version <versione>-rilascio.<numero>, with REGISTRY_TOKEN; artefatti.sh).
|
||||
#
|
||||
# Segreto del repository (Impostazioni ▸ Actions ▸ Segreti): REGISTRY_TOKEN, un token dell'utente con i permessi
|
||||
# «package: read and write». Senza, l'immagine si costruisce e si prova ma non si pubblica: la release esce lo stesso,
|
||||
# con l'installatore per Windows, e le sue note dicono che l'immagine di questa versione non c'è. Aggiunto il segreto,
|
||||
# si rilancia il flusso del tag: l'immagine si pubblica e le note della release si correggono.
|
||||
# Variabile facoltativa (Impostazioni ▸ Actions ▸ Variabili): REGISTRY, il nome del registro come lo raggiunge il
|
||||
# runner (per esempio 192.168.30.23:3000); se manca si usa l'host dell'indirizzo del server Gitea (il suo ROOT_URL).
|
||||
# Il registro risponde in HTTP: la pubblicazione passa da buildx con un builder proprio (docker-container) a cui la
|
||||
# configurazione di buildkit dice che quel registro è in HTTP e insicuro, così non serve che il Docker del runner lo
|
||||
# abbia fra gli insecure-registries. Le credenziali vanno nella configurazione del client Docker, senza «docker login»
|
||||
# (che passerebbe dal demone, e il demone proverebbe HTTPS).
|
||||
# Repository secret (Impostazioni ▸ Actions ▸ Segreti): REGISTRY_TOKEN, a user token with the permissions
|
||||
# «package: read and write». Without it, the image is built and tested but not published: the release comes out
|
||||
# anyway, with the Windows installer, and its notes say the image of this version is missing. Once the secret is
|
||||
# added, the tag's workflow is run again: the image is published and the release notes are corrected.
|
||||
# Optional variable (Impostazioni ▸ Actions ▸ Variabili): REGISTRY, the registry name as the runner reaches it (for
|
||||
# example 192.168.30.23:3000); if missing, the host of the Gitea server address (its ROOT_URL) is used.
|
||||
# The registry answers in HTTP: publishing goes through buildx with a builder of its own (docker-container) whose
|
||||
# buildkit configuration says that registry is HTTP and insecure, so the runner's Docker does not need it among its
|
||||
# insecure-registries. The credentials go into the Docker client configuration, without «docker login» (which would
|
||||
# go through the daemon, and the daemon would try HTTPS).
|
||||
name: rilascio
|
||||
|
||||
on:
|
||||
push:
|
||||
tags: ["v*"]
|
||||
|
||||
# Come la verifica e la pulizia: ogni passo con «bash -e -o pipefail», qualunque sia la shell predefinita del runner
|
||||
# o del contenitore (i Sorgenti usano gli array di bash; in un contenitore Debian la predefinita sarebbe dash).
|
||||
# Like the verification and the cleanup: every step with «bash -e -o pipefail», whatever the default shell of the
|
||||
# runner or of the container (the Sorgenti step uses bash arrays; in a Debian container the default would be dash).
|
||||
defaults:
|
||||
run:
|
||||
shell: bash
|
||||
@@ -51,9 +51,9 @@ jobs:
|
||||
prove:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 60
|
||||
# Lo stesso ambiente delle prove della verifica: Debian 13 con Chromium e Xvfb veri e il riepilogo che non
|
||||
# ammette prove saltate. Su ubuntu-latest le prove nel browser (fra cui il ritorno dopo l'accesso, return-path.js)
|
||||
# sarebbero inconcludenti e un rilascio uscirebbe senza averle fatte.
|
||||
# The same environment as the verification tests: Debian 13 with real Chromium and Xvfb and the summary that
|
||||
# allows no skipped tests. On ubuntu-latest the browser tests (among them the return after sign-in,
|
||||
# return-path.js) would be inconclusive and a release would come out without having run them.
|
||||
container:
|
||||
image: debian:trixie
|
||||
options: --shm-size=1g
|
||||
@@ -108,7 +108,7 @@ jobs:
|
||||
dotnet test tests/Febe.Tests -c Release --no-build --nologo
|
||||
--logger "trx;LogFileName=prove.trx" --results-directory out/prove
|
||||
|
||||
# Nessuna prova saltata: una prova inconcludente (per esempio senza Chromium) ferma il rilascio.
|
||||
# No skipped test: an inconclusive test (for example without Chromium) stops the release.
|
||||
- name: Riepilogo delle prove
|
||||
if: ${{ !cancelled() }}
|
||||
run: bash .gitea/scripts/riepilogo-prove.sh out/prove 0
|
||||
@@ -128,7 +128,7 @@ jobs:
|
||||
needs: prove
|
||||
timeout-minutes: 30
|
||||
env:
|
||||
# Come l'installatore di verifica.yml: l'immagine del runner non garantisce ICU, e qui non serve.
|
||||
# Like the installer job of verifica.yml: the runner image does not guarantee ICU, and it is not needed here.
|
||||
DOTNET_SYSTEM_GLOBALIZATION_INVARIANT: "true"
|
||||
steps:
|
||||
- name: Sorgenti
|
||||
@@ -163,7 +163,7 @@ jobs:
|
||||
|
||||
immagine:
|
||||
runs-on: ubuntu-latest
|
||||
# Dopo l'installatore: :X.Y.Z e :latest escono solo se anche la release potrà uscire.
|
||||
# After the installer: :X.Y.Z and :latest come out only if the release can come out too.
|
||||
needs: [prove, windows]
|
||||
timeout-minutes: 60
|
||||
env:
|
||||
@@ -198,7 +198,7 @@ jobs:
|
||||
git checkout -q --force --detach "$GITHUB_SHA"
|
||||
git log -1 --format='Commit %h: %s'
|
||||
|
||||
# Ciò che un'esecuzione interrotta non ha potuto togliere, e un tentativo precedente di questa stessa esecuzione.
|
||||
# What an interrupted run could not remove, and an earlier attempt of this same run.
|
||||
- name: Resti di esecuzioni interrotte
|
||||
run: |
|
||||
bash .gitea/scripts/pulizia-docker.sh residui 90
|
||||
@@ -219,11 +219,11 @@ jobs:
|
||||
echo "IMAGE=$REGISTRY/$OWNER/febe" >> "$GITHUB_ENV"
|
||||
echo "immagine=$REGISTRY/$OWNER/febe" >> "$GITHUB_OUTPUT"
|
||||
|
||||
# Un builder buildx proprio, che sa che il registro di casa risponde in HTTP.
|
||||
# A buildx builder of our own, which knows that the home registry answers in HTTP.
|
||||
- name: Builder buildx dell'esecuzione
|
||||
run: bash .gitea/scripts/costruisci-immagine.sh builder "$REGISTRY"
|
||||
|
||||
# Gli stessi argomenti ed etichette della pubblicazione (costruisci-immagine.sh): quella esce dalla cache di questa.
|
||||
# The same arguments and labels as the publication (costruisci-immagine.sh): that one comes from this one's cache.
|
||||
- name: Costruzione dell'immagine (le prove girano dentro la build)
|
||||
run: |
|
||||
bash .gitea/scripts/costruisci-immagine.sh archivio "$ARCHIVIO" "$PROVA"
|
||||
@@ -267,37 +267,37 @@ jobs:
|
||||
REGISTRO_UTENTE: ${{ gitea.actor }}
|
||||
run: |
|
||||
set -eu
|
||||
# Le credenziali le mette costruisci-immagine.sh pubblica in una configurazione del client solo sua, tolta
|
||||
# alla fine: buildx le passa al builder, il demone non c'entra.
|
||||
# costruisci-immagine.sh pubblica puts the credentials in a client configuration of its own, removed at the
|
||||
# end: buildx passes them to the builder, the daemon is not involved.
|
||||
NOMI="$IMAGE:$VERSION"
|
||||
case "$VERSION" in
|
||||
*-*) echo "Versione di anteprima: :latest non si sposta." ;;
|
||||
*) NOMI="$NOMI $IMAGE:latest" ;;
|
||||
esac
|
||||
# La stessa costruzione di prima (dalla cache del builder), questa volta spinta sul registro da buildx.
|
||||
# The same build as before (from the builder's cache), this time pushed to the registry by buildx.
|
||||
bash .gitea/scripts/costruisci-immagine.sh pubblica $NOMI
|
||||
echo "pubblicata=si" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Pulizia (sempre)
|
||||
if: always()
|
||||
run: |
|
||||
# La configurazione del client con le credenziali, se un'interruzione ha saltato la trap di chi l'ha scritta.
|
||||
# The client configuration with the credentials, if an interruption skipped the trap of whoever wrote it.
|
||||
rm -rf "${RUNNER_TEMP:-/tmp}/febe-docker-$ESECUZIONE"
|
||||
if [ -n "${ARCHIVIO:-}" ]; then rm -f "$ARCHIVIO"; fi
|
||||
bash .gitea/scripts/pulizia-docker.sh esecuzione "$ESECUZIONE"
|
||||
# Poi, per tutti i progetti del demone, ciò che nessuno usa: immagini senza nome e cache di costruzione
|
||||
# penzolante non usata da 24 ore. Non fa mai fallire il lavoro.
|
||||
# Then, for all the daemon's projects, what nobody uses: unnamed images and dangling build cache unused for
|
||||
# 24 hours. It never fails the job.
|
||||
bash .gitea/scripts/pulizia-docker.sh penzolanti || echo "::warning::La pulizia di ciò che nessuno usa non è riuscita."
|
||||
|
||||
release:
|
||||
runs-on: ubuntu-latest
|
||||
# Le prove sono verdi, l'installatore c'è e l'immagine si è costruita: pubblicata, o non pubblicata per la sola
|
||||
# mancanza del segreto (il lavoro «immagine» lo dice e le note lo riportano). Se la costruzione, la prova del
|
||||
# contenitore, la scansione o la spinta sul registro falliscono, non esce nessuna release.
|
||||
# The tests are green, the installer is there and the image was built: published, or not published only because
|
||||
# the secret is missing (the «immagine» job says so and the notes report it). If the build, the container test,
|
||||
# the scan or the push to the registry fail, no release comes out.
|
||||
needs: [prove, windows, immagine]
|
||||
timeout-minutes: 40
|
||||
env:
|
||||
# Come «windows»: l'immagine del runner non garantisce ICU, e per costruire l'installatore non serve.
|
||||
# Like «windows»: the runner image does not guarantee ICU, and building the installer does not need it.
|
||||
DOTNET_SYSTEM_GLOBALIZATION_INVARIANT: "true"
|
||||
steps:
|
||||
- name: Sorgenti
|
||||
@@ -324,7 +324,7 @@ jobs:
|
||||
- name: SDK .NET 10
|
||||
run: bash .gitea/scripts/dotnet.sh 10.0
|
||||
|
||||
# Lo stesso commit e lo stesso script del lavoro «windows», che ha già fatto da cancello prima dell'immagine.
|
||||
# The same commit and the same script as the «windows» job, which already acted as the gate before the image.
|
||||
- name: Febe.exe, programma di installazione e zip portabile per la release
|
||||
run: bash installer/costruisci.sh "${GITHUB_REF_NAME#v}"
|
||||
|
||||
@@ -339,7 +339,7 @@ jobs:
|
||||
set -eu
|
||||
TAG="${GITHUB_REF_NAME}"
|
||||
VERSION="${TAG#v}"
|
||||
case "$VERSION" in *-*|0.*) PRE=true ;; *) PRE=false ;; esac # le versioni 0.x sono anteprime
|
||||
case "$VERSION" in *-*|0.*) PRE=true ;; *) PRE=false ;; esac # 0.x versions are previews
|
||||
NOTE=$(awk -v v="$VERSION" '/^## /{p=($2==v)} p' CHANGELOG.md || true)
|
||||
[ -n "$NOTE" ] || NOTE="Febe $VERSION"
|
||||
if [ "$PUBBLICATA" = "si" ]; then
|
||||
@@ -349,12 +349,12 @@ jobs:
|
||||
esac
|
||||
IMMAGINE_NOTA="Immagine Docker: $DOVE. Il registro risponde in HTTP: il Docker che la scarica deve averlo fra gli \`insecure-registries\`."
|
||||
else
|
||||
IMMAGINE_NOTA="**L'immagine Docker di questa versione non è stata pubblicata** (${MOTIVO:-motivo sconosciuto}): \`:latest\` resta sulla versione precedente, e Unraid e Docker Compose continuano a usare quella. Febe per Windows, qui allegato, è provato come sempre. Per pubblicare l'immagine, rilancia il flusso di rilascio di questo tag dopo aver risolto il problema: queste note si aggiornano."
|
||||
IMMAGINE_NOTA="**L'immagine Docker di questa versione non è stata pubblicata** (${MOTIVO:-motivo sconosciuto}): questo rilascio non aggiorna \`:latest\`, e Unraid e Docker Compose continuano a usare l'immagine che avevano già, se ce n'era una. Febe per Windows, qui allegato, è provato come sempre. Per pubblicare l'immagine, rilancia il flusso di rilascio di questo tag dopo aver risolto il problema: queste note si aggiornano."
|
||||
fi
|
||||
NOTE=$(printf '%s\n\n### Immagine Docker\n\n%s\n' "$NOTE" "$IMMAGINE_NOTA")
|
||||
|
||||
# JSON letto e scritto con .gitea/scripts/json.sh (awk), niente jq. Le risposte di Gitea in un file: il
|
||||
# lettore legge file, non un flusso.
|
||||
# JSON read and written with .gitea/scripts/json.sh (awk), no jq. Gitea's responses go to a file: the reader
|
||||
# reads files, not a stream.
|
||||
RISPOSTA="${RUNNER_TEMP:-/tmp}/febe-release-${GITHUB_RUN_ID:-0}.json"
|
||||
ID=""
|
||||
if curl -sf -H "Authorization: token $TOKEN" "$API/releases/tags/$TAG" -o "$RISPOSTA"; then
|
||||
@@ -371,7 +371,7 @@ jobs:
|
||||
echo "Release $TAG creata (id $ID)"
|
||||
else
|
||||
[[ "$ID" =~ ^[0-9]+$ ]] || { echo "Identificativo della release inatteso: «$ID»." >&2; exit 1; }
|
||||
# Le note dicono come è andata questa volta (per esempio: l'immagine ora è pubblicata).
|
||||
# The notes say how it went this time (for example: the image is now published).
|
||||
printf '{"body":%s}' "$(bash .gitea/scripts/json.sh stringa "$NOTE")" \
|
||||
| curl -sf -X PATCH -H "Authorization: token $TOKEN" -H "Content-Type: application/json" \
|
||||
--data-binary @- "$API/releases/$ID" > /dev/null
|
||||
@@ -379,7 +379,7 @@ jobs:
|
||||
fi
|
||||
|
||||
cp docker/unraid/febe.xml "out/febe-unraid-$VERSION.xml"
|
||||
# compose.yml indica il profilo seccomp con un percorso relativo: l'archivio li porta insieme.
|
||||
# compose.yml points to the seccomp profile with a relative path: the archive carries them together.
|
||||
COMPOSE="out/febe-compose-$VERSION"
|
||||
rm -rf "$COMPOSE"
|
||||
mkdir -p "$COMPOSE/chromium"
|
||||
|
||||
@@ -1,34 +1,34 @@
|
||||
# Verifica: a ogni push su qualunque ramo (i tag li prende rilascio.yml) e a mano (Actions ▸ verifica ▸ Esegui).
|
||||
# I suoi quattro lavori sono i controlli richiesti per unire in main (docs/processo.md):
|
||||
# controlli sintassi degli script, flussi in YAML a blocchi e senza azioni, segni di conflitto, versione,
|
||||
# progetti della soluzione, JSON; segreti in tutta la storia con gitleaks (versione e impronta fissate);
|
||||
# prove compilazione di tutta la soluzione con gli avvisi come errori e tutte le prove di tests/Febe.Tests
|
||||
# (mai «dotnet test» sulla soluzione intera: tests/Febe.Tests.Windows gira solo su Windows) con
|
||||
# Chromium e Xvfb veri in un contenitore Debian 13: nessuna prova deve saltarsi, tranne le «da fare»
|
||||
# di H264ConformanceTests.FeaturesStillToDo (riepilogo-prove.sh le conta a parte).
|
||||
# Il mondo sintetico del sito di prova ha il seme 13 e, per la categoria SitoDiProva, anche il seme di
|
||||
# questa esecuzione, scritto nel registro per rifare un errore;
|
||||
# installatore Febe-Setup-<versione>-ci.<numero>.exe (il programma di installazione nostro, src/Febe.Installer) e
|
||||
# lo zip portabile; serve solo il .NET SDK;
|
||||
# immagine dopo l'installatore: l'immagine Docker costruita con buildx, provata senza rete (parte, salute,
|
||||
# Chromium, it_IT) e scansionata con Trivy (si ferma per una CRITICAL con correzione); solo dopo un push
|
||||
# su main la pubblica come :main e :sha-<7 caratteri> (:latest resta al rilascio). Alla fine, sempre,
|
||||
# toglie immagini, contenitori, cache e builder di questa esecuzione, poi le immagini senza nome e la
|
||||
# cache di costruzione penzolante non usata da 24 ore di tutti i progetti del demone.
|
||||
# Verification: at every push on any branch (tags are taken by rilascio.yml) and by hand (Actions ▸ verifica ▸ Esegui).
|
||||
# Its four jobs are the checks required to merge into main (docs/processo.md):
|
||||
# controlli script syntax, workflows in block YAML and without actions, conflict markers, version, projects of
|
||||
# the solution, JSON; secrets in the whole history with gitleaks (version and hash pinned);
|
||||
# prove build of the whole solution with warnings as errors and all the tests of tests/Febe.Tests (never
|
||||
# «dotnet test» on the whole solution: tests/Febe.Tests.Windows runs only on Windows) with real
|
||||
# Chromium and Xvfb in a Debian 13 container: no test may be skipped, except the «da fare» ones of
|
||||
# H264ConformanceTests.FeaturesStillToDo (riepilogo-prove.sh counts them apart).
|
||||
# The synthetic world of the test site has seed 13 and, for the SitoDiProva category, also the seed of
|
||||
# this run, written in the log to reproduce a failure;
|
||||
# installatore Febe-Setup-<versione>-ci.<numero>.exe (our own installer, src/Febe.Installer) and the portable zip;
|
||||
# only the .NET SDK is needed;
|
||||
# immagine after the installer: the Docker image built with buildx, tested without network (start, health,
|
||||
# Chromium, it_IT) and scanned with Trivy (it stops for a CRITICAL with a fix); only after a push on
|
||||
# main it publishes it as :main and :sha-<7 characters> (:latest is left to the release). At the end,
|
||||
# always, it removes this run's images, containers, cache and builder, then the unnamed images and the
|
||||
# dangling build cache unused for 24 hours of all the daemon's projects.
|
||||
#
|
||||
# Niente azioni (decisione di Alberto del 18 novembre 2026: niente componenti esterni): ogni passo è un comando. I
|
||||
# sorgenti arrivano con git e il gettone del lavoro, l'SDK .NET con .gitea/scripts/dotnet.sh (verificato con l'impronta
|
||||
# dei metadati di Microsoft), il builder buildx con costruisci-immagine.sh builder. Gli artefatti (risultati delle
|
||||
# prove, installatore e zip, rapporti di gitleaks e di Trivy) vanno nel registro dei pacchetti di Gitea, pacchetto
|
||||
# generico febe-ci, versione <versione>-ci.<numero>, con REGISTRY_TOKEN (.gitea/scripts/artefatti.sh); la pulizia del
|
||||
# lunedì toglie quelli di più di 14 giorni. Senza il segreto un avviso, e il lavoro resta verde. Nessun passo usa Node.
|
||||
# No actions (decision of Alberto of 18 November 2026: no external components): every step is a command. The sources
|
||||
# arrive with git and the job token, the .NET SDK with .gitea/scripts/dotnet.sh (verified against the hash in
|
||||
# Microsoft's metadata), the buildx builder with costruisci-immagine.sh builder. The artifacts (test results,
|
||||
# installer and zip, gitleaks and Trivy reports) go to Gitea's package registry, generic package febe-ci, version
|
||||
# <versione>-ci.<numero>, with REGISTRY_TOKEN (.gitea/scripts/artefatti.sh); the Monday cleanup removes those older
|
||||
# than 14 days. Without the secret a warning, and the job stays green. No step uses Node.
|
||||
#
|
||||
# Niente «pull_request»: in Gitea una richiesta di unione mostra lo stato del suo ultimo commit, che il push del ramo
|
||||
# ha già verificato; pull_request rifarebbe tutto sullo stesso commit (refs/pull/N/head) sull'unico runner.
|
||||
# Runner: act_runner con l'etichetta ubuntu-latest, un lavoro alla volta. I lavori parlano con il demone Docker del
|
||||
# server, lo stesso di Encelado, Mimante e degli altri progetti: niente montaggi della cartella del lavoro in altri
|
||||
# contenitori (sul server i percorsi sono diversi); le immagini passano come archivi e contesti di costruzione.
|
||||
# Che cosa di Gitea 28 si usa e perché: docs/decisioni.md (20 ottobre e 18 novembre 2026) e docs/processo.md.
|
||||
# No «pull_request»: in Gitea a pull request shows the status of its last commit, which the branch push has already
|
||||
# verified; pull_request would redo everything on the same commit (refs/pull/N/head) on the only runner.
|
||||
# Runner: act_runner with the ubuntu-latest label, one job at a time. The jobs talk to the server's Docker daemon, the
|
||||
# same as Encelado, Mimante and the other projects: no mounts of the job folder into other containers (on the server
|
||||
# the paths are different); images travel as archives and build contexts.
|
||||
# What of Gitea 28 is used and why: docs/decisioni.md (20 October and 18 November 2026) and docs/processo.md.
|
||||
name: verifica
|
||||
|
||||
on:
|
||||
@@ -44,10 +44,10 @@ on:
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
# Su un ramo conta l'ultimo push: l'esecuzione precedente si annulla. Su main ogni commit ha il suo gruppo, così ogni
|
||||
# unione arriva fino in fondo e pubblica la sua :sha-. L'evento fa parte del gruppo: un'esecuzione a mano non annulla
|
||||
# mai quella di un push, che è l'unica a scrivere gli stati del commit richiesti per unire (un lavoro annullato lascia
|
||||
# lo stato «failure», e workflow_dispatch non ne scrive).
|
||||
# On a branch the last push counts: the earlier run is cancelled. On main every commit has its own group, so every
|
||||
# merge runs to the end and publishes its :sha-. The event is part of the group: a run by hand never cancels the one
|
||||
# of a push, which is the only one that writes the commit statuses required to merge (a cancelled job leaves the
|
||||
# «failure» status, and workflow_dispatch writes none).
|
||||
concurrency:
|
||||
group: verifica-${{ gitea.event_name }}-${{ gitea.ref }}${{ gitea.ref == 'refs/heads/main' && format('-{0}', gitea.sha) || '' }}
|
||||
cancel-in-progress: ${{ gitea.ref != 'refs/heads/main' }}
|
||||
@@ -68,9 +68,9 @@ jobs:
|
||||
env:
|
||||
NUMERO: ${{ gitea.run_number }}
|
||||
steps:
|
||||
# I sorgenti del commit con git e il gettone del lavoro, che vale solo finché il lavoro gira e non resta nella
|
||||
# configurazione del repository. Qui tutta la storia (PROFONDITA 0): gitleaks legge ogni commit da cui discende
|
||||
# quello verificato. Lo stesso passo, lettera per lettera, apre ogni lavoro (lo controlla PipelineTests).
|
||||
# The commit's sources with git and the job token, which is valid only while the job runs and does not stay in
|
||||
# the repository configuration. Here the whole history (PROFONDITA 0): gitleaks reads every commit the verified
|
||||
# one descends from. The same step, letter for letter, opens every job (PipelineTests checks it).
|
||||
- name: Sorgenti
|
||||
env:
|
||||
TOKEN: ${{ gitea.token }}
|
||||
@@ -112,9 +112,9 @@ jobs:
|
||||
needs: controlli
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 60
|
||||
# Debian 13, nient'altro: Chromium vero della distribuzione, come nell'immagine di Febe (su Ubuntu è uno snap). Senza
|
||||
# azioni non serve Node: git e curl prima dei sorgenti, il resto da ambiente-prove.sh, l'SDK da dotnet.sh.
|
||||
# Memoria condivisa più ampia dei 64 MB predefiniti: le prove dell'interfaccia usano un Chromium senza finestra.
|
||||
# Debian 13, nothing else: the distribution's real Chromium, as in the Febe image (on Ubuntu it is a snap). Without
|
||||
# actions Node is not needed: git and curl before the sources, the rest from ambiente-prove.sh, the SDK from
|
||||
# dotnet.sh. Shared memory larger than the default 64 MB: the interface tests use a Chromium without a window.
|
||||
container:
|
||||
image: debian:trixie
|
||||
options: --shm-size=1g
|
||||
@@ -151,7 +151,7 @@ jobs:
|
||||
git checkout -q --force --detach "$GITHUB_SHA"
|
||||
git log -1 --format='Commit %h: %s'
|
||||
|
||||
# Prima di tutto il resto, così un seme chiesto a mano e sbagliato ferma subito il lavoro.
|
||||
# Before everything else, so that a wrong seed asked by hand stops the job at once.
|
||||
- name: Semi del mondo sintetico
|
||||
id: semi
|
||||
run: |
|
||||
@@ -209,8 +209,8 @@ jobs:
|
||||
timeout-minutes: 30
|
||||
env:
|
||||
NUMERO: ${{ gitea.run_number }}
|
||||
# Questo lavoro gira sull'immagine del runner, che non garantisce ICU: pubblicare e impacchettare non ne hanno
|
||||
# bisogno, quindi .NET va in globalizzazione invariante invece di fermarsi («Couldn't find a valid ICU package»).
|
||||
# This job runs on the runner image, which does not guarantee ICU: publishing and packaging do not need it, so
|
||||
# .NET goes into invariant globalization instead of stopping («Couldn't find a valid ICU package»).
|
||||
DOTNET_SYSTEM_GLOBALIZATION_INVARIANT: "true"
|
||||
steps:
|
||||
- name: Sorgenti
|
||||
@@ -254,8 +254,8 @@ jobs:
|
||||
((${#artefatti[@]} == 2)) || { echo "Servono il programma di installazione e lo zip portabile, non: ${artefatti[*]:-niente}." >&2; exit 1; }
|
||||
bash .gitea/scripts/artefatti.sh verifica "${artefatti[@]}"
|
||||
|
||||
# Dopo l'installatore, non solo dopo le prove: :main e :sha- escono solo da un commit con tutta la verifica verde.
|
||||
# Sull'unico runner i lavori vanno comunque uno alla volta, quindi la durata non cambia.
|
||||
# After the installer, not only after the tests: :main and :sha- come only from a commit with the whole verification
|
||||
# green. On the only runner the jobs go one at a time anyway, so the duration does not change.
|
||||
immagine:
|
||||
needs: [prove, installatore]
|
||||
runs-on: ubuntu-latest
|
||||
@@ -288,14 +288,13 @@ jobs:
|
||||
git checkout -q --force --detach "$GITHUB_SHA"
|
||||
git log -1 --format='Commit %h: %s'
|
||||
|
||||
# Ciò che un'esecuzione interrotta (annullata, scaduta) non ha potuto togliere, e un tentativo precedente di
|
||||
# questa stessa esecuzione.
|
||||
# What an interrupted run (cancelled, timed out) could not remove, and an earlier attempt of this same run.
|
||||
- name: Resti di esecuzioni interrotte
|
||||
run: |
|
||||
bash .gitea/scripts/pulizia-docker.sh residui 90
|
||||
bash .gitea/scripts/pulizia-docker.sh esecuzione "$ESECUZIONE"
|
||||
|
||||
# Registro: la variabile REGISTRY delle Actions, se c'è, altrimenti l'host dell'indirizzo del server (ROOT_URL).
|
||||
# Registry: the REGISTRY variable of the Actions, if set, otherwise the host of the server address (ROOT_URL).
|
||||
- name: Versione, registro e nomi
|
||||
env:
|
||||
REGISTRO_SCELTO: ${{ vars.REGISTRY }}
|
||||
@@ -315,7 +314,7 @@ jobs:
|
||||
} >> "$GITHUB_ENV"
|
||||
echo "Immagine $V-ci.$NUMERO del commit ${GITHUB_SHA::12}, provata come $PROVA; registro $REGISTRY/$OWNER/febe"
|
||||
|
||||
# Un builder buildx di questa esecuzione (con la sua cache), che sa che il registro di casa risponde in HTTP.
|
||||
# A buildx builder of this run (with its cache), which knows that the home registry answers in HTTP.
|
||||
- name: Builder buildx dell'esecuzione
|
||||
run: bash .gitea/scripts/costruisci-immagine.sh builder "$REGISTRY"
|
||||
|
||||
@@ -364,13 +363,13 @@ jobs:
|
||||
REGISTRO_UTENTE: ${{ gitea.actor }}
|
||||
GITEA_TOKEN: ${{ gitea.token }}
|
||||
run: |
|
||||
# Le credenziali le mette costruisci-immagine.sh pubblica in una configurazione del client solo sua, tolta
|
||||
# alla fine: buildx le passa al builder, il demone non c'entra (e proverebbe HTTPS). Non si stampano mai.
|
||||
# costruisci-immagine.sh pubblica puts the credentials in a client configuration of its own, removed at the
|
||||
# end: buildx passes them to the builder, the daemon is not involved (and would try HTTPS). Never printed.
|
||||
NOMI=("$IMAGE:sha-${GITHUB_SHA::7}")
|
||||
# :main solo se main è ancora a questo commit: un'esecuzione arrivata in ritardo non lo riporta indietro.
|
||||
# Il gettone del lavoro solo nell'ambiente di git, come per i sorgenti. Il passo gira con «bash -e -o
|
||||
# pipefail»: senza «|| CIMA=""» un errore di ls-remote chiuderebbe il passo prima dell'avviso, e non
|
||||
# uscirebbe nemmeno la :sha-.
|
||||
# :main only if main is still at this commit: a run that arrives late does not move it back.
|
||||
# The job token only in git's environment, as for the sources. The step runs with «bash -e -o
|
||||
# pipefail»: without «|| CIMA=""» an ls-remote error would end the step before the warning, and not even
|
||||
# the :sha- would come out.
|
||||
INTESTAZIONE="Authorization: basic $(printf 'x-access-token:%s' "$GITEA_TOKEN" | base64 -w0)"
|
||||
CIMA=$(GIT_CONFIG_COUNT=1 GIT_CONFIG_KEY_0=http.extraHeader GIT_CONFIG_VALUE_0="$INTESTAZIONE" \
|
||||
git ls-remote origin refs/heads/main 2> /dev/null | cut -f1) || CIMA=""
|
||||
@@ -386,10 +385,10 @@ jobs:
|
||||
- name: Pulizia (sempre)
|
||||
if: always()
|
||||
run: |
|
||||
# La configurazione del client con le credenziali, se un'interruzione ha saltato la trap di chi l'ha scritta.
|
||||
# The client configuration with the credentials, if an interruption skipped the trap of whoever wrote it.
|
||||
rm -rf "${RUNNER_TEMP:-/tmp}/febe-docker-$ESECUZIONE"
|
||||
if [ -n "${ARCHIVIO:-}" ]; then rm -f "$ARCHIVIO"; fi
|
||||
bash .gitea/scripts/pulizia-docker.sh esecuzione "$ESECUZIONE"
|
||||
# Poi, per tutti i progetti del demone, ciò che nessuno usa: immagini senza nome e cache di costruzione
|
||||
# penzolante non usata da 24 ore. Non fa mai fallire il lavoro.
|
||||
# Then, for all the daemon's projects, what nobody uses: unnamed images and dangling build cache unused for
|
||||
# 24 hours. It never fails the job.
|
||||
bash .gitea/scripts/pulizia-docker.sh penzolanti || echo "::warning::La pulizia di ciò che nessuno usa non è riuscita."
|
||||
@@ -1,24 +1,24 @@
|
||||
#!/bin/sh
|
||||
# Febe: avvio del contenitore (specifica §11).
|
||||
# Febe: container start (specification §11).
|
||||
#
|
||||
# Fa solo tre cose e poi cede il posto al server:
|
||||
# 1. crea, se mancano, il gruppo PGID e l'utente PUID (su Unraid 99 e 100, «nobody:users»);
|
||||
# 2. rende /dati di quell'utente (la prima volta, o se PUID/PGID sono cambiati) e gli fa preparare /dati/home;
|
||||
# 3. exec del server con setpriv, come quell'utente: il server avvia e sorveglia da sé Xvfb e Chromium.
|
||||
# Sempre exec, mai un processo figlio: il server prende il posto di questo script come processo 1 del contenitore
|
||||
# (niente tini), riceve SIGTERM da «docker stop» e, con il runtime .NET, raccoglie i processi rimasti orfani.
|
||||
# Nessun ciclo di sorveglianza qui: è il lavoro di Febe.Server (niente script di shell che facciano da supervisore).
|
||||
# /libreria non si cambia mai ricorsivamente (sono le foto di Alberto); /importa è in sola lettura e non si tocca;
|
||||
# di /esporta (le copie esterne, specifica §4.10) si assegna solo la radice, mai ricorsivamente, e solo se le copie
|
||||
# esterne sono dichiarate (FEBE_ESPORTA=1 o --esporta).
|
||||
# Se /dati non si può sistemare (disco di rete, permessi) si parte lo stesso: è Febe a spiegare il problema nella sua
|
||||
# pagina, invece di un contenitore che si riavvia senza dire perché.
|
||||
# It does only three things and then hands over to the server:
|
||||
# 1. creates, if missing, the group PGID and the user PUID (on Unraid 99 and 100, «nobody:users»);
|
||||
# 2. makes /dati owned by that user (the first time, or if PUID/PGID changed) and has it prepare /dati/home;
|
||||
# 3. execs the server with setpriv, as that user: the server starts and watches Xvfb and Chromium by itself.
|
||||
# Always exec, never a child process: the server takes the place of this script as process 1 of the container
|
||||
# (no tini), receives SIGTERM from «docker stop» and, with the .NET runtime, reaps the orphaned processes.
|
||||
# No watch loop here: that is the job of Febe.Server (no shell script acting as a supervisor).
|
||||
# /libreria is never changed recursively (it holds Alberto's photos); /importa is read only and is not touched;
|
||||
# of /esporta (the external copies, specification §4.10) only the root is assigned, never recursively, and only if
|
||||
# the external copies are declared (FEBE_ESPORTA=1 or --esporta).
|
||||
# If /dati cannot be fixed (network disk, permissions) it starts anyway: Febe explains the problem on its page,
|
||||
# instead of a container that restarts without saying why.
|
||||
set -eu
|
||||
|
||||
PUID="${PUID:-99}"
|
||||
PGID="${PGID:-100}"
|
||||
|
||||
# Già avviato come utente normale (docker run --user ...): niente da cambiare.
|
||||
# Already started as a normal user (docker run --user ...): nothing to change.
|
||||
if [ "$(id -u)" != "0" ]; then
|
||||
exec "$@"
|
||||
fi
|
||||
@@ -36,13 +36,13 @@ if ! getent passwd "${PUID}" >/dev/null 2>&1; then
|
||||
useradd -o -u "${PUID}" -g "${PGID}" -M -d /dati/home -s /usr/sbin/nologin febe
|
||||
fi
|
||||
|
||||
# /dati è dell'utente PUID, che dentro può mettere di tutto, anche collegamenti simbolici verso file del contenitore:
|
||||
# da root qui dentro non si scrive niente. L'unica cosa fatta da root è il cambio di proprietario, ricorsivo e senza
|
||||
# seguire i collegamenti (-R senza -H/-L: cambia il collegamento, mai ciò a cui punta). Il resto lo fa l'utente stesso.
|
||||
# /dati belongs to the PUID user, who can put anything in it, even symbolic links to files of the container: as root
|
||||
# nothing is written in there. The only thing done as root is the change of owner, recursive and without following
|
||||
# links (-R without -H/-L: it changes the link, never what it points to). The rest is done by the user itself.
|
||||
if mkdir -p /dati 2>/dev/null; then
|
||||
da_assegnare=""
|
||||
[ "$(stat -c '%u:%g' /dati)" = "${PUID}:${PGID}" ] || da_assegnare=1
|
||||
# Una /dati/home di un altro proprietario (un avvio precedente come root): conta solo una cartella vera.
|
||||
# A /dati/home with another owner (an earlier start as root): only a real folder counts.
|
||||
if [ -d /dati/home ] && [ ! -L /dati/home ] && [ "$(stat -c '%u:%g' /dati/home)" != "${PUID}:${PGID}" ]; then
|
||||
da_assegnare=1
|
||||
fi
|
||||
@@ -51,22 +51,23 @@ if mkdir -p /dati 2>/dev/null; then
|
||||
chown -R "${PUID}:${PGID}" /dati 2>/dev/null || echo "Febe: non riesco ad assegnare /dati a ${PUID}:${PGID}." >&2
|
||||
fi
|
||||
chmod 0750 /dati 2>/dev/null || true
|
||||
# La HOME di Chromium la crea e la chiude l'utente, con i suoi permessi.
|
||||
# Chromium's HOME is created and locked by the user, with its own permissions.
|
||||
setpriv --reuid="${PUID}" --regid="${PGID}" --init-groups sh -c 'mkdir -p /dati/home && chmod 0700 /dati/home' 2>/dev/null || true
|
||||
# Il profilo seccomp non sta più in /dati: Docker lo legge sul server alla creazione del contenitore, e in /dati
|
||||
# l'utente del contenitore potrebbe allentarlo. Si tiene fuori dal volume dei dati (docs/docker.md, «Sandbox»).
|
||||
# The seccomp profile no longer lives in /dati: Docker reads it on the server when the container is created, and in
|
||||
# /dati the container's user could loosen it. It is kept outside the data volume (docs/docker.md, «Sandbox»).
|
||||
if [ -e /dati/seccomp.json ] || [ -L /dati/seccomp.json ]; then
|
||||
echo "Febe: /dati/seccomp.json non si aggiorna più. Se --security-opt seccomp= indica quel file, sposta il profilo fuori dalla cartella dei dati (su Unraid /mnt/user/appdata/febe-seccomp.json): vedi docs/docker.md, «Sandbox»." >&2
|
||||
fi
|
||||
fi
|
||||
|
||||
# Una cartella della libreria appena creata da Docker appartiene a root: solo quella, senza ricorsione.
|
||||
# A library folder just created by Docker belongs to root: only that folder, without recursion.
|
||||
if [ -d /libreria ] && [ "$(stat -c '%u' /libreria)" = "0" ]; then
|
||||
chown "${PUID}:${PGID}" /libreria 2>/dev/null || true
|
||||
fi
|
||||
|
||||
# /esporta: solo la radice, mai ricorsivo, e solo se le copie esterne sono dichiarate (SPECIFICA §4.10). Dentro ci
|
||||
# sono file di Alberto copiati da Febe o messi da lui: non si cambiano mai. Febe non crea /esporta se manca.
|
||||
# /esporta: only the root, never recursive, and only if the external copies are declared (SPECIFICA §4.10). Inside
|
||||
# there are Alberto's files copied by Febe or put there by him: they are never changed. Febe does not create /esporta
|
||||
# if it is missing.
|
||||
case "${FEBE_ESPORTA:-}" in 1|true|sì|si|yes) esporta=1 ;; *) esporta= ;; esac
|
||||
case " $* " in *" --esporta "*) esporta=1 ;; esac
|
||||
if [ -n "$esporta" ] && [ -d /esporta ] && [ "$(stat -c '%u' /esporta)" = "0" ]; then
|
||||
|
||||
@@ -123,7 +123,7 @@ Tutto il resto si scrive in casa, dalle specifiche pubbliche dei formati e mai c
|
||||
- metadati delle immagini: lettura e scrittura di EXIF (orientamento compreso), profilo ICC e XMP, per copiarli da un formato all'altro (§4.10);
|
||||
- lettori dei contenitori video ISO BMFF (MP4, MOV) e Matroska (MKV, WebM): durata, dimensioni, rotazione, tracce, codec e metadati del contenitore, al posto di ffprobe;
|
||||
- lettori dei contenitori ASF (WMV, WMA), FLV e MPEG-PS (flusso di programma di ISO/IEC 13818-1, `.mpg`, `.vob`): durata, dimensioni, codec e data dove il contenitore la porta (risposta di Alberto del 18 novembre 2026, tappa C5). Solo lettura dei metadati: i loro video non si rimuxano. Di un MPEG-PS codec e dimensioni vengono dall'intestazione di sequenza MPEG-1 o MPEG-2, o dall'SPS di una traccia H.264 o H.265 (questa solo con il tipo di flusso 0x24 nella mappa del flusso di programma); i suoi campioni, spezzati nei pacchetti PES, non si elencano, quindi nemmeno una traccia H.264 o H.265 dà un fotogramma e la miniatura è la tessera neutra. Fra questi contenitori la miniatura viene solo da un FLV con H.264;
|
||||
- rimuxaggio in MP4, senza ricodifica;
|
||||
- rimuxaggio in MP4, senza ricodifica (MOV, M4V, 3GP, MKV e WebM con H.264 o HEVC e AAC o MP3, tappa E3, §4.10);
|
||||
- decodificatore H.264 (ITU-T H.264), per i fotogrammi, le miniature dei video importati e i video fermi (§4.10). **Tutto lo standard** (risposta di Alberto del 18 novembre 2026, «Tutto»): profili Baseline (anche non vincolato), Constrained Baseline, Main, Extended (FMO, ASO, fette ridondanti, partizione dei dati, fette SP e SI), High, High 10, High 4:2:2 e High 4:4:4 (Predictive e Intra, con i piani di colore separati e il modo senza perdita), CAVLC 4:4:4 Intra, monocromatico (4:0:0), con la profondità di bit che ogni profilo prevede (fino a 14 bit); video interlacciati (campi, PAFF, MBAFF); CAVLC e CABAC, trasformata 8×8 e matrici di quantizzazione; SVC (allegato G) e MVC (allegato H), di cui per fotogrammi e miniature si usano lo strato con la risoluzione più alta e la vista di base. Un fotogramma con più di 8 bit si porta a 8 bit solo all'uscita, per JPG, PNG e WEBP. Solo un flusso rovinato dice «Fotogramma non disponibile per questo video»;
|
||||
- decodificatore H.265/HEVC (ITU-T H.265; risposta di Alberto del 18 novembre 2026, dentro la 0.3.0, tappa C4), per gli stessi usi: tutti i profili della serie di conformità ITU-T H.265.1 scelta per Febe (cartelle `HEVC_v1` e `RExt`, §16 domanda 18, risposta di Alberto del 25 novembre 2026), cioè Main, Main 10, Main Still Picture e le **estensioni di formato (RExt)** dei flussi della serie, che **restano**: 4:0:0, 4:2:2 e 4:4:4 fino a 12 bit, con i loro strumenti (predizione fra componenti, RDPCM, adattamento di Rice, `chroma_qp_offset_list`). Un fotogramma con più di 8 bit si porta a 8 bit solo all'uscita, come per H.264. Non hanno flussi in quella serie e restano fuori la precisione estesa dei profili a 16 bit, l'allineamento del CABAC, lo scalabile (SHVC), il multivista (MV-HEVC), il 3D e i contenuti dello schermo (SCC): un video così dice «Fotogramma non disponibile per questo video»;
|
||||
- VP9, AV1 e gli altri codec video non si decodificano (non richiesti): miniatura con la tessera neutra e «Fotogramma non disponibile per questo video»;
|
||||
@@ -219,8 +219,8 @@ A destra un riquadro «Con queste impostazioni» traduce le scelte in conseguenz
|
||||
- Deve restare fluida con 200.000 elementi: caricamento a finestre, miniature generate una volta e conservate.
|
||||
- **«Raggruppa i post» o «Tutte le foto»** (issue #59, tappa D1 del traguardo 0.3.0; decisione di Alberto del 25 novembre 2026): un interruttore a due voci nella riga di strumenti della Libreria e della vista dei contenuti della scheda account, tranne «In evidenza», disegnata per raccolta. «Raggruppa i post», il predefinito, è il mosaico di oggi: una tessera per elemento, con il numero dei file in alto a destra. «Tutte le foto» mette una tessera per file, video compresi, nello stesso ordine (data dell'elemento, poi posizione nella serie): utile quando un post ha più foto. Ha una tessera solo un file presente in libreria (scaricato o importato): un file ancora da scaricare, fallito o saltato no; con i filtri «Foto» e «Video» si vedono solo i file di quel tipo. In quel modo la tessera di un file di una serie dice la sua posizione («2/4»), il conteggio della riga del giorno conta i file, il visualizzatore si apre su quel file e le frecce vanno di file in file. La selezione è di file: «Copia in…» e «Fotogrammi…» lavorano sui file scelti; l'elenco CSV ed «Elimina» lavorano sugli elementi a cui appartengono, e la conferma lo dice («3 file scelti appartengono a 2 elementi: elimino gli elementi interi, 9 file.»). La scelta si ricorda per pagina, una per la Libreria e una per le viste degli account, **solo nel browser in cui si fa** (memoria locale del browser, chiavi `febe.mosaico.libreria` e `febe.mosaico.account`, lette e scritte dentro un `try`): a differenza del tema, che Febe conserva nelle sue impostazioni (Impostazioni → Generali, §10.5) e ogni browser ritrova, non passa a un altro browser né alla finestra di Febe per Windows. Se manca o non si legge vale «Raggruppa i post». Filtri, ricerca e caricamento a finestre funzionano uguali nei due modi, anche con 200.000 elementi e i loro file. Nell'interfaccia di programmazione (`src/Febe.Web/LEGGIMI.md`) `/api/library` e `/api/library/days` prendono `mode=grouped|files` (vuoto vale `grouped`; un altro valore dà 400); con `files` il cursore della finestra è `ms.elemento.posizione` (data in millisecondi, elemento, posizione del file nella serie; raggruppato è `ms.elemento`, e un cursore malformato dà 400), e `/api/library/days` ha il campo `files`, la somma dei file presenti in libreria dei giorni (con `grouped` è `null`), mentre i totali `entries` e `accounts` contano sempre elementi.
|
||||
- **File danneggiato o incompleto** (risposta di Alberto del 25 novembre 2026). Un'immagine troncata o rovinata, scaricata o importata (§3, §8.4), si rifiuta e lo dice: tessera neutra nel mosaico e «File danneggiato o incompleto» nel visualizzatore al posto dell'immagine, con le azioni sul file (mostra nella cartella o scarica, elimina) che restano. Il file **resta in libreria** (regola 12): Febe non lo cancella, non lo sostituisce e non lo riscarica da sé. Un HEIC che non si decodifica ha solo la tessera neutra, senza questa scritta (§3).
|
||||
- Visualizzatore (mockup 02): elemento a tutta altezza, frecce, file della serie, scheda con dati, file e provenienza. Azioni: mostra nella cartella (Windows) o scarica il file (browser), apri su Instagram, elimina dalla libreria. Con l'esportazione (§4.10, traguardo 0.3.0): «Copia in…», «Fotogramma» per i video, «È un video fermo?» a richiesta, e nel pannello File le righe delle copie esterne («Copiato in … · intero», «· fotogramma»).
|
||||
- Eliminare chiede conferma e, per impostazione predefinita, ricorda la scelta: l'elemento resta nel database senza file, nello stato «eliminato», così non viene riscaricato. La conferma offre anche «Eliminalo e lascia che torni». Le copie esterne di un elemento eliminato restano dove sono (§4.10).
|
||||
- Visualizzatore (mockup 02): elemento a tutta altezza, frecce, file della serie, scheda con dati, file e provenienza. Azioni: mostra nella cartella (Windows) o scarica il file (browser), apri su Instagram, elimina dalla libreria. Con l'esportazione (§4.10, traguardo 0.3.0): «Copia in…», «Fotogramma» per i video (tappa E3; per un video senza fotogrammi la riga «Fotogramma non disponibile per questo video»), «È un video fermo?» a richiesta (tappa E4), e nel pannello File le righe delle copie esterne («Copiato in … · intero», «· PNG», «· fotogramma a 0:01 · PNG») e dei file convertiti della libreria («Convertito in PNG · 2,1 MB»).
|
||||
- Eliminare chiede conferma e, per impostazione predefinita, ricorda la scelta: l'elemento resta nel database senza file, nello stato «eliminato», così non viene riscaricato. La conferma offre anche «Eliminalo e lascia che torni». Le copie esterne di un elemento eliminato restano dove sono (§4.10); i suoi file convertiti della libreria (§4.10, «Conversione della libreria») se ne vanno con i suoi file, e la conferma li conta.
|
||||
- Scheda dell'account con gli elementi divisi in Post, Storie, In evidenza, Taggati (mockup 12), con lo stesso interruttore «Raggruppa i post» / «Tutte le foto» in ogni linguetta tranne «In evidenza», le impostazioni e la cronologia dei controlli.
|
||||
- Selezione multipla per esportare (elenco CSV di §4.8; «Copia in…» e «Fotogrammi…» di §4.10) o eliminare. Dal traguardo 0.3.0 un filtro «Copie» (Tutti, Non ancora copiati, Copiati, Tolti o superati) in Libreria e nella scheda dell'account.
|
||||
|
||||
@@ -259,24 +259,24 @@ Hashtag e luoghi, commenti, elenchi di follower di altri, messaggi diretti, più
|
||||
|
||||
### 4.10 Esportazione
|
||||
|
||||
Decisioni di Alberto del 18 novembre 2026 (issue #58, traguardo «0.3.0 — Esportazione», tappe in §15). Dalla tappa E2 (27 novembre 2026) le copie degli originali, accanto all'elenco CSV di §4.8; formati e fotogrammi con E3, video fermi con E4, l'automatica con E5. Fino a E3 ed E4 i loro comandi («Fotogrammi…», «Fotogramma», «È un video fermo?», i formati e la conversione della libreria) mancano dall'interfaccia, non sono spenti; fino a E5 una destinazione in pausa si riprova con «Riprova» o «Riprendi», non con il giro orario.
|
||||
Decisioni di Alberto del 18 novembre 2026 (issue #58, traguardo «0.3.0 — Esportazione», tappe in §15). Dalla tappa E2 (27 novembre 2026) le copie degli originali, accanto all'elenco CSV di §4.8; dalla tappa E3 (28 novembre 2026) i formati delle copie, la conversione della libreria e i fotogrammi («Fotogrammi…», «Fotogramma», i menu dei formati, «Conversione della libreria»); video fermi con E4, l'automatica con E5. Fino a E4 i suoi comandi («È un video fermo?», «Salva il fotogramma») mancano dall'interfaccia, non sono spenti; fino a E5 una destinazione in pausa si riprova con «Riprova» o «Riprendi», non con il giro orario.
|
||||
|
||||
**Principio.** Un'esportazione copia in una cartella esterna (una **destinazione**) file che sono già in libreria: così come sono, convertiti in un altro formato o come fotogramma di un video. È solo lavoro sul disco: niente Instagram, niente CDN, niente Governatore, niente `action_log`. Un file che manca in libreria non si riscarica: la copia dice «File non presente in libreria».
|
||||
|
||||
**Destinazioni.**
|
||||
|
||||
- Una **cartella di esportazione generale** (Impostazioni → Esportazione) e, per ogni account, una **cartella propria facoltativa** che la sostituisce, con l'interruttore **«Esporta questo account»** (scheda account → Impostazioni, blocco «Copie esterne», sotto «Cartella»). Ogni account ha al più una destinazione effettiva: «già copiato» è un sì o un no. **«Esporta questo account» è acceso per impostazione predefinita** (decisione di Alberto del 27 novembre 2026): un account senza scelta registrata si esporta; spento, «Copia in…» lo salta, anche quando la si chiede a mano (proposta applicata dalla tappa E2, §16 domanda 22), e la finestra lo conta fra i file «di account che non si esportano»; le copie già fatte restano.
|
||||
- Una **cartella di esportazione generale** (Impostazioni → Esportazione) e, per ogni account, una **cartella propria facoltativa** che la sostituisce, con l'interruttore **«Esporta questo account»** (scheda account → Impostazioni, blocco «Copie esterne», sotto «Cartella»). Ogni account ha al più una destinazione effettiva: «già copiato» è un sì o un no. **«Esporta questo account» è acceso per impostazione predefinita** (decisione di Alberto del 27 novembre 2026): un account senza scelta registrata si esporta; spento, «Copia in…» lo salta, anche quando la si chiede a mano (risposta di Alberto del 29 novembre 2026, §16 domanda 22), e la finestra lo conta fra i file «di account che non si esportano»; le copie già fatte restano.
|
||||
- Nella cartella generale Febe mette sempre per primo il segmento con il nome dell'account ripulito, perché gli account non si scontrino; sotto vale lo schema dei nomi della destinazione, «Come la libreria» (predefinito) oppure uno proprio, controllato come quelli di §4.7. I suffissi dei fotogrammi (`_fotogramma`, `_t0m12s340`, `_f001`) si aggiungono prima dell'accorciamento a 240 caratteri.
|
||||
- Ogni destinazione dice: tipi di contenuto (post foto, post video, storie, evidenza, taggati, profilo), formati delle copie, schema dei nomi, «Automatica».
|
||||
- Cartelle rifiutate: dentro **o contenenti** Dati, Libreria, una cartella di account (anche fuori dalla Libreria) o `/importa`; la radice di un disco o di una condivisione. Lettere di unità e percorsi UNC che puntano allo stesso posto si riconoscono con un file di prova, non confrontando i testi: un `.febe-prova-*.part` scritto e tolto come quello del punto qui sotto, **solo nella cartella candidata**, che deve già esistere, e mai in Dati, Libreria, cartelle degli account o `/importa`. Lì Febe lo cerca soltanto, in lettura: risalendo le loro cartelle madri (una di loro è dentro la candidata) e, per ogni cartella madre della candidata, allo stesso percorso relativo sotto ciascuna (la candidata è dentro una di loro). Se il file di prova non si scrive, la cartella si rifiuta. Si ricontrolla quando cambia la cartella di un account.
|
||||
- **La radice di una destinazione non si crea mai**: un disco o una condivisione assente non deve diventare una cartella locale. Le sottocartelle dello schema sì. Prima di ogni gruppo di copie Febe scrive e toglie un file `.febe-prova-*.part`; se non riesce, la destinazione va in pausa, lo stato si vede in Impostazioni e nella Dashboard e il giro orario riprova. Mai la striscia rossa, che resta del motore. I controlli sul disco esterno sono asincroni e brevi: una condivisione staccata non blocca l'interfaccia.
|
||||
- Spazio: per le destinazioni non valgono i 10 GB / 5 % della libreria; basta spazio libero per il prossimo file più un margine (64 MB, proposta, §16 domanda 27). Su FAT32 conta il limite di 4 GB per file.
|
||||
- Spazio: per le destinazioni non valgono i 10 GB / 5 % della libreria; basta spazio libero per il prossimo file più un margine (64 MB, risposta di Alberto del 29 novembre 2026, §16 domanda 27). Su FAT32 conta il limite di 4 GB per file.
|
||||
- **Mai sovrascrivere, mai cancellare** (regola 12): si scrive con un `.part`, si verifica lo SHA-256, si rinomina su un nome libero. Togliere una destinazione toglie solo la configurazione («I file già copiati restano dove sono»); le copie registrate restano nel database, legate alla destinazione ritirata; eliminare un elemento dalla libreria non tocca le sue copie. I `.part` rimasti si tolgono solo nelle cartelle di lavori non finiti, mai con una scansione della destinazione.
|
||||
|
||||
**Conversione del formato.** Due impostazioni distinte, **entrambe spente** per impostazione predefinita:
|
||||
|
||||
- **per le copie**: il formato in cui arrivano i file nella destinazione. Valori predefiniti in Impostazioni → Esportazione, che ogni destinazione e ogni singola «Copia in…» possono cambiare;
|
||||
- **per la libreria**: Febe **aggiunge** all'elemento il file convertito, e l'originale **resta** accanto (regola 12). Il convertito è legato al suo originale: SHA-256, impronta visiva, miniatura, controllo dei doppioni e `_febe.jsonl` restano quelli dell'originale, e il convertito non si riscarica né conta come doppione. Si registra in `media_conversion` (migrazione `0003`, tappa E1; decisione di Alberto del 26 novembre 2026): una riga per file convertito, legata alla riga `media` dell'originale, con formato, percorso, byte, SHA-256 del convertito, data e stato; la tabella `media` non cambia. La conversione la fa la tappa E3.
|
||||
- **per la libreria**: Febe **aggiunge** all'elemento il file convertito, e l'originale **resta** accanto (regola 12). Il convertito è legato al suo originale: SHA-256, impronta visiva, miniatura, controllo dei doppioni e `_febe.jsonl` restano quelli dell'originale, e il convertito non si riscarica né conta come doppione. Si registra in `media_conversion` (migrazione `0003`, tappa E1; decisione di Alberto del 26 novembre 2026): una riga per file convertito, legata alla riga `media` dell'originale, con formato, percorso, byte, SHA-256 del convertito, data e stato; la tabella `media` non cambia. La conversione la fa la tappa E3 (qui sotto, «Conversione della libreria»).
|
||||
|
||||
| | Scelte | Come |
|
||||
|---|---|---|
|
||||
@@ -285,34 +285,43 @@ Decisioni di Alberto del 18 novembre 2026 (issue #58, traguardo «0.3.0 — Espo
|
||||
|
||||
- **Con perdita solo se scelto**: l'unica conversione con perdita è JPG, a qualità 92, e la finestra lo dice («con perdita»). PNG, WEBP senza perdita e il rimuxaggio non perdono nulla; un'immagine animata non si converte mai, perché perderebbe i fotogrammi dopo il primo. La trasparenza in JPG diventa bianco.
|
||||
- **Metadati: tutti quelli possibili.** Il convertito è la stessa immagine con un'altra estensione: EXIF con l'orientamento (che resta un dato, i pixel non si ruotano), profilo ICC, XMP, nei posti che il formato di arrivo prevede (APP1 e APP2 in JPG, `eXIf`, `iCCP` e `iTXt` in PNG, `EXIF`, `ICCP` e `XMP ` in WEBP); per i video i metadati del contenitore (date, rotazione, lingua delle tracce). La data del file segue `libreria.data-file-pubblicazione`, fotogrammi compresi. Ciò che il formato di arrivo non può tenere lo dice il resoconto.
|
||||
- **Quale formato** (tappa E3). Per ogni file vale la scelta della singola «Copia in…» («Formato: come la destinazione · Cambia»), poi quella della destinazione («Come le impostazioni generali», il predefinito), poi Impostazioni → Esportazione. Un formato nuovo vale per i file non ancora copiati («Già copiato», qui sotto). Lo stesso formato si riconosce dai byte, non dall'estensione: un `.jpg` che è un PNG si converte in JPG; un WEBP con perdita con «WEBP senza perdita» si copia byte per byte, perché ricodificarlo lo farebbe solo più grande (risposta di Alberto del 29 novembre 2026, §16 domanda 36); un video è già MP4 quando è ISO BMFF con un marchio diverso da quello di QuickTime (`qt `) e con l'estensione `.mp4`.
|
||||
- **Copiati come sono anche** (tappa E3, oltre la tabella; risposte di Alberto del 29 novembre 2026, §16 domande 31 e 38): le immagini CMYK o YCCK e quelle con più di 8 bit per colore verso PNG e WEBP senza perdita, perché i codificatori di Febe sono RGB a 8 bit (verso JPG si convertono: un profilo ICC non RGB è detto «non tenuto», come un profilo grigio verso ogni formato); le immagini oltre 40 megapixel per WEBP e oltre 100 per PNG e JPG, con un lato oltre 16.384 pixel per WEBP, o più grandi di 512 MB. Ognuna con la sua nota («Copiato com'è: immagine CMYK», «Copiato com'è: troppo grande per il formato scelto»). Un EXIF rovinato non ferma la conversione: si lascia fuori, con la nota.
|
||||
- **Rimuxaggio** (tappa E3). MOV, M4V, 3GP e Matroska (MKV, WebM) con una traccia video H.264 o HEVC e al più una traccia audio AAC o MP3 diventano MP4 copiando i campioni uno per uno, senza tenerli tutti in memoria: restano fotogrammi chiave, ordine di presentazione, l'inizio ritardato e il priming dell'AAC (l'elenco di modifiche), la rotazione, la lingua delle tracce e le date. Le tracce in più (codice di tempo, sottotitoli, una seconda traccia audio) si tolgono, e la nota lo dice («Tracce tolte: 1»). Si copia com'è, con il motivo, un video con un altro codec (VP9, AV1, Opus…), senza la configurazione del codec, con tracce Matroska codificate, con più di un taglio nell'elenco di modifiche, o in un contenitore che MP4 non prende così com'è (AVI, ASF, FLV, MPEG-PS).
|
||||
- **Note e spazio** (tappa E3). Le note sono nel resoconto del lavoro (colonne «Come sono» e «Note»), nelle righe del visualizzatore e, previste dall'estensione, nel riepilogo di «Copia in…» («circa 3 HEIC copiati come sono»; «con perdita» quando almeno un file si converte in JPG). I byte del riepilogo sono quelli degli originali, «circa»; il controllo dello spazio della destinazione usa la dimensione del convertito, perché Febe converte prima di controllare.
|
||||
- **Conversione della libreria** (tappa E3). Due impostazioni, Foto e Video, in Impostazioni → Esportazione, «Originale» (cioè spente) per impostazione predefinita. Il convertito si scrive accanto all'originale, nella stessa cartella, con lo stesso nome e l'estensione del formato (`nome.png`; `nome (2).png` se il nome è occupato: mai una sovrascrittura), con le regole di scrittura, i metadati e le note delle copie, e la data del file secondo `libreria.data-file-pubblicazione`. Un file già nel formato scelto, HEIC, AVIF, raw, GIF e WebM non entrano in coda; un'immagine animata o un video che non si rimuxa «non si convertono», e non si riprovano finché il file non cambia. Lavora in sottofondo, un file per volta, mai durante una sessione del motore; lascia il passo a importazione, copie e ricostruzione, che partono subito, e riprende dopo; si mette in pausa quando lo spazio libero della libreria scenderebbe sotto la soglia del disco (10 GB / 5 %) con il file da scrivere. Accenderla chiede «Convertire anche i N file già in libreria?», con lo spazio che occupano gli originali, e la risposta proposta è **«Solo i nuovi»**: un file nuovo (salvato in libreria da quando il formato è quello scelto) entra in coda dopo la sua riga di `_febe.jsonl`, anche se arriva tardi in un elemento vecchio, senza i file che l'elemento aveva già; spegnerla svuota la coda e lascia i convertiti dove sono (risposta di Alberto del 29 novembre 2026, §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 (risposta di Alberto del 29 novembre 2026, §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 (risposta di Alberto del 29 novembre 2026, §16 domanda 37).
|
||||
|
||||
**Fotogrammi e video fermi.**
|
||||
|
||||
- **Fotogrammi a richiesta**, dal visualizzatore (questo istante, uno ogni k secondi, N in tutto, con anteprima) o con «Fotogrammi…» dalla selezione (le foto si saltano, e la finestra lo dice): JPG, PNG o WEBP senza perdita, a piena risoluzione, con i decodificatori H.264 e H.265 (HEVC) di Febe (§3; H.265 dalla tappa C4). Un video in un altro codec (VP9, AV1 e gli altri, non richiesti) dice «Fotogramma non disponibile per questo video». Uscita: «Scarica» (un file, o uno zip per più file) oppure una destinazione.
|
||||
- **Solo il fotogramma**: l'audio si perde, e la finestra lo dice: «Il fotogramma non ha l'audio».
|
||||
- **Quali fotogrammi** (tappa E3). Gli istanti sono quelli che il lettore del visualizzatore mostra (il tempo di presentazione, con il ritardo iniziale dell'elenco di modifiche). «Questo istante» dà il fotogramma mostrato in quel momento (prima dell'inizio il primo, oltre la fine l'ultimo); dal visualizzatore la finestra si apre all'istante del lettore, con l'anteprima. «Uno ogni k secondi» parte da 0:00 (0, k, 2k… prima della fine), con k di almeno 0,1 secondi; «N in tutto» divide il video in N parti uguali e prende il centro di ognuna, (i + ½) · durata / N (risposta di Alberto del 29 novembre 2026, §16 domanda 33). Limiti (risposta di Alberto del 29 novembre 2026, §16 domanda 38): N da 1 a 1.000, al più 1.000 fotogrammi per video («Più di 1.000 fotogrammi per un video: scegli un intervallo più lungo») e 20.000 per richiesta; le anteprime sono di al più 480 pixel e si fanno in 30 secondi («Il fotogramma richiede troppo tempo: scegli la cartella delle copie»). Il fotogramma è a piena risoluzione, mai ridimensionato, ruotato come il video si vede, e **senza metadati**: non ha EXIF né data del video (risposta di Alberto del 29 novembre 2026, §16 domanda 32). Il formato proposto è **PNG** (risposta di Alberto del 29 novembre 2026, §16 domanda 35); JPG dice «con perdita».
|
||||
- **Nomi e uscite dei fotogrammi** (tappa E3). Il nome è quello del video con un suffisso prima dell'estensione: `_t0m12s340` (minuti, secondi e millesimi dell'istante del fotogramma davvero mostrato) per «Questo istante» e «Uno ogni k secondi», `_f001` (la posizione, con almeno tre cifre) per «N in tutto»; `_fotogramma` resta a «Salva il fotogramma» (E4). «Scarica»: un fotogramma è l'immagine stessa; da 2 a 20 uno zip in qualunque momento; da 21 a 500 uno zip solo fuori dalle sessioni del motore e quando non lavorano importazione, copie o ricostruzione; oltre 500 solo «Nella cartella delle copie» (risposta di Alberto del 29 novembre 2026, §16 domanda 34). Lo zip si scrive mentre si scarica, senza compressione (le immagini sono già compresse), con una cartella per account e i nomi resi unici («nome (2).png»), e si chiama `febe-fotogrammi-AAAA-MM-GG.zip`; la data delle voci segue `libreria.data-file-pubblicazione`. «Nella cartella delle copie» è un lavoro di copia verso la destinazione di ogni account, con gli stessi file dovuti di «Copia in…» (un account che non si esporta si salta e si conta); «Scarica» non guarda le destinazioni. Un video che non dà fotogrammi si salta con la nota «Fotogramma non disponibile per questo video».
|
||||
- **Un fotogramma non fa «Copiato».** La copia di un fotogramma ha la sua identità, con l'istante del fotogramma mostrato in millisecondi (arrotondato in su): lo stesso fotogramma chiesto di nuovo è «già copiato», un altro istante è un'altra copia. Il video resta «Non ancora copiato» finché non c'è una sua copia intera o convertita; un elemento che ha soltanto fotogrammi copiati ha sulla tessera il segno «Solo fotogrammi», e il visualizzatore dice «· fotogramma a 0:01,125 · PNG». Un fotogramma «Tolto» o «Superato» si riscrive a una nuova richiesta esplicita (risposta di Alberto del 29 novembre 2026, §16 domanda 32). «Una copia sola» non vale per i fotogrammi.
|
||||
- **Video fermo** (mostra sempre la stessa immagine): l'analisi si fa **solo a richiesta**, dal visualizzatore («È un video fermo?») o dalla selezione, mai in sottofondo. Esiti: «Fermo», «In movimento», «Non analizzabile», salvati per SHA-256 (`video_analysis`, con il numero dell'algoritmo per poter rianalizzare). Per un video fermo il visualizzatore mostra «Un'immagine sola per tutto il video: basta un fotogramma» con «Salva il fotogramma»; nelle destinazioni si copia comunque **il video intero**, che tiene l'audio.
|
||||
- Copie, conversioni e analisi lunghe partono fuori dalle sessioni del motore; esportazione, importazione e ricostruzione non girano insieme.
|
||||
- Copie, conversioni e analisi lunghe partono fuori dalle sessioni del motore; esportazione, importazione e ricostruzione non girano insieme. La conversione della libreria gira in sottofondo e cede il passo a tutte e tre (tappa E3); uno zip di più di 20 fotogrammi conta come un lavoro lungo.
|
||||
|
||||
**Manuale e automatica.**
|
||||
|
||||
- **Manuale sempre**: «Copia in…» dalla selezione, dal filtro corrente, dal visualizzatore e dalla scheda dell'account.
|
||||
- **Automatica spenta** per ogni destinazione. Quando Alberto l'accende, Febe chiede che cosa fare di ciò che è già in libreria; la risposta proposta è **«Solo i nuovi»**. Un elemento nuovo entra in coda dopo la sua riga di `_febe.jsonl`; un giro di recupero all'avvio e ogni ora. Nella tappa E2 l'interruttore non si mostra: la scelta si registra (database e interfaccia di programmazione), ma nulla la usa fino a E5 (proposta, §16 domanda 24).
|
||||
- **Automatica spenta** per ogni destinazione. Quando Alberto l'accende, Febe chiede che cosa fare di ciò che è già in libreria; la risposta proposta è **«Solo i nuovi»**. Un elemento nuovo entra in coda dopo la sua riga di `_febe.jsonl`; un giro di recupero all'avvio e ogni ora. Nella tappa E2 l'interruttore non si mostra: la scelta si registra (database e interfaccia di programmazione), ma nulla la usa fino a E5 (risposta di Alberto del 29 novembre 2026, §16 domanda 24).
|
||||
|
||||
**«Già copiato».**
|
||||
|
||||
- Una riga per copia (`export_copy`). Una copia è identificata da SHA-256 dell'originale, destinazione, **account effettivo** (quello del segmento con il nome dell'account nella cartella generale, o l'account della cartella propria), variante (intero, convertito, fotogramma), formato e istante del fotogramma; la riga tiene anche percorso relativo, byte e SHA-256 della copia, data, stato. Si cerca per SHA-256, non per l'identificativo di Instagram, che gli importati possono non avere: un elemento eliminato con «Eliminalo e lascia che torni» ritrova le sue copie quando torna.
|
||||
- Stati di un file: **«Copiato»**, **«Tolto»** (il file non c'è più nella destinazione), **«Superato»** (il file della libreria è cambiato, per esempio dopo «Tieni il più grande» o una ricostruzione), «Non riuscito». Tolto e Superato **non si ricopiano mai da soli**: «Copia di nuovo» a richiesta scrive un file nuovo, e la copia vecchia resta: dal visualizzatore, un file alla volta, o per tutti quelli scelti con la casella «Copia di nuovo anche i N tolti o superati» della finestra «Copia in…», spenta all'apertura (proposta, §16 domanda 25). «Tolto» lo trova «Controlla le copie» (Impostazioni → Esportazione), che guarda soltanto: con la radice della destinazione irraggiungibile non segna nulla come tolto e mette la destinazione in pausa. Neppure dopo la rimozione di un account: le sue copie restano registrate, senza account ma con il suo identificativo di Instagram e il suo nome, e se l'account torna quelle della cartella generale tornano sue, in ogni stato (per identificativo; per nome solo se l'identificativo non era noto); quelle della sua cartella propria tornano quando Alberto gliela ridà.
|
||||
- **Adozione per percorso**: se nel percorso di arrivo c'è già un file, Febe lo adotta come copia invece di scriverne un secondo solo se è proprio quella copia. Per le copie byte per byte vuole lo stesso SHA-256 dell'originale; per i convertiti e i fotogrammi Febe rifà la conversione con le impostazioni di quella copia (i suoi codificatori sono fissi, §3) e vuole lo stesso SHA-256 del file trovato. La sola dimensione non basta mai. Se non coincide, il nome è occupato: Febe scrive su un nome libero e il file trovato resta com'è. Copre un database perso, un backup vecchio, due istanze sulla stessa cartella; «Riconosci le copie già presenti» lo fa per tutta la destinazione.
|
||||
- Per elemento, calcolato al momento (nessuna tabella derivata): «Copiato», «Copiato in parte», «Non ancora copiato»; un video copiato solo come fotogramma lo dice («fotogramma», non «intero»).
|
||||
- **File dovuti** (tappa E2): un file è dovuto quando è presente in libreria (scaricato o importato, con il suo SHA-256), il suo account ha «Esporta questo account» acceso e una destinazione effettiva, e il suo tipo di contenuto è fra quelli della destinazione (post foto, post video, storie, evidenza, taggati, profilo; una storia in una raccolta in evidenza è anche evidenza). Il segno sulla tessera, il filtro «Copie», il conteggio della scheda dell'account e «Copia in…» considerano solo i file dovuti (proposta, §16 domanda 26), così «312 su 1.204 non ancora copiati» è proprio ciò che «Copia in…» copierebbe. Le tre scelte del filtro dividono i file dovuti senza sovrapporsi: «Copiati» (copia corrente «Copiato»), «Tolti o superati» (l'ultima copia è «Tolto» o «Superato»), «Non ancora copiati» (tutti gli altri, «Non riuscito» compreso, che la copia successiva riprova). Un account spento non ha file dovuti.
|
||||
- Dove si vede: un piccolo segno sulla tessera (solo se esiste almeno una destinazione; differenza voluta rispetto al mockup 01), le righe del pannello File del visualizzatore («Copiato in Disco USB il 3 novembre · intero», «· fotogramma a 0:01 · JPG», «Tolto» con «Copia di nuovo»), il conteggio nella scheda dell'account («312 su 1.204 non ancora copiati»), il filtro «Copie».
|
||||
- **«Già copiato» guarda il file, non il formato** (tappa E3; risposta di Alberto del 29 novembre 2026, §16 domanda 28, che cambia ciò che seguirebbe dall'identità qui sopra). Un file dovuto è «Copiato» in una destinazione quando ha lì una copia corrente intera o convertita, **in qualunque formato**, ed è «Tolto» o «Superato» quando lo è la sua ultima copia intera o convertita; i fotogrammi non contano. Piano, filtro «Copie», segno sulla tessera, conteggio della scheda dell'account, «Una copia sola» e copia usano questa sola regola, mentre l'identità registrata resta quella completa. Così un formato nuovo vale per i file non ancora copiati, e un file già copiato in un'altra forma si salta con «Già copiato in un altro formato». Per averlo nel formato nuovo: togliere il file vecchio dalla destinazione, «Controlla le copie» lo segna «Tolto», poi «Copia di nuovo». «Copia di nuovo» dal visualizzatore rifà **proprio quella copia** (stessa variante, formato e istante del fotogramma); la casella «Copia di nuovo anche i N tolti o superati» di «Copia in…» usa i formati di adesso.
|
||||
- Stati di un file: **«Copiato»**, **«Tolto»** (il file non c'è più nella destinazione), **«Superato»** (il file della libreria è cambiato, per esempio dopo «Tieni il più grande» o una ricostruzione), «Non riuscito». Tolto e Superato **non si ricopiano mai da soli**: «Copia di nuovo» a richiesta scrive un file nuovo, e la copia vecchia resta: dal visualizzatore, un file alla volta, o per tutti quelli scelti con la casella «Copia di nuovo anche i N tolti o superati» della finestra «Copia in…», spenta all'apertura (risposta di Alberto del 29 novembre 2026, §16 domanda 25). «Tolto» lo trova «Controlla le copie» (Impostazioni → Esportazione), che guarda soltanto: con la radice della destinazione irraggiungibile non segna nulla come tolto e mette la destinazione in pausa. Neppure dopo la rimozione di un account: le sue copie restano registrate, senza account ma con il suo identificativo di Instagram e il suo nome, e se l'account torna quelle della cartella generale tornano sue, in ogni stato (per identificativo; per nome solo se l'identificativo non era noto); quelle della sua cartella propria tornano quando Alberto gliela ridà.
|
||||
- **Adozione per percorso**: se nel percorso di arrivo c'è già un file, Febe lo adotta come copia invece di scriverne un secondo solo se è proprio quella copia. Per le copie byte per byte vuole lo stesso SHA-256 dell'originale; per i convertiti e i fotogrammi Febe rifà la conversione con le impostazioni di quella copia (i suoi codificatori sono fissi, §3) e vuole lo stesso SHA-256 del file trovato (dalla tappa E3: prima la lunghezza, poi lo SHA-256; per un rimuxaggio la lunghezza si sa prima di scrivere; una riga orfana si ricollega solo se ha la stessa forma e lo stesso SHA-256 della copia). La sola dimensione non basta mai. Se non coincide, il nome è occupato: Febe scrive su un nome libero e il file trovato resta com'è. Copre un database perso, un backup vecchio, due istanze sulla stessa cartella; «Riconosci le copie già presenti» lo fa per tutta la destinazione.
|
||||
- Per elemento, calcolato al momento (nessuna tabella derivata): «Copiato», «Copiato in parte», «Non ancora copiato»; un video copiato solo come fotogramma lo dice («fotogramma», non «intero»). Contano solo le copie intere o convertite dei file dovuti; un elemento senza nessuna di queste ma con almeno un fotogramma copiato ha il segno «Solo fotogrammi» (tappa E3).
|
||||
- **File dovuti** (tappa E2): un file è dovuto quando è presente in libreria (scaricato o importato, con il suo SHA-256), il suo account ha «Esporta questo account» acceso e una destinazione effettiva, e il suo tipo di contenuto è fra quelli della destinazione (post foto, post video, storie, evidenza, taggati, profilo; una storia in una raccolta in evidenza è anche evidenza). Il segno sulla tessera, il filtro «Copie», il conteggio della scheda dell'account e «Copia in…» considerano solo i file dovuti (risposta di Alberto del 29 novembre 2026, §16 domanda 26), così «312 su 1.204 non ancora copiati» è proprio ciò che «Copia in…» copierebbe. Le tre scelte del filtro dividono i file dovuti senza sovrapporsi: «Copiati» (copia corrente «Copiato»), «Tolti o superati» (l'ultima copia è «Tolto» o «Superato»), «Non ancora copiati» (tutti gli altri, «Non riuscito» compreso, che la copia successiva riprova). Un account spento non ha file dovuti.
|
||||
- Dove si vede: un piccolo segno sulla tessera (solo se esiste almeno una destinazione; differenza voluta rispetto al mockup 01), le righe del pannello File del visualizzatore («Copiato in Disco USB il 3 novembre · intero», «· PNG», «· fotogramma a 0:01 · JPG», «Tolto» con «Copia di nuovo», con le note su una seconda riga; il segno «Solo fotogrammi» sulla tessera), il conteggio nella scheda dell'account («312 su 1.204 non ancora copiati»), il filtro «Copie».
|
||||
|
||||
**Casi particolari.**
|
||||
|
||||
- **Lo stesso post in due account** (il post dell'uno e il taggato dell'altro, §8.3): un'impostazione sceglie fra **«Una copia per account»**, ognuna nella sua destinazione, che è il **predefinito** (risposta di Alberto del 18 novembre 2026), e **«Una copia sola»**, nel primo account che la copia; l'altro la mostra «Copiato» con la destinazione dove sta. Lo si riconosce dallo SHA-256.
|
||||
- **Una storia entrata in una raccolta in evidenza** conta anche come evidenza: una destinazione con il solo tipo «evidenza» la copia. Per lo stesso account effettivo un file si copia una volta sola in una destinazione: la storia e la sua evidenza sono una copia. Con «una copia per account» (qui sopra) lo stesso SHA-256 sta invece due volte nella cartella generale, una sotto il segmento di ciascun account.
|
||||
|
||||
**Docker e Windows.** In Docker le destinazioni sono sottocartelle di `/esporta`, scelte da un elenco come le sorgenti di importazione (`..` rifiutato, come testo, prima di ogni normalizzazione; `/esporta` stessa non è una destinazione). `/esporta` è attivo **solo se dichiarato** con `--esporta` (un'opzione senza valore) o `FEBE_ESPORTA` e solo se è davvero montato: una destinazione è attiva se sta su un montaggio in `/esporta` o sotto, letto da `/proc/self/mountinfo` (il montaggio che la contiene, con il punto di montaggio più lungo, deve avere il punto in `/esporta` o in una sua sottocartella e non essere in sola lettura). Basta anche montare solo delle sottocartelle (`/esporta/usb`, `/esporta/nas`; proposta, §16 domanda 23); una cartella di `/esporta` che non sta su un montaggio si rifiuta, perché sarebbe il disco delle immagini. Altrimenti non si scrive nulla. Nel Dockerfile non c'è una riga `VOLUME` per `/esporta`, né un `mkdir`: un volume anonimo la farebbe sembrare montata e riempirebbe in silenzio il disco delle immagini di Unraid (§11). Si cambia il proprietario solo della radice, mai in modo ricorsivo, e solo quando le copie esterne sono dichiarate e la radice è di root. Su Windows la cartella si sceglie con il selettore nativo, anche su un percorso di rete o UNC (§12).
|
||||
**Docker e Windows.** In Docker le destinazioni sono sottocartelle di `/esporta`, scelte da un elenco come le sorgenti di importazione (`..` rifiutato, come testo, prima di ogni normalizzazione; `/esporta` stessa non è una destinazione). `/esporta` è attivo **solo se dichiarato** con `--esporta` (un'opzione senza valore) o `FEBE_ESPORTA` e solo se è davvero montato: una destinazione è attiva se sta su un montaggio in `/esporta` o sotto, letto da `/proc/self/mountinfo` (il montaggio che la contiene, con il punto di montaggio più lungo, deve avere il punto in `/esporta` o in una sua sottocartella e non essere in sola lettura). Basta anche montare solo delle sottocartelle (`/esporta/usb`, `/esporta/nas`; risposta di Alberto del 29 novembre 2026, §16 domanda 23); una cartella di `/esporta` che non sta su un montaggio si rifiuta, perché sarebbe il disco delle immagini. Altrimenti non si scrive nulla. Nel Dockerfile non c'è una riga `VOLUME` per `/esporta`, né un `mkdir`: un volume anonimo la farebbe sembrare montata e riempirebbe in silenzio il disco delle immagini di Unraid (§11). Si cambia il proprietario solo della radice, mai in modo ricorsivo, e solo quando le copie esterne sono dichiarate e la radice è di root. Su Windows la cartella si sceglie con il selettore nativo, anche su un percorso di rete o UNC (§12).
|
||||
|
||||
**Fuori dal traguardo 0.3.0.** Ricodifica dei video (VP9, AV1, HEVC → MP4); conversione al momento dello scaricamento; unione di immagine e traccia audio dei post con musica (§4.9); un diario delle copie nelle destinazioni; la colonna «Copiato in» nel CSV.
|
||||
|
||||
@@ -408,7 +417,7 @@ User agent e valori della pagina si leggono con **una sola** `Runtime.evaluate`
|
||||
|
||||
La copia si fa solo da una pagina del sito che non sia un percorso di accesso o di verifica delle regole di arresto (§7.6), dentro i comandi del collegamento, dopo il controllo del cookie di sessione e prima del riposo. Si fa solo dentro il permesso di guida di Alberto («Accedi a Instagram», «Usa il browser»): Febe tiene il permesso e il turno della pagina per tutta la copia, a «Ho finito» come alla chiusura della finestra e alla fine del permesso, e in Docker lasciando la pagina del browser («Quando si copia»), e se il permesso finisce comunque prima del salvataggio la copia si butta. In ogni caso la copia dura al più 10 secondi; oltre, è un errore del browser e la copia si butta.
|
||||
|
||||
**Quando si copia** (decisione di Alberto del 18 novembre 2026, tappa S4b di #36). In tre momenti, sempre **prima che la pagina torni al motore**: a «Ho finito»; quando Alberto chiude la finestra «Browser di Febe» su Windows (anche quando resta ridotta a icona troppo a lungo); quando il permesso di guida finisce da solo. In Docker, al posto della finestra, conta **lasciare la pagina del browser** (risposta di Alberto del 25 novembre 2026): mentre Alberto guida, passare dalla pagina «Browser» o dalla vista remota della pagina Collegamento a un'altra pagina di Febe, chiudere la scheda o la finestra del browser in cui la guarda, o perderne il collegamento. Febe lo riconosce dal server: si chiude l'ultima vista remota aperta durante il permesso (la pagina che si lascia lo dice subito; una scheda chiusa o un collegamento perso chiudono la sua connessione) e per 5 secondi non se ne apre un'altra, così ricaricare la pagina non è lasciarla (i 5 secondi di grazia sono una proposta, §16 domanda 20: Alberto ha detto solo che lasciare la pagina copia la sessione). Da lì vale ciò che vale per la finestra di Windows: la copia, se la pagina è sul sito e non è di accesso o di verifica, poi il permesso finisce e la pagina torna al motore, che rimette il browser a riposo. L'interfaccia lo dice al server con `cancel` e `pageLeft` (`IConnectionService.LeavePageAsync`); su Windows, dove il browser è una finestra a parte, lasciare la pagina rilascia solo il permesso tenuto da quella pagina e la finestra resta com'è. Una vista chiusa perché il browser si è fermato non conta come pagina lasciata. Dove la sessione si copia, solo il pulsante «Annulla» restituisce il browser senza copiare. Senza la raccolta `richieste` non c'è una sessione salvata: lasciare la pagina fa solo finire il permesso, senza copia; dove Febe non ha un collegamento che copi la sessione (la modalità dimostrativa, un avvio fermato da un problema di configurazione, il browser non disponibile) lasciare la pagina vale «Annulla». Alla chiusura della finestra, lasciando la pagina in Docker e alla fine del permesso la copia ha le stesse garanzie di «Ho finito»: i comandi del collegamento, la presa del permesso di guida e il turno della pagina, che Febe rilascia solo quando la copia è salvata o buttata (la finestra tiene una presa del permesso finché la copia non è finita; la fine del permesso copia prima di rilasciarlo); il motore intanto è fermo e aspetta (regola 4: la pagina non è mai di due). Si copia solo con il cookie di sessione nel browser e solo da una pagina del sito che non sia di accesso o di verifica (né il riposo). Alla chiusura della finestra e lasciando la pagina in Docker Febe aspetta al più 30 secondi che finisca un altro comando del collegamento in corso, perché il motore non resti trattenuto (se non finisce, il permesso finisce senza copia, e il registro lo dice); poi vale il limite di 10 secondi della copia. Un errore imprevisto (database, disco) si scrive nel registro con il solo tipo d'errore e il permesso si rilascia lo stesso. Lì non c'è un messaggio: l'esito è una riga del registro con soli conteggi e lo stato nel riquadro della pagina Collegamento. La fine del permesso non copia di nuovo se la finestra (o la pagina lasciata) ha appena copiato, e un «Ho finito» tardivo dopo una copia fatta lasciando il browser non rilegge nulla e dice che la sessione era già stata copiata.
|
||||
**Quando si copia** (decisione di Alberto del 18 novembre 2026, tappa S4b di #36). In tre momenti, sempre **prima che la pagina torni al motore**: a «Ho finito»; quando Alberto chiude la finestra «Browser di Febe» su Windows (anche quando resta ridotta a icona troppo a lungo); quando il permesso di guida finisce da solo. In Docker, al posto della finestra, conta **lasciare la pagina del browser** (risposta di Alberto del 25 novembre 2026): mentre Alberto guida, passare dalla pagina «Browser» o dalla vista remota della pagina Collegamento a un'altra pagina di Febe, chiudere la scheda o la finestra del browser in cui la guarda, o perderne il collegamento. Febe lo riconosce dal server: si chiude l'ultima vista remota aperta durante il permesso (la pagina che si lascia lo dice subito; una scheda chiusa o un collegamento perso chiudono la sua connessione) e per 5 secondi non se ne apre un'altra, così ricaricare la pagina non è lasciarla (i 5 secondi di grazia sono la risposta di Alberto del 29 novembre 2026, §16 domanda 20; il 25 novembre aveva detto solo che lasciare la pagina copia la sessione). Da lì vale ciò che vale per la finestra di Windows: la copia, se la pagina è sul sito e non è di accesso o di verifica, poi il permesso finisce e la pagina torna al motore, che rimette il browser a riposo. L'interfaccia lo dice al server con `cancel` e `pageLeft` (`IConnectionService.LeavePageAsync`); su Windows, dove il browser è una finestra a parte, lasciare la pagina rilascia solo il permesso tenuto da quella pagina e la finestra resta com'è. Una vista chiusa perché il browser si è fermato non conta come pagina lasciata. Dove la sessione si copia, solo il pulsante «Annulla» restituisce il browser senza copiare. Senza la raccolta `richieste` non c'è una sessione salvata: lasciare la pagina fa solo finire il permesso, senza copia; dove Febe non ha un collegamento che copi la sessione (la modalità dimostrativa, un avvio fermato da un problema di configurazione, il browser non disponibile) lasciare la pagina vale «Annulla». Alla chiusura della finestra, lasciando la pagina in Docker e alla fine del permesso la copia ha le stesse garanzie di «Ho finito»: i comandi del collegamento, la presa del permesso di guida e il turno della pagina, che Febe rilascia solo quando la copia è salvata o buttata (la finestra tiene una presa del permesso finché la copia non è finita; la fine del permesso copia prima di rilasciarlo); il motore intanto è fermo e aspetta (regola 4: la pagina non è mai di due). Si copia solo con il cookie di sessione nel browser e solo da una pagina del sito che non sia di accesso o di verifica (né il riposo). Alla chiusura della finestra e lasciando la pagina in Docker Febe aspetta al più 30 secondi che finisca un altro comando del collegamento in corso, perché il motore non resti trattenuto (se non finisce, il permesso finisce senza copia, e il registro lo dice); poi vale il limite di 10 secondi della copia. Un errore imprevisto (database, disco) si scrive nel registro con il solo tipo d'errore e il permesso si rilascia lo stesso. Lì non c'è un messaggio: l'esito è una riga del registro con soli conteggi e lo stato nel riquadro della pagina Collegamento. La fine del permesso non copia di nuovo se la finestra (o la pagina lasciata) ha appena copiato, e un «Ho finito» tardivo dopo una copia fatta lasciando il browser non rilegge nulla e dice che la sessione era già stata copiata.
|
||||
|
||||
**Copia incompleta** (impostazione `sessione.copia-incompleta`, tappa S4b di #36, letta a ogni copia). Una copia a cui manca qualche valore o `doc_id` che un'operazione configurata manda segue l'opzione «Copia incompleta» della pagina Collegamento: **«Sostituisci comunque»** (predefinita), perché tenere una copia più vecchia potrebbe tenere i cookie di un altro accesso; oppure **«Tieni la copia completa di prima»**, che lascia la sessione salvata com'era se quella era completa, e lo dice («Ho tenuto la copia del 17 novembre: in quella nuova mancavano …»). Una copia completa sostituisce sempre. Il messaggio di «Ho finito» conta solo i valori e i `doc_id` che un'operazione configurata manda, e dice com'è secondo ciò che è successo. Se la copia nuova ha sostituito quella di prima («Sostituisci comunque», o «Tieni la copia completa di prima» quando quella di prima era già incompleta): le richieste che li usano non partono e, alla prima, Febe si ferma come disconnessione e chiede un nuovo accesso (mai un ritorno alle pagine) finché un nuovo «Ho finito» non li trova. Se Febe ha tenuto la copia completa di prima: la sessione salvata resta quella di quella data, le richieste continuano a usarla e nulla si ferma per quei valori; la copia nuova non si tiene. Dopo «Ho finito» il permesso di guida è finito: per rifare la copia Alberto riapre il browser dalla pagina Collegamento («Usa il browser» o «Pagina iniziale») e preme di nuovo «Ho finito», ed è ciò che il messaggio di una copia rifiutata gli dice. Una copia rifiutata (pagina fuori dal sito, pagina di accesso o verifica, browser che non risponde, nessun user agent) la lascia com'era. Con il sito di prova e `--accesso-di-prova` la copia si fa anche dopo l'accesso automatico, come la farebbe Alberto.
|
||||
|
||||
@@ -552,7 +561,7 @@ La pagina mostra versioni ridotte; gli indirizzi delle versioni migliori sono ne
|
||||
3. Senza browser, la via principale dal 16 novembre 2026 (§6.0, tappa S5 di #36): `HttpClient` verso i soli domini del CDN presenti nell'indirizzo ricevuto, mai verso `instagram.com`, senza seguire rinvii fuori dal CDN. Senza cookie, con l'user agent della sessione salvata. Se il CDN la rifiuta, il file resta in attesa e l'interfaccia lo dice.
|
||||
4. Il file si scrive con un nome temporaneo, se ne calcola lo SHA-256 e lo si rinomina. Uno scaricamento interrotto non lascia mai un file con il nome definitivo.
|
||||
5. Se l'indirizzo è scaduto, il file torna «da scaricare». Il recupero passa dalla ricetta Post singolo, che rilegge il post e ne ottiene uno nuovo, dentro il suo tetto. Per le storie non c'è recupero dopo la scadenza.
|
||||
6. Coda dedicata, al massimo due scaricamenti insieme, piccole pause casuali, tetto giornaliero sui dati. L'ordine della coda segue **«Cosa scaricare prima»** dell'account del file (§7.2; tappa D1 del traguardo 0.3.0): prima i file del tipo che viene primo, poi gli altri tipi nell'ordine, e dentro un tipo prima quelli che scadono prima, poi i più vecchi in attesa. Con l'ordine predefinito le storie, che scadono, vengono prima di tutto, come oggi; le foto del profilo vanno con i post. Come proposta (§16 domanda 21: Alberto ha chiesto solo l'ordine), un posto su otto è riservato al file che aspetta da più tempo in **tutta** la coda, di qualunque tipo: serve a garantire che nessun file aspetti per sempre (per esempio un tipo in fondo all'ordine quando il tetto dei dati finisce ogni giorno prima della coda), non è una quota per tipo. Un tipo trovato dopo un arretrato più vecchio di un altro tipo (taggati scoperti dopo migliaia di post dello storico) aspetta che quell'arretrato finisca; gli altri sette posti su otto seguono l'ordine.
|
||||
6. Coda dedicata, al massimo due scaricamenti insieme, piccole pause casuali, tetto giornaliero sui dati. L'ordine della coda segue **«Cosa scaricare prima»** dell'account del file (§7.2; tappa D1 del traguardo 0.3.0): prima i file del tipo che viene primo, poi gli altri tipi nell'ordine, e dentro un tipo prima quelli che scadono prima, poi i più vecchi in attesa. Con l'ordine predefinito le storie, che scadono, vengono prima di tutto, come oggi; le foto del profilo vanno con i post. Come ha confermato Alberto il 29 novembre 2026 (§16 domanda 21; prima aveva chiesto solo l'ordine), un posto su otto è riservato al file che aspetta da più tempo in **tutta** la coda, di qualunque tipo: serve a garantire che nessun file aspetti per sempre (per esempio un tipo in fondo all'ordine quando il tetto dei dati finisce ogni giorno prima della coda), non è una quota per tipo. Un tipo trovato dopo un arretrato più vecchio di un altro tipo (taggati scoperti dopo migliaia di post dello storico) aspetta che quell'arretrato finisca; gli altri sette posti su otto seguono l'ordine.
|
||||
|
||||
### 6.6 Ipotesi da provare in M0
|
||||
|
||||
@@ -609,7 +618,7 @@ Nessuno può garantire che basti. Per questo il motore ha tre livelli indipenden
|
||||
- **Pavimento.** La pausa minima vale sempre, anche con molto lavoro arretrato. L'arretrato si smaltisce nei giorni, non stringendo le pause.
|
||||
- **Avvio.** Dopo l'avvio del programma la prima sessione parte dopo un'attesa casuale fra 2 e 10 minuti. Tetti e registro delle azioni sono su disco: un riavvio non azzera nulla. Un programma che riparte più volte non deve produrre più traffico di uno che resta acceso.
|
||||
- **Composizione.** Una sessione comincia di norma con il Giro dei seguiti, prosegue con le storie segnalate, poi con i controlli di profilo scaduti, infine con qualche pagina di storico. Non tutte le sessioni fanno tutto: circa una su tre si limita al giro e alle storie. L'ordine degli account è estratto a caso con pesi, mai lo stesso. Dalla tappa D1 l'ordine delle visite dopo il giro lo pesa anche «Cosa scaricare prima» (qui sotto).
|
||||
- **Cosa scaricare prima** (issue #59, tappa D1 del traguardo 0.3.0; decisione di Alberto del 25 novembre 2026). Un ordine dei tipi, generale (Impostazioni → Limiti e comportamento, mockup 07) e per account (§4.4: «Come le impostazioni generali», il predefinito, oppure un ordine suo), che si cambia trascinando le righe o, da tastiera, con i pulsanti «Su» e «Giù». Ordine predefinito: storie, evidenza, post, reel, taggati (Alberto ha detto storie, post, reel, taggati; le raccolte in evidenza subito dopo le storie sono una proposta, §16 domanda 19). Un tipo è quello delle ricette di §6.3: storie per Storie di un account, evidenza per Raccolta in evidenza, post per Controllo del profilo e Storico (foto del profilo comprese), reel per Reel, taggati per Taggati. Pesa in due posti, dopo il Giro dei seguiti, che resta sempre primo, e dopo le storie segnalate dalla barra delle storie, che restano davanti (lo storico viene dopo): sulle **visite del motore nella sessione**, perché fra il lavoro già dovuto e permesso la visita successiva si estrae con il peso dell'account moltiplicato per il peso del tipo (tabella qui sotto), così il primo tipo viene di norma prima ma non sempre; e sulla **coda dei file** (§6.5), dove i file del primo tipo passano prima. Restano come sono il Governatore e i tetti (§7.4), le pause, la fascia, le frequenze (§7.3), la composizione casuale delle sessioni (circa una su tre si limita al giro e alle storie), l'umore e l'avvio graduale: l'ordine pesa le scelte dentro ciò che è già permesso, non aggiunge visite, non le anticipa e non le rende fisse; un tipo in cima senza nulla di dovuto non si visita. Un reel è un post: in coda conta come reel se Febe sa che lo è, cioè se l'ha trovato percorrendo la scheda Reel del profilo o se la risposta lo dice (`product_type` «clips»), altrimenti come post. Il segno non si toglie più, un taggato non è mai un reel e i post salvati prima della tappa D1 restano post. Nella coda dei file un posto su otto va al file che aspetta da più tempo (§6.5; una proposta, §16 domanda 21). Le storie scadono in 24 ore: spostarle in basso le espone a scadere prima di essere scaricate, e l'impostazione lo dice accanto all'elenco.
|
||||
- **Cosa scaricare prima** (issue #59, tappa D1 del traguardo 0.3.0; decisione di Alberto del 25 novembre 2026). Un ordine dei tipi, generale (Impostazioni → Limiti e comportamento, mockup 07) e per account (§4.4: «Come le impostazioni generali», il predefinito, oppure un ordine suo), che si cambia trascinando le righe o, da tastiera, con i pulsanti «Su» e «Giù». Ordine predefinito: storie, evidenza, post, reel, taggati (Alberto ha detto storie, post, reel, taggati; le raccolte in evidenza subito dopo le storie le ha confermate il 29 novembre 2026, §16 domanda 19). Un tipo è quello delle ricette di §6.3: storie per Storie di un account, evidenza per Raccolta in evidenza, post per Controllo del profilo e Storico (foto del profilo comprese), reel per Reel, taggati per Taggati. Pesa in due posti, dopo il Giro dei seguiti, che resta sempre primo, e dopo le storie segnalate dalla barra delle storie, che restano davanti (lo storico viene dopo): sulle **visite del motore nella sessione**, perché fra il lavoro già dovuto e permesso la visita successiva si estrae con il peso dell'account moltiplicato per il peso del tipo (tabella qui sotto), così il primo tipo viene di norma prima ma non sempre; e sulla **coda dei file** (§6.5), dove i file del primo tipo passano prima. Restano come sono il Governatore e i tetti (§7.4), le pause, la fascia, le frequenze (§7.3), la composizione casuale delle sessioni (circa una su tre si limita al giro e alle storie), l'umore e l'avvio graduale: l'ordine pesa le scelte dentro ciò che è già permesso, non aggiunge visite, non le anticipa e non le rende fisse; un tipo in cima senza nulla di dovuto non si visita. Un reel è un post: in coda conta come reel se Febe sa che lo è, cioè se l'ha trovato percorrendo la scheda Reel del profilo o se la risposta lo dice (`product_type` «clips»), altrimenti come post. Il segno non si toglie più, un taggato non è mai un reel e i post salvati prima della tappa D1 restano post. Nella coda dei file un posto su otto va al file che aspetta da più tempo (§6.5; risposta di Alberto del 29 novembre 2026, §16 domanda 21). Le storie scadono in 24 ore: spostarle in basso le espone a scadere prima di essere scaricate, e l'impostazione lo dice accanto all'elenco.
|
||||
- **Umore della sessione.** Ogni sessione ha un fattore di velocità estratto una volta, che moltiplica tutte le attese: alcune sessioni sono svelte, altre lente.
|
||||
- **Riposo.** A fine sessione il browser torna alla pagina vuota (§6.1).
|
||||
- **Avvio graduale.** Se attivo (lo è per impostazione predefinita), nei primi giorni dopo il collegamento e dopo ogni verifica risolta i tetti partono dalla metà e risalgono in modo lineare fino al valore pieno, nel numero di giorni previsto dal profilo.
|
||||
@@ -783,7 +792,7 @@ Tabelle principali. Completa colonne e indici dove serve, ma non cambiare i conc
|
||||
| `event` | Cronologia leggibile per l'interfaccia |
|
||||
| `following` | Copia locale dell'elenco dei profili seguiti, con data di lettura |
|
||||
| `import_run`, `import_file` | Importazioni e loro file, con esito e decisione |
|
||||
| `export_destination`, `export_account`, `export_copy`, `export_run`, `export_item`, `video_analysis`, `media_conversion` | Migrazione `0003` (tappa E1 del traguardo 0.3.0, §4.10; la `0002` è della tappa D1), usate dalla tappa E2 (copie degli originali; `video_analysis` e `media_conversion` aspettano E4 ed E3): destinazioni di esportazione (generale o di un account, con una colonna esplicita per l'ambito, `General` o `Account`; una riga è una cartella per sempre: togliere una destinazione o cambiarne la cartella la ritira, e le copie registrate restano; rimuovere un account la lascia senza account, inattiva («Automatica» spenta, «Solo i nuovi» dimenticato, anche quando l'account torna), e ne tiene il nome: non la cancella); l'interruttore «Esporta questo account» in `export_account`, che se ne va con l'account (nessuna riga vuol dire acceso, §4.10); copie fatte, per SHA-256 dell'originale, destinazione, account effettivo, variante e formato effettivi e istante del fotogramma, con il loro stato (§4.10), che restano anche se l'elemento si elimina e tengono lo SHA-256 del file che ha preso il posto dell'originale per «Superato»; rimuovere un account toglie l'account alle sue copie e ne tiene identificativo di Instagram e nome, così quelle della cartella generale, anche «Tolto» e «Superato», tornano all'account aggiunto di nuovo; lavori di esportazione e loro file (sul modello di `import_run` e `import_file`, per interrompere e riprendere); esito dell'analisi dei video fermi per SHA-256 e numero dell'algoritmo; file convertiti per la libreria in `media_conversion`, una riga per file legata alla riga `media` dell'originale (decisione di Alberto del 26 novembre 2026): la tabella `media` non cambia. Impostazioni in `setting` con chiavi `esportazione.*` (`esportazione.formato-foto`, `esportazione.formato-video`, `esportazione.libreria-formato-foto`, `esportazione.libreria-formato-video`, `esportazione.stesso-post`); nessuna colonna nuova in `account` |
|
||||
| `export_destination`, `export_account`, `export_copy`, `export_run`, `export_item`, `video_analysis`, `media_conversion` | Migrazione `0003` (tappa E1 del traguardo 0.3.0, §4.10; la `0002` è della tappa D1), usate dalla tappa E2 (copie degli originali) e dalla tappa E3 (copie convertite e fotogrammi in `export_copy` ed `export_item`, conversione della libreria in `media_conversion`, senza una migrazione nuova; `video_analysis` aspetta E4): destinazioni di esportazione (generale o di un account, con una colonna esplicita per l'ambito, `General` o `Account`; una riga è una cartella per sempre: togliere una destinazione o cambiarne la cartella la ritira, e le copie registrate restano; rimuovere un account la lascia senza account, inattiva («Automatica» spenta, «Solo i nuovi» dimenticato, anche quando l'account torna), e ne tiene il nome: non la cancella); l'interruttore «Esporta questo account» in `export_account`, che se ne va con l'account (nessuna riga vuol dire acceso, §4.10); copie fatte, per SHA-256 dell'originale, destinazione, account effettivo, variante e formato effettivi e istante del fotogramma, con il loro stato (§4.10), che restano anche se l'elemento si elimina e tengono lo SHA-256 del file che ha preso il posto dell'originale per «Superato»; rimuovere un account toglie l'account alle sue copie e ne tiene identificativo di Instagram e nome, così quelle della cartella generale, anche «Tolto» e «Superato», tornano all'account aggiunto di nuovo; lavori di esportazione e loro file (sul modello di `import_run` e `import_file`, per interrompere e riprendere); esito dell'analisi dei video fermi per SHA-256 e numero dell'algoritmo; file convertiti per la libreria in `media_conversion`, una riga per file legata alla riga `media` dell'originale (decisione di Alberto del 26 novembre 2026): la tabella `media` non cambia. Le note di un file di un lavoro (`export_item.note`) e l'ultimo errore di una conversione (`media_conversion.last_error`) sono elenchi di codici separati da spazi; per una conversione riuscita `last_error` dice ciò che non si è tenuto (tappa E3, `docs/decisioni.md`). Impostazioni in `setting` con chiavi `esportazione.*` (`esportazione.formato-foto`, `esportazione.formato-video`, `esportazione.libreria-formato-foto`, `esportazione.libreria-formato-video`, `esportazione.stesso-post`); nessuna colonna nuova in `account` |
|
||||
|
||||
Vincoli che contano:
|
||||
|
||||
@@ -907,7 +916,7 @@ Ogni riga è un file in `docs/mockup/`. I dati sono inventati: gli account che f
|
||||
|
||||
Schermate senza mockup, da comporre con gli elementi del foglio di stile: Scheda account → Cronologia (elenco dei controlli con esito); Impostazioni → Notifiche, Dati e copie di sicurezza, Informazioni; revisione dei doppioni dopo uno scaricamento (lo stesso confronto del mockup 09); primo avvio (la schermata vuota del mockup 13 con i due pulsanti, nella Libreria vuota; nella Dashboard, che `/` apre per prima, lo stesso benvenuto in un riquadro compatto sopra il cruscotto finché non c'è nessun account, §7.9); pagina di errore di configurazione (§8.2, §11).
|
||||
|
||||
Schermate dell'esportazione (§4.10, traguardo 0.3.0), anche queste senza mockup, composte dai mockup esistenti (decisione di Alberto del 18 novembre 2026): Impostazioni → Esportazione (cartella generale, formati predefiniti delle copie, conversione della libreria, «Una copia per account» o «Una copia sola», nota su `/esporta` in Docker; dai mockup 08 e 07); finestra della destinazione (cartella, tipi, formati, schema con anteprima, «Automatica» con la domanda «Solo i nuovi»; dal mockup 08 e dai dialoghi del 13); blocco «Copie esterne» nella scheda account → Impostazioni, sotto «Cartella» (mockup 05); finestra «Copia in…» con il riepilogo («312 file · 41 già copiati, saltati · 3 HEIC copiati come sono · circa 4,2 GB», con «con perdita» quando serve) e finestra «Fotogrammi…» (dialoghi del 13 e mockup 09); in Libreria e nella scheda account il menu dell'icona CSV («Esporta l'elenco (CSV)», «Copia i file in…»), «Copia in…» e «Fotogrammi…» nella barra della selezione, il filtro «Copie» e il segno sulla tessera (mockup 01 e 12); nel visualizzatore «Copia in…», «Fotogramma», «È un video fermo?» e le righe delle copie nel pannello File (mockup 02); scheda «Esportazione» nella Dashboard con avanzamento, Interrompi, Riprendi e resoconto (mockup 06 e passo 2 del 09). Le differenze rispetto ai mockup da cui nascono vanno in `docs/schermate/differenze.md`.
|
||||
Schermate dell'esportazione (§4.10, traguardo 0.3.0), anche queste senza mockup, composte dai mockup esistenti (decisione di Alberto del 18 novembre 2026): Impostazioni → Esportazione (cartella generale, «Formati delle copie», «Conversione della libreria» con la domanda «Convertire anche i N file già in libreria?» e la riga di stato con «Interrompi», «Riprendi» e «Riprova i non riusciti», «Una copia per account» o «Una copia sola», nota su `/esporta` in Docker; dai mockup 08 e 07); finestra della destinazione (cartella, tipi, formati con «Come le impostazioni generali», schema con anteprima, e dalla tappa E5 «Automatica» con la domanda «Solo i nuovi»; dal mockup 08 e dai dialoghi del 13); blocco «Copie esterne» nella scheda account → Impostazioni, sotto «Cartella» (mockup 05); finestra «Copia in…» con il riepilogo («312 file · 41 già copiati, saltati · circa 3 HEIC copiati come sono · circa 4,2 GB», con «con perdita» quando serve) e la riga «Formato: come la destinazione · Cambia», e finestra «Fotogrammi…» (dialoghi del 13 e mockup 09: «Questo istante», «Uno ogni k secondi», «N in tutto», le anteprime, il formato, «Scarica» o «Nella cartella delle copie»); in Libreria e nella scheda account il menu dell'icona CSV («Esporta l'elenco (CSV)», «Copia i file in…»), «Copia in…» e «Fotogrammi…» nella barra della selezione, il filtro «Copie» e il segno sulla tessera, anche «Solo fotogrammi» (mockup 01 e 12); nel visualizzatore «Copia in…», «Fotogramma», dalla tappa E4 «È un video fermo?», e nel pannello File le righe delle copie con la loro forma e le righe dei file convertiti (mockup 02); scheda «Esportazione» nella Dashboard con avanzamento, Interrompi, Riprendi, il riquadro «Conversione della libreria» e il resoconto con «Come sono» e «Note» (mockup 06 e passo 2 del 09). Le differenze rispetto ai mockup da cui nascono vanno in `docs/schermate/differenze.md`.
|
||||
|
||||
Schermate della tappa D1 (issue #59, traguardo 0.3.0), anche queste senza mockup, composte dai mockup esistenti (decisione di Alberto del 25 novembre 2026):
|
||||
|
||||
@@ -1166,15 +1175,26 @@ Falle quando arrivi al punto indicato, una per volta, proponendo la risposta del
|
||||
| 16 | **Risposta di Alberto del 18 novembre 2026: sì** (§3, §14.1). Domanda di allora: le immagini di riferimento dei codec si generano una sola volta con SkiaSharp prima che esca? | C1, prima di cominciare | Risposta: SkiaSharp permesso un'ultima volta per generarle, fatto; per JPEG e WEBP con perdita le tolleranze di §14.1 |
|
||||
| 17 | **Risposta di Alberto del 18 novembre 2026: si tolgono** (regola 13, §3, §15 tappa C6). Domanda di allora: componenti in uso oltre a quelli ammessi dalla regola 13 (Xvfb e gli altri pacchetti Debian di §11, il carattere Archivo e le icone Lucide come file, NSIS e Node nella CI): restano come eccezioni per nome o si tolgono? | E0 | Risposta: escono anche questi; installatore senza NSIS (scritto in casa), CI senza Node (passi di shell con git e curl verso l'API di Gitea), caratteri di sistema (`system-ui`) al posto di Archivo, icone SVG disegnate in casa al posto di Lucide. Restano solo Xvfb e i pacchetti Debian che servono a Chromium, e gitleaks e Trivy nella sola CI. Inoltre: lo stesso post in due account si copia con «Una copia per account» come predefinito (§4.10) |
|
||||
| 18 | **Risposta di Alberto del 25 novembre 2026: le estensioni di formato (RExt) restano** (§3, §15 tappa C4). Domanda di allora: decodificatore H.265, oltre a Main, Main 10 e Main Still Picture, quali profili? Estensioni di formato (4:2:2, 4:4:4, 12 e 16 bit, senza perdita), scalabile (SHVC), multivista (MV-HEVC), 3D, contenuti dello schermo (SCC) | C4, prima di cominciare | Risposta: tutti i profili della serie di ITU-T H.265.1 scelta per Febe (cartelle `HEVC_v1` e `RExt`): Main, Main 10, Main Still Picture e RExt fino a 12 bit. Ciò che non ha flussi in quella serie (precisione estesa a 16 bit, SHVC, MV-HEVC, 3D, SCC) dice «Fotogramma non disponibile per questo video». Inoltre, lo stesso giorno: in Docker lasciare la pagina del browser copia la sessione (§6.0); nell'immagine Docker `fonts-noto-color-emoji` resta e `fonts-liberation` è uscito (§11); le immagini troncate si rifiutano con «File danneggiato o incompleto», senza impronta, e restano in libreria (§8.4) |
|
||||
| 19 | «Cosa scaricare prima»: le raccolte in evidenza vanno subito dopo le storie? Alberto ha detto storie, post, reel, taggati, senza nominarle | D1, prima di cominciare | Sì: storie, evidenza, post, reel, taggati, perché sono storie anche loro; si possono comunque spostare trascinandole |
|
||||
| 20 | In Docker lasciare la pagina del browser copia la sessione (risposta del 25 novembre, domanda 18) quando per 5 secondi non si riapre un'altra vista remota, così una pagina ricaricata non è lasciata: vanno bene i 5 secondi di grazia? Alberto non ha detto una durata | S4b, prima della prova dal vivo in Docker | Sì, 5 secondi: bastano a una pagina che si ricarica e non trattengono il motore |
|
||||
| 21 | «Cosa scaricare prima», coda dei file (§6.5): basta riservare un posto su otto al file che aspetta da più tempo in tutta la coda, così nessun file aspetta per sempre, o serve un minimo per tipo? Alberto ha chiesto solo l'ordine | D1, prima di unire | Il posto su otto, senza quote per tipo: un tipo trovato dopo un arretrato più vecchio aspetta che quell'arretrato finisca, ma nessun file aspetta per sempre |
|
||||
| 22 | Copie esterne (§4.10): con «Esporta questo account» spento, «Copia in…» chiesto a mano salta anche quell'account, o l'interruttore vale solo per le copie automatiche? Alberto ha deciso solo che è acceso per impostazione predefinita (27 novembre 2026) | E2, prima di unire | Spento salta ogni copia di quell'account, anche a mano: la finestra lo dice («12 di account che non si esportano»), le copie già fatte restano e il visualizzatore le mostra. Così fa la tappa E2 |
|
||||
| 23 | Copie esterne in Docker (§4.10, §11): se sono montate solo delle sottocartelle (`/esporta/usb`, `/esporta/nas`) e non `/esporta`, le copie sono attive? | E2, prima di unire | Sì: una destinazione è accettata quando sta su un montaggio in `/esporta` o sotto; una cartella di `/esporta` che non sta su un montaggio si rifiuta, perché sarebbe il disco delle immagini. Così fa la tappa E2 |
|
||||
| 24 | L'interruttore «Automatica» delle destinazioni (§4.10) si mostra già nella tappa E2, anche se fino a E5 non fa nulla? | E2, prima di unire | No: nascosto fino a E5, perché un interruttore che non fa nulla inganna; il database e l'interfaccia di programmazione lo registrano già. Così fa la tappa E2 |
|
||||
| 25 | Nella finestra «Copia in…» (§4.10) si offre «Copia di nuovo anche i N tolti o superati», o «Copia di nuovo» resta solo nel visualizzatore, un file alla volta? | E2, prima di unire | Si offre nella finestra, spenta all'apertura: senza la casella i tolti e i superati si saltano e si contano. Così fa la tappa E2 |
|
||||
| 26 | Il conteggio della scheda dell'account, il filtro «Copie» e il segno sulla tessera (§4.10) considerano solo i file dei tipi scelti per la destinazione (con il solo «post foto», le storie non sono dovute)? | E2, prima di unire | Sì, solo i file dovuti (§4.10, «File dovuti»), così «312 su 1.204 non ancora copiati» è ciò che «Copia in…» copierebbe. Così fa la tappa E2 |
|
||||
| 27 | Il margine di spazio libero delle destinazioni (§4.10, «più un margine»): quanto? | E2, prima di unire | 64 MB oltre al prossimo file. Così fa la tappa E2 |
|
||||
| 19 | **Risposta di Alberto del 29 novembre 2026: sì, come proposto**. Domanda di allora: «Cosa scaricare prima»: le raccolte in evidenza vanno subito dopo le storie? Alberto ha detto storie, post, reel, taggati, senza nominarle | D1, prima di cominciare | Risposta: sì: storie, evidenza, post, reel, taggati, perché sono storie anche loro; si possono comunque spostare trascinandole |
|
||||
| 20 | **Risposta di Alberto del 29 novembre 2026: sì, come proposto**. Domanda di allora: in Docker lasciare la pagina del browser copia la sessione (risposta del 25 novembre, domanda 18) quando per 5 secondi non si riapre un'altra vista remota, così una pagina ricaricata non è lasciata: vanno bene i 5 secondi di grazia? Alberto non ha detto una durata | S4b, prima della prova dal vivo in Docker | Risposta: sì, 5 secondi: bastano a una pagina che si ricarica e non trattengono il motore |
|
||||
| 21 | **Risposta di Alberto del 29 novembre 2026: sì, come proposto** (§6.5). Domanda di allora: «Cosa scaricare prima», coda dei file (§6.5): basta riservare un posto su otto al file che aspetta da più tempo in tutta la coda, così nessun file aspetta per sempre, o serve un minimo per tipo? Alberto ha chiesto solo l'ordine | D1, prima di unire | Risposta: il posto su otto, senza quote per tipo: un tipo trovato dopo un arretrato più vecchio aspetta che quell'arretrato finisca, ma nessun file aspetta per sempre |
|
||||
| 22 | **Risposta di Alberto del 29 novembre 2026: sì, come proposto** (§4.10). Domanda di allora: copie esterne (§4.10): con «Esporta questo account» spento, «Copia in…» chiesto a mano salta anche quell'account, o l'interruttore vale solo per le copie automatiche? Alberto ha deciso solo che è acceso per impostazione predefinita (27 novembre 2026) | E2, prima di unire | Risposta: spento salta ogni copia di quell'account, anche a mano: la finestra lo dice («12 di account che non si esportano»), le copie già fatte restano e il visualizzatore le mostra |
|
||||
| 23 | **Risposta di Alberto del 29 novembre 2026: sì, come proposto** (§4.10, §11). Domanda di allora: copie esterne in Docker (§4.10, §11): se sono montate solo delle sottocartelle (`/esporta/usb`, `/esporta/nas`) e non `/esporta`, le copie sono attive? | E2, prima di unire | Risposta: sì: una destinazione è accettata quando sta su un montaggio in `/esporta` o sotto; una cartella di `/esporta` che non sta su un montaggio si rifiuta, perché sarebbe il disco delle immagini |
|
||||
| 24 | **Risposta di Alberto del 29 novembre 2026: sì, come proposto** (§4.10). Domanda di allora: l'interruttore «Automatica» delle destinazioni (§4.10) si mostra già nella tappa E2, anche se fino a E5 non fa nulla? | E2, prima di unire | Risposta: no: nascosto fino a E5, perché un interruttore che non fa nulla inganna; il database e l'interfaccia di programmazione lo registrano già |
|
||||
| 25 | **Risposta di Alberto del 29 novembre 2026: sì, come proposto** (§4.10). Domanda di allora: nella finestra «Copia in…» (§4.10) si offre «Copia di nuovo anche i N tolti o superati», o «Copia di nuovo» resta solo nel visualizzatore, un file alla volta? | E2, prima di unire | Risposta: si offre nella finestra, spenta all'apertura: senza la casella i tolti e i superati si saltano e si contano |
|
||||
| 26 | **Risposta di Alberto del 29 novembre 2026: sì, come proposto** (§4.10). Domanda di allora: il conteggio della scheda dell'account, il filtro «Copie» e il segno sulla tessera (§4.10) considerano solo i file dei tipi scelti per la destinazione (con il solo «post foto», le storie non sono dovute)? | E2, prima di unire | Risposta: sì, solo i file dovuti (§4.10, «File dovuti»), così «312 su 1.204 non ancora copiati» è ciò che «Copia in…» copierebbe |
|
||||
| 27 | **Risposta di Alberto del 29 novembre 2026: sì, come proposto** (§4.10). Domanda di allora: il margine di spazio libero delle destinazioni (§4.10, «più un margine»): quanto? | E2, prima di unire | Risposta: 64 MB oltre al prossimo file |
|
||||
| 28 | **Risposta di Alberto del 29 novembre 2026: sì, come proposto** (§4.10). Domanda di allora: formati delle copie (§4.10, «Già copiato»): se il formato cambia (per esempio da Originale a JPG), i file già copiati nella forma di prima si copiano di nuovo? L'identità di una copia comprende il formato, quindi la risposta cambia che cosa vuol dire «già copiato» | E3, prima di unire | Risposta: no: «già copiato» guarda il file, non il formato, e il formato nuovo vale per i file non ancora copiati; un file già copiato in un'altra forma si salta con «Già copiato in un altro formato». Per averlo nella forma nuova si toglie il file vecchio dalla destinazione, «Controlla le copie» lo segna «Tolto», poi «Copia di nuovo». L'alternativa è «già copiato» per formato: un cambio ricopierebbe ogni file nella forma nuova accanto a quella vecchia |
|
||||
| 29 | **Risposta di Alberto del 29 novembre 2026: sì, come proposto** (§4.10). Domanda di allora: conversione della libreria accesa (§4.10): si convertono solo i file nuovi o anche quelli già in libreria? Quando entra in coda un file nuovo? Che cosa succede quando si spegne? | E3, prima di unire | Risposta: si chiede, con «Solo i nuovi» come risposta proposta e «Anche i N già in libreria» (con lo spazio degli originali) come l'altra; un file nuovo entra in coda dopo la sua riga di `_febe.jsonl`; spenta, la coda si svuota e i convertiti restano dove sono |
|
||||
| 30 | **Risposta di Alberto del 29 novembre 2026: sì, come proposto**. Domanda di allora: il visualizzatore mostra i file convertiti della libreria accanto all'originale, con ciò che non si è tenuto? | E3, prima di unire | Risposta: sì, nel pannello File: «Convertito in PNG · 2,1 MB», con «Scarica» o «Mostra nella cartella» e le perdite su una seconda riga |
|
||||
| 31 | **Risposta di Alberto del 29 novembre 2026: sì, come proposto**. Domanda di allora: immagini con più di 8 bit per colore o CMYK verso PNG o WEBP senza perdita: i codificatori di Febe sono RGB a 8 bit. Si copia l'originale con una nota o si converte lo stesso? E un profilo ICC grigio, che l'uscita RGB non tiene? | E3, prima di unire | Risposta: si copia l'originale con una nota; verso JPG si convertono (JPG perde comunque, e il profilo CMYK si dice «non tenuto»); un profilo ICC grigio si dice «non tenuto» |
|
||||
| 32 | **Risposta di Alberto del 29 novembre 2026: sì, come proposto** (§4.10). Domanda di allora: fotogrammi (§4.10): nomi `_t0m12s340` per un istante e per «uno ogni k secondi», `_f001` per «N in tutto», `_fotogramma` tenuto per E4; l'istante del nome e di «già copiato» è quello del fotogramma davvero mostrato, in millesimi arrotondati in su. I fotogrammi si ruotano come il video si vede e non hanno metadati. Un fotogramma «Tolto» o «Superato» si riscrive a una nuova richiesta. Va bene? | E3, prima di unire | Risposta: sì |
|
||||
| 33 | **Risposta di Alberto del 29 novembre 2026: sì, come proposto**. Domanda di allora: «N in tutto»: fotogrammi al centro di N parti uguali ((i + ½) · durata / N)? «Uno ogni k secondi» da 0:00? | E3, prima di unire | Risposta: sì a tutti e due |
|
||||
| 34 | **Risposta di Alberto del 29 novembre 2026: sì, come proposto**. Domanda di allora: «Scarica» di più fotogrammi: uno zip; fino a 20 in qualunque momento; da 21 a 500 solo fuori dalle sessioni del motore e quando non lavorano importazione, copie o ricostruzione; oltre 500 solo «Nella cartella delle copie». Va bene? | E3, prima di unire | Risposta: sì |
|
||||
| 35 | **Risposta di Alberto del 29 novembre 2026: sì, come proposto**. Domanda di allora: formato proposto per i fotogrammi? | E3, prima di unire | Risposta: PNG: nessuna perdita, piena risoluzione |
|
||||
| 36 | **Risposta di Alberto del 29 novembre 2026: sì, come proposto**. Domanda di allora: un WEBP con perdita con «WEBP senza perdita»: si copia byte per byte o si ricodifica senza perdita? | E3, prima di unire | Risposta: byte per byte: è lo stesso formato, e ricodificarlo lo farebbe solo più grande |
|
||||
| 37 | **Risposta di Alberto del 29 novembre 2026: sì, come proposto**. Domanda di allora: importare una copia convertita o un fotogramma trovati in una destinazione (o un convertito della libreria): si riconosce («È una copia convertita (o un fotogramma) di un file già in libreria.») invece di proporlo come doppione probabile dell'originale? | E3, prima di unire | Risposta: sì, «già in libreria», mai una coppia di doppioni |
|
||||
| 38 | **Risposta di Alberto del 29 novembre 2026: sì, come proposto**. Domanda di allora: limiti: al più 1.000 fotogrammi per video e 20.000 per richiesta, «uno ogni k secondi» con k di almeno 0,1 s, N al più 1.000; foto copiate come sono oltre 40 megapixel (WEBP) o 100 (JPG e PNG), con un lato oltre 16.384 pixel per WEBP, oltre 512 MB; anteprime di al più 480 pixel entro 30 secondi; zip di al più 500 fotogrammi. Vanno bene? Alberto non ha dato numeri | E3, prima di unire | Risposta: sì: sono i limiti di memoria e di tempo di un server di casa |
|
||||
|
||||
---
|
||||
|
||||
@@ -1556,6 +1576,14 @@ Icone: fino alla tappa C6 della 0.3.0 erano quelle di Lucide (licenza ISC), con
|
||||
| Fotogramma | `Frame` | Un'immagine presa da un video |
|
||||
| Video fermo | `StillVideo` | Video che mostra sempre la stessa immagine: basta un fotogramma |
|
||||
| Rimuxaggio | `Remux` | Passaggio di un video in un altro contenitore senza ricodifica |
|
||||
| Formato delle copie | `ExportFormat` | Originale, JPG, PNG, WEBP senza perdita, MP4: generale, della destinazione o della singola «Copia in…» (§4.10) |
|
||||
| Copia convertita | `ExportVariant.Converted` | Una copia esterna in un altro formato; con l'intera e il fotogramma, una delle tre varianti di una copia (§4.10) |
|
||||
| Copiato com'è | `AsIs` (codici `AsIs…`) | Un file che non si converte (HEIC, raw, animato, CMYK…) e si copia byte per byte, con una nota (§4.10) |
|
||||
| Con perdita | `Lossy` | Una conversione che non tiene tutti i pixel: solo JPG, a qualità 92 (§4.10) |
|
||||
| Conversione della libreria | `LibraryConversion` | Il lavoro in sottofondo che aggiunge accanto all'originale il file convertito nel formato scelto per la libreria (§4.10) |
|
||||
| File convertito | `MediaConversion` | Un file aggiunto dalla conversione della libreria, legato al suo originale (`media_conversion`, §8.3) |
|
||||
| Solo fotogrammi | `ExportMark.FrameOnly` | Il segno di un elemento che di copiato ha soltanto fotogrammi: non conta come «Copiato» (§4.10) |
|
||||
| Note | `ExportText.Notes`, codici | Ciò che una copia o una conversione dice di sé: copiata com'è, che cosa non ha tenuto, perché si è saltata (§4.10) |
|
||||
| Dashboard | `Dashboard` | La pagina iniziale e cruscotto del motore, prima voce della barra laterale; prima si chiamava Attività (§7.9) |
|
||||
| Cosa scaricare prima | `DownloadOrder` | L'ordine dei tipi (storie, evidenza, post, reel, taggati) che pesa sulle visite dopo il Giro dei seguiti e sulla coda dei file, generale o di un account (§7.2) |
|
||||
| Raggruppa i post | `MosaicMode.Grouped` | Il mosaico con una tessera per elemento, il predefinito (§4.6) |
|
||||
|
||||
@@ -629,3 +629,34 @@ Ogni scelta tecnica presa strada facendo, con data e motivo (specifica §15).
|
||||
| 2026-11-27 | Tappa E2, revisione: **«Una copia sola»** ha una regola sola in piano, filtro «Copie», visualizzatore e copiatore: conta una copia nella destinazione dell'account stesso, o una copia di **un altro account** (mai una riga generale senza account) in una destinazione in uso. `FindCopiedElsewhereAsync` riceve l'account da escludere. «Storia» del filtro comprende ogni riga «Tolto» o «Superato», con o senza data | I quattro punti davano risposte diverse per lo stesso file |
|
||||
| 2026-11-27 | Tappa E2, revisione: il controllo della cartella confronta anche **dove sta davvero** la cartella (`FolderIdentity`): su Windows il percorso finale (`GetFinalPathNameByHandle`, che risolve collegamenti, giunzioni, `subst` e unità di rete), su Linux `realpath` più il dispositivo `major:minor` e la cartella del suo file system letti da `/proc/self/mountinfo` (un bind mount di una cartella della libreria è dentro la radice del montaggio della libreria). Su Windows le giunzioni **sotto** la cartella scelta non si cercano | SPECIFICA §4.10, «Cartelle rifiutate»: il confronto per testo e il file di prova non vedevano un collegamento né un bind mount di una sottocartella |
|
||||
| 2026-11-27 | Tappa E2, revisione: lo **sfoglia delle cartelle** (`/api/export/folders`) ha un tempo massimo per l'elenco e uno per ogni sottocartella (guardate in parallelo; oltre il tempo «senza sottocartelle»); il piano dice `HasDestination`, e «Copia in…» scrive «Nessuna cartella» solo quando non ce n'è nessuna, altrimenti «file di account che non si esportano». Il visualizzatore tiene «In copia…» dopo «Copia di nuovo» e rilegge le copie alla fine del lavoro; la Dashboard fa una lettura per volta | Una condivisione morta bloccava il dialogo; le altre erano parole sbagliate o letture doppie |
|
||||
| 2026-11-28 | Tappa E3: lo **zip dei fotogrammi** si scrive con l'API asincrona di `ZipArchive` (`CreateAsync`, `OpenAsync`, `DisposeAsync`) su `Response.Body`, senza abilitare l'I/O sincrono di Kestrel: .NET 10 scrive ancora in modo sincrono il piccolo descrittore di ogni voce, che `FrameService` tiene in memoria (al più 64 KB) e manda con la scrittura asincrona seguente. Il video della dimostrazione è scritto in casa (`H264PcmWriter`: solo macroblocchi I_PCM, 240×432, 8 fotogrammi al secondo, 2 s) | Un `Write` sincrono sul corpo della risposta è rifiutato da Kestrel; abilitarlo terrebbe un thread fermo per ogni lettore lento |
|
||||
| 2026-11-28 | Tappa E3: **«già copiato» per file, in qualunque forma** (proposta, §16 domanda 28). Un file dovuto è «Copiato» quando ha una copia corrente intera o convertita in qualunque formato; «Tolto» o «Superato» quando lo è la sua ultima copia intera o convertita; i fotogrammi non contano mai (`variant <> 'Frame'` in `CopyStatesSql`, `ReplacedCopySql`, `ReplacedStatesSql`, `CopiedElsewhereSql` e nei rami «Non riuscito», «Tolti o superati» e «Storia» del filtro). Piano, filtro, segni, conteggio dell'account, «Una copia sola» e copiatore leggono la stessa regola (`ListCurrentCopiesAnyFormAsync`, `FindLatestCopyAnyFormAsync`, `FindCopiedElsewhereAsync(sha, exceptAccountId)`, tutte su `ix_export_copy_sha256`); l'identità registrata resta quella completa di §4.10 (`ux_export_copy_identity`). Per lo stato di un file vale «Copiato» > «Non riuscito» > l'ultima riga «Tolto»/«Superato», come il filtro di E2, dove «Non ancora copiati» comprende i non riusciti. Dopo una copia riuscita le righe «Non riuscito» delle altre forme dello stesso file si tolgono (`ClearFailedAsync`): non hanno file | Con l'identità completa un cambio di formato ricopierebbe ogni file accanto a quello vecchio; la regola sola evita che piano, filtro e copiatore dicano cose diverse |
|
||||
| 2026-11-28 | Tappa E3: **richiesta ed esito**. `export_item` tiene ciò che si è chiesto (`Converted` + `Jpg`, `Frame` + `Png` + istante chiesto), `export_copy` ciò che è uscito (un HEIC chiesto in JPG è una copia `Whole`/`Original` con la nota). `UpdateItemsAsync` non cambia mai variante, formato e istante di un file. Le scelte di un lavoro di fotogrammi e il «Copia di nuovo» esatto stanno in `setting` (`esportazione.lavoro.{id}.fotogrammi` = `Istante`, `Ogni` o `Numero:N`; `esportazione.lavoro.{id}.esatta`), tolte prima di scrivere quelle di un lavoro nuovo con lo stesso numero. Nessuna migrazione `0005` | Il commento della `0003` su `export_item`; la ripresa di un lavoro deve rifare la stessa richiesta |
|
||||
| 2026-11-28 | Tappa E3: **il formato di una copia** si sceglie così: la scelta della singola «Copia in…», poi quella della destinazione (le colonne `photo_format`/`video_format` di `export_destination` già nella `0003`, `null` = «Come le impostazioni generali»), poi `esportazione.formato-foto`/`-video`. Cambiare il formato di una destinazione non la ritira (lo fa solo la cartella). Sul filo i formati restano quelli di E2 (`original`, `jpg`, `png`, `webplossless`, `mp4`); `PUT /api/export/settings` è parziale e risponde `{ message, overview, queued }`, così il JavaScript che legge `message` continua a funzionare | SPECIFICA §4.10, «per le copie»: valori predefiniti che destinazione e «Copia in…» possono cambiare |
|
||||
| 2026-11-28 | Tappa E3: **quando una foto si converte** (`ImageConverter.Check`): il formato si riconosce dai byte (`ImageFormatSniffer`), non dall'estensione; stesso formato → copia byte per byte (anche un WEBP con perdita verso «WEBP senza perdita», proposta, §16 domanda 36); HEIF/AVIF, TIFF e raw, ciò che non si identifica, le immagini animate (presenza di `acTL`, di `ANIM`/`ANMF`, GIF con più di un fotogramma), CMYK/YCCK e più di 8 bit verso PNG e WEBP, oltre 40 megapixel per WEBP o 100 per PNG e JPG, un lato WEBP oltre 16.384, un file oltre 512 MiB → copiato com'è con il suo codice (`AsIs…`; proposte, §16 domande 31 e 38). JPG a qualità 92, 4:4:4, trasparenza su bianco (`TransparencyWhite`). I metadati si ripuliscono **prima** dei codificatori: ciò che il formato non tiene (EXIF oltre 65.533 byte in JPG, EXIF senza intestazione TIFF, ICC non RGB o in più di 255 pezzi, IPTC, altri blocchi, testi, commento troppo lungo, XMP esteso) diventa un codice `Lost…`, mai un'eccezione; i codificatori tengono i loro controlli per chi li chiama direttamente | La memoria di un server di casa (il WEBP senza perdita vuole circa 24-28 byte per pixel: 40 megapixel sono circa 1,1 GB) e la regola «ciò che non si tiene lo dice il resoconto» |
|
||||
| 2026-11-28 | Tappa E3: **stesse conversioni, stessi byte** (D9 del progetto della tappa), con la stessa versione di Febe **sullo stesso runtime di .NET**: JPEG (DCT in virgola mobile con `MathF.Round`, senza SIMD) è deterministico; in `Vp8LWriter` le stime dei costi non usano più `Math.Log2` ma un logaritmo in base 2 a virgola fissa (Q16, tabella per i valori piccoli e quadrati esatti oltre), così le scelte del codificatore WEBP non dipendono dalla libreria C (UCRT o glibc). **Limite noto:** PNG comprime con `ZLibStream` della BCL a `CompressionLevel.Optimal`, i cui byte possono cambiare con un aggiornamento di servizio di .NET; allora l'adozione per percorso di un PNG convertito prima non riconosce il file e scrive su un nome libero un secondo file uguale nei pixel. Nessun numero di versione delle conversioni è registrato: un codificatore che cambia uscita ha lo stesso effetto. Un deflate scritto in casa non è nella tappa E3; un PNG non compresso è stato scartato (file molte volte più grandi) | SPECIFICA §4.10, adozione: «i suoi codificatori sono fissi». Il danno del limite è al più un file in più, mai una sovrascrittura |
|
||||
| 2026-11-28 | Tappa E3: **rimuxaggio** (`Mp4Remuxer`): ISO BMFF (`qt `, `M4V `, `3gp*`, ogni estensione non `.mp4`) e Matroska/WebM, con una traccia H.264 o HEVC (`avc1`/`avc3`/`hvc1`/`hev1` come nell'origine) e al più una AAC o MP3; un file ISO con un marchio diverso da `qt ` e l'estensione `.mp4` è già MP4 e si copia. L'elenco di modifiche dell'origine si riporta: il tratto vuoto iniziale (un inizio ritardato) e il tempo del primo tratto (il priming dell'AAC resta nascosto); più di un tratto non vuoto → rifiutato (`EditList`). MP3 nell'MP4 con l'OTI 0x6B (letto dall'`esds`, prima si scambiava per AAC), anche dentro `wave` di `mp4a`; per gli ID Matroska vecchi `A_AAC/MPEG4/…` la configurazione AAC si ricava da frequenza e canali; tracce Matroska con `ContentEncodings` rifiutate. Tracce in più tolte (`LostTracks:n`), `udta`/`meta`/tag non riportati (`LostVideoMetadata`); si tengono rotazione, lingua (`mdhd`, prima sempre «und») e date. Il lettore lavora con un «adesso» fisso (`ContainerReader.AnyDate`), così l'uscita non dipende dall'orologio; `Mp4Writer.Prepare` dà la lunghezza esatta prima di scrivere, e `Write` di prima dà gli stessi byte. In memoria solo le tabelle e il `moov`: i campioni si leggono e si scrivono uno per volta | SPECIFICA §4.10: «solo rimuxaggio, mai ricodifica»; un video non rimuxabile si copia com'è con il motivo |
|
||||
| 2026-11-28 | Tappa E3: **fotogrammi** (`VideoFrameReader`). Gli istanti sono tempi di presentazione come li mostra il lettore: i PTS del lettore ISO comprendono già `ctts` e tolgono il primo tratto non vuoto, e vi si aggiunge il tratto vuoto iniziale. «Questo istante» = il campione con il tempo mostrato più grande che non supera l'istante (il primo prima dell'inizio, l'ultimo oltre la fine). La decodifica è esatta: parte da un IDR, da un CRA/BLA di HEVC o da un I di H.264 con un punto di ripresa (`recovery_frame_cnt` 0), altrimenti dal campione 0; i fotogrammi escono nell'ordine di decodifica e i nomi vengono da `Locate`. L'identità di un fotogramma copiato è l'istante del campione mostrato in millisecondi **arrotondato in su** (`frame_at_ms`): richiesto di nuovo a quell'istante trova lo stesso campione (sotto i 1.000 fotogrammi al secondo due campioni non distano meno di 1 ms); in un lavoro i doppioni si tolgono per campione, e il file del lavoro tiene l'istante chiesto. I pixel si ruotano come il video si vede (90 → EXIF 6, 180 → 3, 270 → 8) e **il fotogramma non ha metadati** (manca uno scrittore di EXIF; la data del file segue `libreria.data-file-pubblicazione`; proposta, §16 domanda 32). Oltre 8 bit si porta a 8 all'uscita. Suffissi `_t0m12s340` e `_f001` protetti dall'accorciamento a 240 caratteri (`FitPath(…, keepSuffix)`, il numero libero va dopo: `x_f001 (2).png`) | SPECIFICA §4.10, «Fotogrammi»; con l'arrotondamento in su basta una regola sola per ritrovare il fotogramma |
|
||||
| 2026-11-28 | Tappa E3: **fotogrammi nelle destinazioni**: un lavoro di copia con file `Frame`, creati di seguito per video nell'ordine degli istanti; il copiatore li prende a gruppi per video e formato (anche fra due pagine di 500), apre il video una volta, scrive un fotogramma alla volta e fra l'uno e l'altro guarda sessione, interruzione e cartella: una pausa lascia in attesa il resto. Un video senza durata nota si misura quando si registra il lavoro; uno illeggibile dà un istante 0 e poi «Fotogramma non disponibile per questo video» senza riga di copia. Prima di registrare qualunque cosa il lavoro si rifiuta oltre 1.000 fotogrammi per un video o 20.000 in tutto. Nel piano un fotogramma conta 0 byte; il segno della tessera è `FrameOnly` quando l'elemento non ha copie intere o convertite e ha almeno un fotogramma copiato (proposta, §16 domande 32 e 38) | SPECIFICA §4.10: un fotogramma non fa «Copiato»; un video si legge una volta sola, non mille |
|
||||
| 2026-11-28 | Tappa E3: **adozione e spazio con le conversioni**. Il file si converte **prima** dei controlli di dimensione (FAT32) e di spazio, che usano la lunghezza del convertito; il riepilogo dice «circa» con i byte degli originali. Adozione: la lunghezza, poi lo SHA-256 del file trovato contro quello della conversione; per un rimuxaggio lo SHA-256 si calcola scrivendo in un pozzo che conta e somma, solo se la lunghezza coincide. Una riga orfana di E2 si ricollega solo con lo stesso SHA-256 della copia, la stessa variante, lo stesso formato e lo stesso istante. Una foto si legge tutta in memoria e il suo SHA-256 si confronta prima di convertire; per video e fotogrammi l'origine si ricontrolla prima del cambio di nome (`SourceChanged`). Una foto oltre 512 MiB, copiata com'è, si copia in flusso | SPECIFICA §4.10, «Adozione per percorso», e lo spazio di §4.10 |
|
||||
| 2026-11-28 | Tappa E3: **le note sono un elenco di codici** separati da spazi (`Codice` o `Codice:argomento`, argomento senza spazi) in `export_item.note` e in `media_conversion.last_error`; `ExportText.Note` li traduce uno per uno e li unisce con « · », e un codice sconosciuto si mostra com'è. In una riga di `media_conversion` **«Convertito»** `last_error` dice ciò che non si è tenuto (codici `Lost…`); in una «Non riuscito» il perché (`SourceMissing`, `SourceChanged`, `AccountFolderMissing`, `Error:<Tipo>`, oppure `AsIs…`, che non si converte). Il resoconto tiene al più 200 file con una nota e conta per account i «come sono» per etichetta | Nessuna colonna nuova: `note` e `last_error` sono `TEXT` senza vincoli. Una copia può perdere più cose insieme |
|
||||
| 2026-11-28 | Tappa E3: **permesso di sottofondo** (`LongWorkGate.TryEnterBackground`, solo per `LongWorkKind.LibraryConversion`). Si prende solo se nessun lavoro lungo lo tiene; `Busy` non lo vede, così `EnsureIdle` delle copie e dell'importazione non rifiuta. `TryEnter` (sincrono, firma invariata) di un lavoro in primo piano lo toglie: sotto il lucchetto lo segna, fuori dal lucchetto annulla `Preempted` e, se il lavoro sta registrando un file (`TryBeginCommit`: un cambio di nome e una transazione, con `CancellationToken.None`), aspetta al più 10 secondi; oltre restituisce `false` con «La conversione della libreria sta salvando un file: riprova fra un attimo.». Fuori dalla registrazione il lavoro legge l'originale e scrive solo il suo `.part`, che la ricostruzione salta; quando vede la richiesta toglie il `.part` e lascia la riga «In coda». `FrameDownload` è un tipo nuovo con i suoi messaggi («scarica i fotogrammi») | SPECIFICA §4.10: la conversione cede il passo. Chi avvia copie e importazioni chiama `TryEnter` sotto i suoi lucchetti: una sospensione asincrona cambierebbe quei chiamanti, una registrazione dura millisecondi |
|
||||
| 2026-11-28 | Tappa E3: **lavoro della conversione della libreria** (`LibraryConversionWorker`): un ciclo avviato con `InBackground` in `FebeApp` (non un `BackgroundService`, che con un'eccezione fermerebbe l'ospite), mai nella dimostrazione. Si sveglia con `LibraryConversionQueue.Signal()` o ogni 30 secondi, aspetta fuori dalle sessioni (ogni 5 secondi), prende 50 righe per volta; in pausa con `esportazione.libreria-sospesa` = `1`. Per ogni riga: elemento sparito → riga tolta; cartella dell'account assente → «Non riuscito» (`AccountFolderMissing`), mai creata (`RequireExistingRoot`); originale mancante → `SourceMissing`; SHA-256 cambiato → la riga prende quello nuovo; un video si somma prima del rimuxaggio; stesso formato riconosciuto dai byte → riga tolta (il vincolo `sha256 <> source_sha256` non lascia registrarla); copiato com'è → «Non riuscito» con il codice `AsIs…`, definitivo («Riprova i non riusciti» lo salta); spazio sotto `DiskThresholds.Default` con il file da scrivere → pausa con il motivo. Scrittura con `SafeFileWriter` nella cartella dell'originale, stesso nome, estensione del formato, nome libero, rilettura dal disco; adozione di un file con lo stesso SHA-256 solo se nessun file presente e nessuna conversione viva dell'account registrano quel percorso. Se alla registrazione l'elemento non c'è più (o il posto è preso), Febe toglie il file **appena scritto da lei**, dopo averne riletto lo SHA-256, mai un file adottato. Ogni errore di un file finisce in `last_error` come `Error:<Tipo>`; il registro ha solo il nome del tipo | Regola 11: la conversione aggiunge e non toglie; un disco staccato non deve diventare una cartella locale; nel registro mai percorsi |
|
||||
| 2026-11-28 | Tappa E3: **righe della conversione sempre vere**. Un file nuovo entra in coda in `LibraryIngest.AppendJournalAsync`, dopo la sua riga di `_febe.jsonl` (scaricamento e importazione; nessun costruttore cambia). Spegnere o cambiare un formato toglie le righe «In coda» di quello di prima; i convertiti e le loro righe restano. Un originale cambiato (`ExportSupersession.FileChangedAsync`): le righe «Convertito» diventano «Superato» (il file resta), quelle «In coda» o «Non riuscito», **anche le `AsIs…`** (il verdetto era sui byte di prima), tornano «In coda» con lo SHA-256 nuovo. «Elimina dalla libreria» che ricorda la scelta segna «Tolto» i convertiti e toglie le righe senza file; «Eliminalo e lascia che torni» toglie le righe (`RemoveWithConversionsAsync`); poi il file convertito si cancella solo se il suo SHA-256 è ancora quello registrato e nessuna riga viva tiene quel percorso, altrimenti resta ed è detto. `EntryStore.RemoveAsync` resta severo: una riga «Convertito» o «Superato» lo fa fallire (`ON DELETE RESTRICT`) con un errore in italiano. Il file scartato da «Tieni il più grande» porta via i suoi convertiti in una transazione (`ForgetDeletedMediaAsync`). La ricostruzione non converte: salta i percorsi registrati, conta i convertiti accanto agli originali (`RebuildReport.ConversionsFound`) e, con la conversione accesa per quel formato, ne rimette la riga «In coda» (il lavoro poi la adotta per SHA-256); per gli elementi eliminati passa solo le conversioni il cui file manca e conta le altre (`ConversionsOfDeletedEntries`) | SPECIFICA §4.10: il convertito è legato al suo originale; regola 11 |
|
||||
| 2026-11-28 | Tappa E3: **l'importazione riconosce i convertiti** (proposta, §16 domanda 37): uno SHA-256 di una conversione della libreria o di una copia convertita o di un fotogramma (`export_copy.copy_sha256` delle righe `Converted`/`Frame`) è «già in libreria», con la nota «È una copia convertita (o un fotogramma) di un file già in libreria.», mai una coppia di doppioni. Le copie si leggono una volta per importazione in un insieme in memoria (`LoadConvertedCopyShasAsync`), perché `copy_sha256` non ha un indice e la tappa non aggiunge migrazioni | Una copia convertita somiglia all'originale per impronta: senza la regola l'importazione di una destinazione proporrebbe centinaia di doppioni |
|
||||
| 2026-11-28 | Tappa E3: **risorse delle conversioni**. Ogni conversione di una foto (copiatore, lavoro della libreria e fotogrammi delle destinazioni) passa da un solo `ConversionThrottle` del processo (`SemaphoreSlim(1)`) e gira con `Task.Run`; un video si legge a pezzi; un fotogramma è un'immagine RGBA alla volta. I file della libreria si aprono anche con `FileShare.Delete`, così una lettura lunga non blocca «Elimina dalla libreria» su Windows | Un server di casa con poca memoria; due conversioni di foto grandi insieme raddoppierebbero il picco |
|
||||
| 2026-11-28 | Tappa E3: **fotogrammi dall'interfaccia** (`FrameService`). Anteprime e fotogrammi singoli uno alla volta, entro 30 secondi (oltre, 503 «Il fotogramma richiede troppo tempo: scegli la cartella delle copie»), con le informazioni dei video in memoria per SHA-256 (le ultime 64); anteprima JPG di al più 480 pixel, scaricamento in PNG di serie con il nome del fotogramma. «Scarica» passa da un gettone in memoria (5 minuti, un uso solo): 1 fotogramma → l'immagine, da 2 a 500 → uno zip `febe-fotogrammi-AAAA-MM-GG.zip`, non compresso, con voci `<account>/<nome>` rese uniche come i nomi liberi e la data delle voci secondo `libreria.data-file-pubblicazione` tenuta fra il 1980 e il 2107 (i limiti dello zip). Oltre 20 fotogrammi lo zip vuole il permesso `FrameDownload` (409 altrimenti) e niente sessione del motore, lascia il permesso anche se il browser chiude, e si interrompe dopo 60 secondi senza che una scrittura vada avanti. Oltre 500 → «Per più di 500 fotogrammi scegli la cartella delle copie» (proposta, §16 domanda 34). Gli errori con un codice (409, 503) passano da `ApiStatusException` | Un browser lento non deve tenere il permesso dei lavori lunghi per sempre; uno zip grande non deve fermare il motore |
|
||||
| 2026-11-28 | Tappa E3, interfaccia: un dialogo aperto dal visualizzatore resta sopra di lui (velo dei dialoghi da `z-index` 40 a 55, il visualizzatore è a 50, i menu a 60); il segno «Solo fotogrammi» è disegnato in CSS, senza un file d'icona; «Fotogrammi…» dalla selezione ha solo il campo dell'istante, senza anteprime (non c'è un video solo); il riquadro «Conversione della libreria» della Dashboard compare solo quando la conversione è accesa o ha righe; la domanda «Convertire anche i N file già in libreria?» si fa a ogni cambio verso un formato che non è «Originale», se l'anteprima trova file da convertire. La dimostrazione non avvia mai la conversione: semina una copia PNG fatta dal motore vero, un fotogramma a 1,234 s (il campione mostrato è a 1,125 s) e due righe `media_conversion` («Convertito» in PNG con il suo file e «Non riuscito» `AsIsAnimated`) | Un dialogo sotto il visualizzatore non si vedeva; un riquadro sempre presente per una funzione spenta sarebbe rumore |
|
||||
| 2026-11-28 | Revisione della tappa E3, immagini: il controllo prima della conversione stima anche la memoria di lavoro del decodificatore JPEG (`ImageInfo.DecodeWorkingBytes`: un progressivo tiene i coefficienti), così un JPEG che il decodificatore rifiuterebbe esce «troppo grande» (`AsIsTooLarge`) e non «illeggibile»; un'eccezione di limite durante la conversione della libreria fa lo stesso. Un EXIF che non si tiene (illeggibile o troppo grande per il JPG) lascia comunque un EXIF minimo con il solo orientamento (`ExifOrientation.Minimal`, nell'ordine dei byte della fonte) | Il verdetto deve dire il vero motivo; senza orientamento la foto uscirebbe girata |
|
||||
| 2026-11-28 | Revisione della tappa E3, fotogrammi: gli istanti di «Uno ogni k secondi» e «N in tutto» sono in millisecondi interi (`ExportFrames.WholeMs`) prima di contare i doppioni; la copia ricalcola gli istanti dalla durata (misurata se il database non la sa) e trova l'indice del nome per istante (`ExportFrames.IndexOf`), con il conteggio delle righe solo come riserva. I video di durata sconosciuta si misurano nel pianificatore (`lengthOf`, una volta per video e per richiesta) prima che si registri qualcosa, così contano nei limiti di 500 per richiesta e 5000 per video; un video che non si misura dà il solo fotogramma a 0 | Nomi e conteggi non devono dipendere dall'ordine delle righe né scoprire il troppo dopo averlo scritto |
|
||||
| 2026-11-28 | Revisione della tappa E3, video: il rimuxaggio porta in MP4 la durata del segmento di `elst` (`MediaTrack.EditSegmentDuration`) e la scrive quando taglia la fine; i fotogrammi non cadono oltre la fine mostrata. Il punto di recupero H.264 vale come IDR solo con `exact_match_flag` = 1. MP3 in MP4: `objectTypeIndication` 0x69 (MPEG-2, fino a 24 kHz) o 0x6B (MPEG-1) secondo la frequenza | Un AAC con la fine tagliata è comune; un recovery point inesatto dà fotogrammi sporchi; 0x6B con 22,05 kHz è un'etichetta falsa (ISO/IEC 14496-1, tabella 5) |
|
||||
| 2026-11-28 | Revisione della tappa E3, conversione della libreria: il lavoro ricontrolla il formato della riga con le impostazioni di adesso e toglie quella di un formato spento o cambiato; spegnere o cambiare un formato toglie anche i suoi «Non riuscito» (non `AsIs…`, `DeleteQueueAsync`); «Riprova» rimette solo i formati di adesso. Prima di rileggere l'originale il lavoro guarda lo spazio libero e si mette in pausa se è già sotto la soglia. «Anche i N» conta e mette in coda solo il tipo che si sta cambiando (`?photo=`/`?video=`, e nel PUT i tipi il cui formato cambia), mai l'altro che aveva già avuto «Solo i nuovi». Il PUT delle impostazioni dell'esportazione passa da un cancello (uno per volta): due clic veloci non partono dallo stesso «prima» | Una riga di un formato spento non deve scrivere file; rileggere un originale grande con il disco pieno è lavoro buttato; due cambi insieme perdevano l'uno o l'altro |
|
||||
| 2026-11-28 | Revisione della tappa E3: «file nuovo» per «Solo i nuovi» vuol dire salvato in libreria (`media.downloaded_at`) da quando il formato di quel tipo è quello di adesso (`esportazione.libreria-formato-foto-dal` / `-video-dal`, in millisecondi, scritti da `OnSettingsChangedAsync`; senza la chiave ogni file è nuovo). Un file arrivato tardi in un elemento vecchio mette in coda sé, non i fratelli | Come per «Automatica» (`automatic_since` contro `media.downloaded_at`); passare gli id dai chiamanti non reggeva alle righe del giornale rimandate |
|
||||
| 2026-11-28 | Revisione della tappa E3: «Elimina dalla libreria» (con memoria) e «Tieni il più grande» scelgono le righe dei convertiti nella stessa transazione che elimina (`MarkDeletedWithConversionsAsync`, `ForgetDeletedMediaAsync` che segna anche il file «Eliminato»), così un convertito registrato dal lavoro un attimo prima se ne va con il suo originale. Lo zip dei fotogrammi si scrive a pezzi di 64 KB, ognuno con i suoi 60 secondi: un browser lento che legge non si interrompe, uno fermo sì | Un convertito orfano resterebbe sul disco con la riga «Convertito»; un fotogramma grande su una linea lenta superava i 60 secondi in una scrittura sola |
|
||||
| 2026-11-28 | Seconda revisione della tappa E3, video: `Mp4Writer` misura la fine della presentazione in tempo di composizione (il massimo di decodifica + scarto di composizione + durata di ogni campione), non la somma delle durate di decodifica. Con i fotogrammi B l'edit comincia al primo scarto di composizione e con la somma l'MP4 nascondeva gli ultimi fotogrammi mostrati (2 in un iPhone), e durava altrettanto meno in `mvhd`, `tkhd` ed `elst`; il segmento della sorgente resta il limite. Vale per ogni scrittura, non solo per le sorgenti con un segmento: per una traccia senza scarti la fine è la stessa di prima e i byte non cambiano, con gli scarti il risultato di prima era sbagliato anche senza segmento (Matroska, ISO senza `elst`). | Una MOV con fotogrammi B rimuxata in MP4 (conversione della libreria o copia) deve mostrare quello che mostrava la sorgente; i fotogrammi presi dal convertito ora leggono il segmento giusto. |
|
||||
| 2026-11-28 | Seconda revisione della tappa E3, conversione della libreria: il lavoro ricorda il file che l'ha messo in pausa per spazio e quanto serve al suo convertito (riga, SHA-256 dell'originale, byte), e finché il disco non ha posto anche per quello la pausa vale prima di rileggere l'originale (hash, decodifica, rimuxaggio). Non si sottraggono i byte dell'originale in anticipo: un PNG grande che diventa un JPG piccolo resterebbe fermo senza motivo. Il ricordo è del processo: dopo un riavvio l'originale si rilegge una volta. | La pausa per spazio (D17) non deve rileggere lo stesso video di 2 GB a ogni risveglio quando lo spazio libero sta fra la soglia e la soglia più il file. |
|
||||
| 2026-11-28 | Seconda revisione della tappa E3: un cambio dei formati della libreria si salva in una transazione sola con le chiavi «dal» e la coda svuotata del formato sostituito (`LibraryConversionQueue.SaveSettingsAsync`, `IMediaConversionStore.SaveSettingsAndDeleteQueuesAsync`); «Anche i N» dopo il salvataggio non dipende più dalla richiesta (`CancellationToken.None`). Il gancio della libreria legge formati e chiavi «dal» con una lettura sola. | Una scheda chiusa, un arresto o un file salvato in quel momento non devono vedere il formato nuovo senza la sua chiave «dal» (che metterebbe in coda tutto l'elemento) né lasciare «Non riuscito» del formato vecchio che «Riprova» non tocca più. |
|
||||
| 2026-11-28 | Seconda revisione della tappa E3, fotogrammi: i tempi di `WriteStall` dello zip passano da un `TimeProvider` della BCL (`FrameService.StallTime`, di serie quello di sistema); la prova del lettore lento usa un `TimeProvider` scritto nella prova che avanza solo quando il collegamento finto manda un pezzo. | La prova dipendeva da orologi veri con 250 ms di margine e poteva cadere su un esecutore carico della CI; ora non dipende dal carico. Nessun pacchetto esterno. |
|
||||
| 2026-11-29 | **Confermate le risposte proposte delle domande 19–38 di §16**, che le tappe D1, S4b, E2 ed E3 avevano già adottato: D1 (19 e 21) le raccolte in evidenza subito dopo le storie nell'ordine predefinito e il posto su otto della coda al file che aspetta da più tempo, senza quote per tipo; S4b (20) i 5 secondi di grazia prima che lasciare la pagina del browser in Docker copi la sessione; E2 (22–27) «Esporta questo account» spento salta anche le copie a mano, `/esporta` attiva su un montaggio in `/esporta` o sotto, «Automatica» nascosta fino a E5, «Copia di nuovo anche i N tolti o superati» spenta all'apertura, conteggi e segni sui soli file dovuti, margine di 64 MB; E3 (28–38) «già copiato» guarda il file e non il formato, «Solo i nuovi» per la conversione della libreria, i convertiti nel visualizzatore, CMYK e più di 8 bit copiati come sono verso PNG/WEBP, nomi, istanti e limiti dei fotogrammi, zip, PNG per i fotogrammi, WEBP con perdita copiato byte per byte, i convertiti riconosciuti «già in libreria» all'importazione. La riga di ogni domanda dice la risposta (§16) e i paragrafi che le citavano come proposte ora la citano come risposta | Risposta di Alberto del 29 novembre 2026: «Le confermo tutte». Nulla cambia nel codice: le tappe facevano già così |
|
||||
| 2026-11-29 | Commenti in inglese anche negli script di shell di `.gitea/scripts/` e `installer/`, nei blocchi `run:` dei flussi di `.gitea/workflows/` e in `docker/entrypoint.sh`; restano in italiano i messaggi che una persona legge (`echo`, `::warning::`/`::error::`, nomi dei passi, note della release, istruzioni d'uso), come nel resto del codice. Decisione di Alberto (#43) | La regola «codice e commenti in inglese; interfaccia, documenti e messaggi in italiano» vale per tutto il repository, script compresi: nessuna eccezione per la CI |
|
||||
| 2026-11-29 | **Subito dopo «Scollega», con l'indirizzo della pagina sconosciuto** (il browser non risponde ancora, `FullUrlAsync` dà `null`), Febe aspetta che il browser risponda, entro un limite; se ancora non risponde apre la pagina di accesso (#67). È la sola decisione: da fare, il codice oggi non aspetta (`OpenForAlbertoAsync` scrive «Alberto usa il browser» e non apre nulla; `docs/stato.md`, «Rimandato») | Decisione di Alberto del 29 novembre 2026: senza sapere quale pagina mostra il browser non si può dire se è già quella di accesso; aspettare un poco evita di ricaricare una pagina che sta arrivando, e il limite evita di restare fermi |
|
||||
@@ -54,6 +54,9 @@ Che cosa fa:
|
||||
disco, e rispetta le eliminazioni (un elemento eliminato «ricordando la scelta» resta eliminato);
|
||||
- **non riscarica nulla** e **non sposta, non rinomina e non cancella nessun file**;
|
||||
- gli elementi già presenti nel database restano come sono: si può lanciare anche su un database esistente;
|
||||
- non converte nulla: i file della conversione della libreria accanto ai loro originali (`foto.png` accanto a
|
||||
`foto.jpg`) si riconoscono e non contano fra i file sconosciuti; se la conversione è accesa per quel formato, il file
|
||||
torna nell'elenco dei convertiti dopo la ricostruzione;
|
||||
- mostra l'avanzamento (cartelle e file controllati) e alla fine un resoconto.
|
||||
|
||||
Che cosa non torna:
|
||||
|
||||
@@ -2,11 +2,12 @@
|
||||
|
||||
Le **copie esterne** sono copie dei file della libreria in cartelle fuori da Febe: un disco USB, una chiavetta, una
|
||||
cartella di rete, un'altra cartella del server. La libreria non cambia: Febe legge i suoi file e li copia così come
|
||||
sono, byte per byte. Non riscarica nulla e non apre Instagram: è solo lavoro sul disco.
|
||||
sono, byte per byte, oppure convertiti in un altro formato (vedi «Formati»), oppure ne prende dei fotogrammi (vedi
|
||||
«Fotogrammi»). Non riscarica nulla e non apre Instagram: è solo lavoro sul disco.
|
||||
|
||||
In questa versione (tappa E2) si copiano gli **originali**. Le copie in un altro formato e i fotogrammi dei video
|
||||
arrivano con la tappa E3, l'analisi dei video fermi con la E4, le copie automatiche con la E5: fino ad allora quei
|
||||
comandi non ci sono.
|
||||
In questa versione (tappa E3) ci sono le copie degli originali, i formati delle copie, la conversione della libreria e
|
||||
i fotogrammi dei video. L'analisi dei video fermi arriva con la tappa E4 e le copie automatiche con la E5: fino ad
|
||||
allora quei comandi («È un video fermo?», «Automatica») non ci sono.
|
||||
|
||||
> **Le copie esterne escono dal controllo di Febe.** Chi ha la cartella di una copia, o il disco su cui sta, ha quei
|
||||
> file, comprese le foto e i video di altre persone. Febe non le cifra, non le cancella e, dopo averle scritte, ne sa
|
||||
@@ -78,13 +79,54 @@ quando quell'account ne ha una).
|
||||
La finestra conta prima di copiare: quanti file, quanti già copiati (saltati), quanti tolti o superati (saltati), quanti
|
||||
di account che non si esportano, quanti non presenti in libreria, circa quanto spazio, e lo spazio libero di ogni
|
||||
cartella. **«Copia di nuovo anche i N tolti o superati»** è spenta: accendila se vuoi riscriverli (vedi «Stati»).
|
||||
«Copia N file» fa partire il lavoro e la finestra si chiude: le copie vanno avanti da sole e si seguono nella Dashboard.
|
||||
La riga **«Formato: come la destinazione · Cambia»** dice in che formato arrivano i file; «Cambia» lo sceglie solo per
|
||||
questa copia (vedi «Formati»), e il riepilogo dice allora anche quanti file si copiano come sono («circa 3 HEIC copiati
|
||||
come sono») e «con perdita» se qualche file diventa JPG. «Copia N file» fa partire il lavoro e la finestra si chiude:
|
||||
le copie vanno avanti da sole e si seguono nella Dashboard.
|
||||
|
||||
Si copiano solo i **file dovuti**: i file presenti in libreria di un account che si esporta e ha una cartella delle
|
||||
copie, del tipo che quella cartella copia. Il segno sulle tessere, il filtro «Copie», il conteggio della scheda
|
||||
dell'account e «Copia in…» contano tutti e soli questi file, così «312 su 1.204 non ancora copiati» è proprio ciò che
|
||||
«Copia in…» copierebbe.
|
||||
|
||||
## Formati
|
||||
|
||||
Di solito le copie sono gli **originali**, byte per byte. Puoi chiedere invece che arrivino in un altro formato:
|
||||
|
||||
| | Scelte |
|
||||
|---|---|
|
||||
| Foto | **Originale** (di solito), JPG, PNG, WEBP senza perdita |
|
||||
| Video | **Originale** (di solito), MP4 |
|
||||
|
||||
Il formato si sceglie in tre posti, e vale il più vicino alla copia: **«Cambia»** nella finestra «Copia in…» (solo per
|
||||
quella copia), la parte **«Formati»** della finestra di una cartella («Come le impostazioni generali», di solito),
|
||||
**Impostazioni ▸ Esportazione ▸ «Formati delle copie»**.
|
||||
|
||||
- **Con perdita solo se lo scegli.** JPG è l'unico formato con perdita: Febe lo scrive a **qualità 92**, e la finestra lo
|
||||
dice («con perdita: qualità 92», «con perdita» nel riepilogo). La trasparenza in JPG diventa bianco. PNG e WEBP senza
|
||||
perdita tengono tutti i pixel.
|
||||
- **Video in MP4: solo rimuxaggio, mai ricodifica.** Febe porta in MP4 un MOV, un M4V, un 3GP o un MKV/WebM con video
|
||||
H.264 o HEVC e audio AAC o MP3, copiando i fotogrammi così come sono: tengono qualità, rotazione, lingua delle tracce
|
||||
e date. Tracce in più (codice di tempo, sottotitoli, una seconda traccia audio) si tolgono, e la nota lo dice. Un
|
||||
video con un altro codec (VP9, AV1, Opus…) si copia com'è.
|
||||
- **Un file già in quel formato si copia byte per byte**, mai ricodificato. Febe lo riconosce dal contenuto, non dal
|
||||
nome: un `.jpg` che in realtà è un PNG si converte. Un WEBP con perdita resta com'è anche con «WEBP senza perdita».
|
||||
- **Si copiano come sono, con una nota:** HEIC, AVIF, raw (`.dng`, `.cr2`, `.nef`…), le immagini animate (GIF, WEBP e
|
||||
PNG animati: convertite perderebbero i fotogrammi dopo il primo), ciò che Febe non riesce a leggere, le immagini CMYK
|
||||
o con più di 8 bit per colore verso PNG e WEBP, le immagini troppo grandi per il formato (oltre 40 megapixel per WEBP,
|
||||
oltre 100 per JPG e PNG, oltre 512 MB), i video che non si portano in MP4 senza ricodificarli.
|
||||
- **I metadati vengono con il file:** EXIF (l'orientamento resta un dato, i pixel non si ruotano), profilo ICC, XMP; per
|
||||
i video date, rotazione e lingua. Ciò che il formato non può tenere (un EXIF troppo grande per JPG, un profilo ICC non
|
||||
RGB…) lo dicono le note («Non tenuto: profilo ICC»).
|
||||
- **Un formato nuovo vale per i file non ancora copiati.** Un file già copiato in un'altra forma resta «Copiato» e si
|
||||
salta («Già copiato in un altro formato»). Se lo vuoi anche nel formato nuovo: togli il file vecchio dalla cartella,
|
||||
«Controlla le copie» lo segna «Tolto», poi «Copia di nuovo».
|
||||
- Il riepilogo prevede le note dal nome dei file e dice lo spazio degli originali, «circa»: un convertito può occupare
|
||||
di più. Lo spazio della cartella Febe lo controlla sul file convertito, prima di scriverlo.
|
||||
|
||||
Le note di ogni file stanno nel **resoconto** del lavoro (Dashboard ▸ Esportazione ▸ «Resoconto», colonne «Come sono» e
|
||||
«Note») e nelle righe del visualizzatore.
|
||||
|
||||
## Come Febe scrive una copia
|
||||
|
||||
- Prima di ogni gruppo di copie (al più 100 file o 1 GB) Febe scrive e toglie un file di prova nella cartella. Se non
|
||||
@@ -97,7 +139,8 @@ dell'account e «Copia in…» contano tutti e soli questi file, così «312 su
|
||||
della libreria, poi prende il nome definitivo. **Febe non sovrascrive mai un file**: se il nome è occupato da un altro
|
||||
file, scrive `nome (2).jpg` e lascia l'altro com'è. Non cancella e non sposta nulla nelle cartelle delle copie; i
|
||||
`.part` rimasti da una copia interrotta li toglie solo nelle cartelle di quel lavoro, mai frugando nel resto.
|
||||
- La data del file segue l'impostazione della libreria «Imposta la data del file a quella di pubblicazione».
|
||||
- La data del file segue l'impostazione della libreria «Imposta la data del file a quella di pubblicazione», anche
|
||||
per i file convertiti e i fotogrammi.
|
||||
- Non si copia durante una sessione del motore: la copia aspetta che la sessione finisca («Aspetto la fine della
|
||||
sessione del motore»). Copie, importazione e ricostruzione del database non girano insieme: mentre una lavora, le
|
||||
altre due aspettano che finisca o che la interrompi.
|
||||
@@ -106,28 +149,31 @@ dell'account e «Copia in…» contano tutti e soli questi file, così «312 su
|
||||
|
||||
Se nel posto dove andrebbe la copia c'è già un file **identico** (stesso SHA-256 dell'originale), Febe lo adotta come
|
||||
copia invece di scriverne un secondo: succede dopo un database perso o ricostruito, con un backup vecchio della
|
||||
cartella, con due Febe sulla stessa cartella. La sola dimensione non basta mai: un file diverso con la stessa
|
||||
dimensione resta com'è, e la copia va su un nome libero.
|
||||
cartella, con due Febe sulla stessa cartella. Per un file convertito o un fotogramma Febe rifà la conversione e vuole
|
||||
lo stesso SHA-256 del file che trova. La sola dimensione non basta mai: un file diverso con la stessa dimensione resta
|
||||
com'è, e la copia va su un nome libero.
|
||||
|
||||
## Stati di una copia
|
||||
|
||||
| Stato | Che cosa vuol dire |
|
||||
|---|---|
|
||||
| **Copiato** | Il file è nella cartella, uguale all'originale |
|
||||
| **Copiato** | Il file è nella cartella, uguale all'originale o convertito nel formato chiesto |
|
||||
| **Tolto** | Il file non c'è più nella cartella (l'hai spostato o cancellato tu, o il disco è un altro). Lo trova «Controlla le copie» in Impostazioni ▸ Esportazione, che guarda soltanto e non tocca nessun file. Con il disco staccato non segna nulla come tolto: mette la cartella in pausa |
|
||||
| **Superato** | Il file della libreria è cambiato dopo la copia: «Tieni il più grande» fra due doppioni, un'importazione che sostituisce, una ricostruzione che trova un altro file. La copia vecchia resta |
|
||||
| **Non riuscito** | La copia non si è potuta fare (per esempio il limite di FAT32): la prossima «Copia in…» ci riprova |
|
||||
|
||||
**Tolto e Superato non si ricopiano mai da soli.** «Copia di nuovo», nel pannello File del visualizzatore accanto alla
|
||||
riga della copia, oppure la casella «Copia di nuovo anche i N tolti o superati» di «Copia in…», scrive un file nuovo, e
|
||||
la copia vecchia resta dov'è. Eliminare un elemento dalla libreria non tocca le sue copie.
|
||||
la copia vecchia resta dov'è. Dal visualizzatore rifà proprio quella copia, nella sua forma (intero, PNG, il fotogramma
|
||||
a quell'istante…); la casella di «Copia in…» usa i formati di adesso. Eliminare un elemento dalla libreria non tocca le
|
||||
sue copie.
|
||||
|
||||
Dove si vede:
|
||||
|
||||
- un piccolo **segno sulla tessera** (solo se c'è almeno una cartella delle copie), con «2/3» per un post copiato in
|
||||
parte;
|
||||
- le righe del **pannello File** del visualizzatore: «Copiato in Disco USB il 3 novembre · intero», «Tolto da…»,
|
||||
«Superato in…», con «Copia di nuovo»;
|
||||
parte e un piccolo riquadro, **«Solo fotogrammi»**, per un elemento di cui sono stati copiati solo dei fotogrammi;
|
||||
- le righe del **pannello File** del visualizzatore: «Copiato in Disco USB il 3 novembre · intero», «… · PNG»,
|
||||
«… · fotogramma a 0:01,125 · PNG», «Tolto da…», «Superato in…», con «Copia di nuovo» e, sotto, le note;
|
||||
- il conteggio nella **scheda dell'account** («312 su 1.204 non ancora copiati», i tolti o superati, i non riusciti);
|
||||
- il filtro **«Copie»** in Libreria e nella scheda dell'account: Tutti, Non ancora copiati, Copiati, Tolti o superati.
|
||||
Resta nell'indirizzo della pagina (`?copie=non-copiati`).
|
||||
@@ -141,6 +187,79 @@ Quando lo stesso file è il post di un account e il taggato di un altro, Imposta
|
||||
- **«Una copia sola»**: si copia una volta, nel primo account che lo copia; l'altro lo mostra «Copiato» con la cartella
|
||||
dove sta.
|
||||
|
||||
## Fotogrammi
|
||||
|
||||
Un **fotogramma** è un'immagine presa da un video, a piena risoluzione e girata come il video si vede. Si chiede:
|
||||
|
||||
- dal **visualizzatore**, con **«Fotogramma»** sotto un video: il video si ferma e la finestra si apre all'istante in
|
||||
cui era, con l'anteprima e il cursore per spostarsi;
|
||||
- dalla **selezione**, in Libreria e nella scheda di un account: «Seleziona», scegli le tessere, **«Fotogrammi…»** nella
|
||||
barra in basso. Lo stesso istante (o la stessa regola) vale per ogni video scelto; **le foto si saltano**, e la
|
||||
finestra lo dice.
|
||||
|
||||
Quali fotogrammi:
|
||||
|
||||
- **Questo istante**: il fotogramma che il video mostra in quel momento (scrivi l'istante come `0:12` o `0:12,5`); oltre
|
||||
la fine, l'ultimo;
|
||||
- **Uno ogni k secondi**: da 0:00, poi ogni k secondi fino alla fine (k almeno 0,1 secondi);
|
||||
- **N in tutto**: il video diviso in N parti uguali, un fotogramma al centro di ognuna (da 1 a 1.000).
|
||||
|
||||
Dal visualizzatore la finestra mostra le anteprime dei primi sei («e altri N»). Formato: **PNG** (di solito, nessuna
|
||||
perdita), JPG (con perdita) o WEBP senza perdita. **Il fotogramma non ha l'audio**, e la finestra lo ricorda; non ha
|
||||
nemmeno i metadati del video. Un video in un codec che Febe non decodifica (VP9, AV1…) o rovinato dice **«Fotogramma
|
||||
non disponibile per questo video»**.
|
||||
|
||||
Dove vanno:
|
||||
|
||||
- **«Scarica»**: un fotogramma si scarica com'è; più fotogrammi in uno **zip** (`febe-fotogrammi-AAAA-MM-GG.zip`, una
|
||||
cartella per account). Fino a 20 fotogrammi lo zip si fa in qualunque momento; da 21 a 500 solo fuori dalle sessioni
|
||||
del motore e quando non lavorano importazione, copie o ricostruzione; per più di 500 scegli la cartella delle copie.
|
||||
«Scarica» non guarda le cartelle delle copie né «Esporta questo account».
|
||||
- **«Nella cartella delle copie»**: un lavoro di copia, come «Copia in…», nella cartella di ogni account, accanto alle
|
||||
copie, con gli stessi file dovuti (gli account che non si esportano si saltano e si contano). Si segue nella
|
||||
Dashboard.
|
||||
|
||||
I nomi sono quelli del video con l'istante: `video_t0m12s340.png` (0 minuti, 12 secondi e 340 millesimi: l'istante del
|
||||
fotogramma davvero mostrato) per «Questo istante» e «Uno ogni k secondi», `video_f001.png`, `video_f002.png`… per «N in
|
||||
tutto». Al più 1.000 fotogrammi per video («Più di 1.000 fotogrammi per un video: scegli un intervallo più lungo») e
|
||||
20.000 per volta.
|
||||
|
||||
**Un fotogramma non fa «copiato» il video:** il video resta «Non ancora copiato» finché non ne copi il file intero, e
|
||||
un elemento con soli fotogrammi ha il segno «Solo fotogrammi». Lo stesso fotogramma chiesto di nuovo nella stessa
|
||||
cartella è «già copiato»; un fotogramma «Tolto» si riscrive quando lo chiedi di nuovo.
|
||||
|
||||
## Conversione della libreria
|
||||
|
||||
Oltre alle copie, Febe può tenere **nella libreria** un file convertito accanto a ogni foto o video: Impostazioni ▸
|
||||
Esportazione ▸ **«Conversione della libreria»**, Foto (JPG, PNG, WEBP senza perdita) e Video (MP4). Di solito è spenta
|
||||
(«Originale»).
|
||||
|
||||
- **Il file convertito si aggiunge: l'originale resta**, con il suo nome. Il convertito va nella stessa cartella, con lo
|
||||
stesso nome e l'estensione nuova (`foto.png` accanto a `foto.jpg`; `foto (2).png` se il nome è già preso: mai una
|
||||
sovrascrittura), con le stesse regole e le stesse note delle copie.
|
||||
- Resta l'originale il file della libreria: SHA-256, miniatura, doppioni, `_febe.jsonl`, «Copia in…», «Fotogrammi…» e
|
||||
l'elenco CSV usano sempre l'originale. Il convertito non si riscarica e non è un doppione.
|
||||
- Quando la accendi Febe chiede **«Convertire anche i N file già in libreria?»**, con lo spazio che occupano gli
|
||||
originali (i convertiti possono occupare di più): **«Solo i nuovi»** converte da adesso in poi, ogni file dopo il
|
||||
suo scaricamento o la sua importazione; «Anche i N già in libreria» li mette tutti in coda. Spegnerla svuota la coda;
|
||||
i file già convertiti restano dove sono.
|
||||
- Lavora **in sottofondo**, un file alla volta, mai durante una sessione del motore; quando parte un'importazione, una
|
||||
copia o una ricostruzione si fa da parte e riprende dopo. Con il disco della libreria quasi pieno (sotto 10 GB o il 5 %
|
||||
liberi, contando il file da scrivere) si mette in pausa e lo dice.
|
||||
- **A che punto è**: in Impostazioni ▸ Esportazione e nella Dashboard, scheda Esportazione («In coda 12 · convertiti 340
|
||||
· non riusciti 2 · non si convertono 3»), con **«Interrompi»**, **«Riprendi»** e **«Riprova i non riusciti»**. «Non si
|
||||
converte» vuol dire che il file resta solo originale (HEIC, raw, un'immagine animata, un video che non va in MP4
|
||||
senza ricodifica): non si riprova finché il file non cambia.
|
||||
- Nel **visualizzatore**, pannello File: «Convertito in PNG · 2,1 MB» con «Mostra nella cartella» (Windows) o «Scarica»,
|
||||
e sotto ciò che non si è tenuto.
|
||||
- Solo tu togli un convertito, sempre con il suo originale: «Elimina dalla libreria» (la conferma li conta: «… 9 file e
|
||||
2 file convertiti»), la rimozione di un account con i suoi file, «Tieni il più grande» per il file che scarti. Un
|
||||
convertito che hai cambiato tu dopo la conversione resta dov'è, e Febe lo dice. Se l'originale cambia, il convertito
|
||||
di prima resta e se ne fa uno nuovo.
|
||||
- La ricostruzione del database non converte e riconosce i convertiti accanto agli originali; l'importazione riconosce
|
||||
un convertito, o una copia convertita o un fotogramma di una cartella delle copie, come già in libreria («È una copia
|
||||
convertita (o un fotogramma) di un file già in libreria.»).
|
||||
|
||||
## La Dashboard, scheda Esportazione
|
||||
|
||||
La Dashboard ha due schede, **Motore** ed **Esportazione** (`/dashboard/esportazione`).
|
||||
@@ -150,8 +269,11 @@ La Dashboard ha due schede, **Motore** ed **Esportazione** (`/dashboard/esportaz
|
||||
- **Da riprendere:** le cartelle in pausa con il motivo e **«Riprova»**; le copie interrotte o in pausa con
|
||||
**«Riprendi»** (riparte dai file che mancano) e **«Annulla»** (i file già copiati restano, gli altri non si copiano);
|
||||
**«Riprendi tutte»**. Una copia interrotta da un arresto di Febe si ritrova qui al riavvio: non riparte da sola.
|
||||
- **Conversione della libreria** (quando è accesa o ha già lavorato): a che punto è, con «Interrompi», «Riprendi» e
|
||||
«Riprova i non riusciti».
|
||||
- **Ultimi lavori**, ognuno con il suo **«Resoconto»**: copiati, già presenti e riconosciuti, già copiati, saltati, non
|
||||
presenti in libreria, non riusciti, per account, e i file da guardare con il motivo.
|
||||
presenti in libreria, non riusciti, per account (con i file copiati come sono), i file da guardare con il motivo e le
|
||||
note dei file copiati (che cosa non si è tenuto, che cosa si è copiato com'è).
|
||||
|
||||
Quando ci sono copie da riprendere o cartelle in pausa, la scheda Motore lo dice con un avviso.
|
||||
|
||||
|
||||
@@ -49,6 +49,8 @@ fare solo con Instagram o su Windows:
|
||||
Unraid.
|
||||
- **Copie esterne degli originali (tappa E2, 27 novembre 2026):** pronte, da provare dal vivo su Unraid con
|
||||
`/esporta` montata e su Windows con una cartella di rete. Vedi [Copie esterne](Esportazione).
|
||||
- **Formati, fotogrammi e conversione della libreria (tappa E3, 28 novembre 2026):** pronti, da provare dal vivo con
|
||||
foto e video veri della tua libreria (HEIC e MOV del telefono compresi). Vedi [Copie esterne](Esportazione).
|
||||
|
||||
## Pagine della guida
|
||||
|
||||
@@ -60,7 +62,7 @@ fare solo con Instagram o su Windows:
|
||||
| [Account e impostazioni](Account-e-impostazioni) | Aggiungere account, punti di partenza, impostazioni per account |
|
||||
| [Libreria](Libreria) | Mosaico, filtri, visualizzatore, eliminazione, esportazione CSV, nomi dei file |
|
||||
| [Importazione](Importazione) | Portare in libreria foto e video che hai già, senza doppioni |
|
||||
| [Copie esterne](Esportazione) | Copiare i file della libreria su un disco esterno o una cartella di rete: cartelle, «Copia in…», stati delle copie, `/esporta` in Docker |
|
||||
| [Copie esterne](Esportazione) | Copiare i file della libreria su un disco esterno o una cartella di rete: cartelle, «Copia in…», formati, fotogrammi, conversione della libreria, stati delle copie, `/esporta` in Docker |
|
||||
| [Limiti e comportamento](Limiti-e-comportamento) | Profili di prudenza, tetti, fascia oraria, ritmo delle sessioni |
|
||||
| [Dashboard e arresti](Dashboard-e-arresti) | La Dashboard, pagina iniziale e cruscotto del motore; che cosa fare dopo una verifica o un rallentamento |
|
||||
| [Avvisi e Telegram](Avvisi-e-Telegram) | Striscia, notifiche di Windows, messaggi Telegram con un bot tuo |
|
||||
|
||||
@@ -43,7 +43,9 @@ Quattro contatori:
|
||||
|
||||
I doppioni si cercano anche dentro la sorgente stessa (una copia identica nella sorgente si copia una volta sola). Per
|
||||
i video vale solo lo SHA-256 (e il codice). Un file che hai eliminato «ricordando la scelta» conta come già in
|
||||
libreria: un'importazione non annulla un'eliminazione.
|
||||
libreria: un'importazione non annulla un'eliminazione. Anche un file convertito della libreria, o una copia convertita
|
||||
o un fotogramma presi da una cartella delle copie ([Copie esterne](Esportazione)), conta come già in libreria («È una
|
||||
copia convertita (o un fotogramma) di un file già in libreria.»), mai come doppione probabile dell'originale.
|
||||
|
||||
**Cartelle e account.** Una tabella lega ogni cartella della sorgente a un account: uno esistente (riconosciuto per
|
||||
identificativo o per nome), oppure un nuovo account «Solo archivio» con il nome della cartella. Una cartella senza
|
||||
|
||||
@@ -43,7 +43,9 @@ si legge «Libreria, file 12 di 61.034». A lato: la serie dei file, didascalia,
|
||||
|
||||
- **Mostra nella cartella** (Windows) oppure **Scarica** il file (dal browser, in Docker);
|
||||
- **Apri su Instagram**, nel tuo browser;
|
||||
- **Elimina dalla libreria**.
|
||||
- **Elimina dalla libreria**;
|
||||
- con le copie esterne, **«Copia in…»** e, per i video, **«Fotogramma»** (vedi [Copie esterne](Esportazione)); nel
|
||||
pannello File le righe delle copie e, con la conversione della libreria accesa, dei file convertiti.
|
||||
|
||||
## Eliminare
|
||||
|
||||
@@ -55,7 +57,9 @@ Eliminare chiede conferma. I file vengono cancellati dal disco e non si recupera
|
||||
scarica di nuovo.
|
||||
|
||||
L'eliminazione si scrive prima nel file `_febe.jsonl` dell'account, poi nel database, poi sul disco: anche una
|
||||
ricostruzione del database la rispetta.
|
||||
ricostruzione del database la rispetta. Se la conversione della libreria ha aggiunto dei file convertiti, se ne vanno
|
||||
con i loro originali e la conferma li conta («… 9 file e 2 file convertiti»); un convertito che hai cambiato tu resta.
|
||||
Le copie esterne invece restano dove sono.
|
||||
|
||||
**La libreria non cancella e non sostituisce mai un file da sola.** Se un contenuto sparisce da Instagram, il file
|
||||
resta. Un file si elimina o si sostituisce solo per una scelta tua.
|
||||
@@ -63,7 +67,8 @@ resta. Un file si elimina o si sostituisce solo per una scelta tua.
|
||||
## Selezione multipla
|
||||
|
||||
«Seleziona» attiva la scelta delle tessere; nella barra in basso: **Esporta l'elenco** degli elementi scelti oppure
|
||||
**Elimina** (con la stessa conferma di sopra). «Fine» chiude la selezione.
|
||||
**Elimina** (con la stessa conferma di sopra); **Fotogrammi…** per i video scelti; con una cartella delle copie anche
|
||||
«Copia in…» ([Copie esterne](Esportazione)). «Fine» chiude la selezione.
|
||||
|
||||
Con «Tutte le foto» si scelgono i file, ma l'elenco CSV ed «Elimina» lavorano sugli **elementi interi** a cui
|
||||
appartengono: la barra lo dice («3 file scelti, di 2 elementi», «Elimina 2 elementi») e anche la conferma («3 file
|
||||
|
||||
@@ -95,8 +95,8 @@ in cima senza nulla da controllare non si visita. Le storie scadono dopo 24 ore:
|
||||
scadano prima di essere scaricate. Un account può avere un ordine suo (scheda dell'account → Impostazioni, vedi
|
||||
[Account e impostazioni](Account-e-impostazioni)). Un reel conta come reel quando Febe sa che lo è (l'ha trovato nella
|
||||
scheda Reel, o la risposta lo dice), altrimenti come post. Perché i tipi in fondo non restino ad aspettare per sempre,
|
||||
un file su otto della coda è quello che aspetta da più tempo, di qualunque tipo sia. Questa quota è una proposta, ancora da
|
||||
confermare.
|
||||
un file su otto della coda è quello che aspetta da più tempo, di qualunque tipo sia. Questa quota è decisa (risposta del
|
||||
29 novembre 2026).
|
||||
|
||||
## Avvio graduale
|
||||
|
||||
|
||||
@@ -152,6 +152,16 @@ Vedi anche [Copie esterne](Esportazione).
|
||||
| «C'è un lavoro di copia non finito verso questa cartella…» | Prima di cambiare la cartella, riprendi o annulla quel lavoro nella Dashboard, scheda Esportazione |
|
||||
| «Copia in…» dice «N di account che non si esportano» | Quegli account hanno «Esporta questo account» spento (scheda dell'account ▸ Impostazioni ▸ «Copie esterne») |
|
||||
| «Copia in…» o il filtro «Copie» non ci sono | Manca una cartella delle copie: scegline una in Impostazioni ▸ Esportazione (o nella scheda dell'account) |
|
||||
| Ho scelto JPG ma un file è arrivato com'è («HEIC copiato com'è», «Immagine animata copiata com'è…», «Copiato com'è: …») | È voluto: HEIC, AVIF, raw, immagini animate, immagini CMYK o con più di 8 bit verso PNG e WEBP e quelle troppo grandi non si convertono. Le note sono nel resoconto e nel visualizzatore |
|
||||
| «Video copiato com'è: non si porta in MP4 senza ricodificarlo (codec video)» | Il video non è H.264 o HEVC (o l'audio non è AAC o MP3, o il contenitore non si rimuxa): Febe non ricodifica mai, quindi lo copia com'è |
|
||||
| «Già copiato in un altro formato» | Il file è già nella cartella in un'altra forma. Per averlo nel formato nuovo: togli il file vecchio dalla cartella, «Controlla le copie», poi «Copia di nuovo» |
|
||||
| «Fotogramma non disponibile per questo video» | Il video è in un codec che Febe non decodifica (VP9, AV1…) o è rovinato. Il video intero si copia lo stesso |
|
||||
| «Il fotogramma richiede troppo tempo: scegli la cartella delle copie» | Un video lungo o grande non dà l'anteprima in 30 secondi: scegli «Nella cartella delle copie», che lavora senza fretta |
|
||||
| «Il motore è in sessione: per più di 20 fotogrammi riprova fra poco» | Uno zip di più di 20 fotogrammi si prepara solo fuori dalle sessioni del motore e quando non lavorano importazione, copie o ricostruzione: riprova dopo, o scegli meno fotogrammi |
|
||||
| «Per più di 500 fotogrammi scegli la cartella delle copie» o «Più di 1.000 fotogrammi per un video…» | Sono i limiti di «Scarica» e di un video: scegli «Nella cartella delle copie», o un intervallo più lungo |
|
||||
| La conversione della libreria non va avanti: «Il motore è in sessione…», «Un'importazione, una copia o una ricostruzione è al lavoro…» | È voluto: la conversione lavora in sottofondo e cede il passo. Riprende da sola |
|
||||
| «Spazio libero sotto la soglia: la conversione della libreria è in pausa» | Il disco della libreria è quasi pieno: libera spazio (o spegni la conversione); riprende da sola |
|
||||
| Un file convertito «non si converte» o «Conversione … non riuscita» | «Non si converte» è definitivo (HEIC, raw, animata…); per gli altri, se la cartella dell'account era staccata o il file mancava, sistema e premi «Riprova i non riusciti» in Impostazioni ▸ Esportazione |
|
||||
|
||||
## Database
|
||||
|
||||
|
||||
@@ -119,4 +119,5 @@ trattale come i dati che descrivono.
|
||||
Le [copie esterne](Esportazione) escono dal controllo di Febe: chi ha la cartella delle copie, o il disco su cui sta,
|
||||
ha quei file, foto e video di altre persone compresi. Febe non le cifra e non le cancella; nelle cartelle delle copie
|
||||
non scrive diari, identificativi o didascalie, solo i file. Una chiavetta o un disco con le copie va trattato come la
|
||||
libreria.
|
||||
libreria. Lo stesso vale per i fotogrammi scaricati e per i loro zip, che finiscono nei download del browser. Una
|
||||
conversione con perdita (JPG) è una scelta tua: Febe non la fa mai da sola.
|
||||
@@ -549,7 +549,7 @@ cambiano». Se i nomi sono diversi, il catalogo va corretto prima di configurare
|
||||
|
||||
---
|
||||
|
||||
## F. Copie esterne (tappa E2): Docker con `/esporta`, FAT32, cartella di rete su Windows
|
||||
## F. Copie esterne (tappe E2 ed E3): Docker con `/esporta`, FAT32, cartella di rete su Windows, formati, fotogrammi
|
||||
|
||||
Scopo: vedere sul tuo impianto ciò che le prove automatiche non possono fare (specifica §4.10, §11, §12): un montaggio
|
||||
vero su Unraid, un disco FAT32 vero, una condivisione che si stacca. **Non serve Instagram**: le copie leggono solo
|
||||
@@ -618,10 +618,67 @@ in quelle cartelle, né crearne la cartella scelta.
|
||||
5. Facoltativo: esci da Febe durante una copia e riaprilo. Atteso: la copia è «Interrotta» nella scheda Esportazione e
|
||||
non riparte da sola; nel registro «N copie interrotte dall'arresto precedente…».
|
||||
|
||||
### F5. Che cosa riferire
|
||||
### F5. Formati delle copie con i tuoi file (tappa E3)
|
||||
|
||||
Le prove automatiche convertono immagini e video costruiti da loro; qui servono file veri del tuo telefono e della
|
||||
libreria: qualche JPG con la posizione nell'EXIF, una foto HEIC, un PNG con la trasparenza, una GIF animata, un MOV
|
||||
dell'iPhone (meglio se girato in verticale) e un video con VP9 o AV1, se ne hai uno (per esempio un WebM).
|
||||
|
||||
1. Impostazioni ▸ Esportazione ▸ «Formati delle copie»: Foto **JPG**, Video **MP4**. Atteso: «con perdita: qualità 92»
|
||||
sotto JPG, «solo rimuxaggio, mai ricodifica» sotto MP4.
|
||||
2. «Copia in…» su quei file. Atteso nel riepilogo: «circa 1 HEIC copiato com'è», «con perdita». Copia, poi
|
||||
«Resoconto»: l'HEIC, la GIF e il video VP9/AV1 «come sono», con la nota; il PNG con «La trasparenza è diventata
|
||||
bianco».
|
||||
3. Nella cartella delle copie: il JPG di partenza è **identico** all'originale (confronta lo SHA-256, per esempio con
|
||||
`Get-FileHash` su Windows o `sha256sum` su Unraid); il PNG è diventato `.jpg`, con lo sfondo bianco dove era
|
||||
trasparente; il MOV è diventato `.mp4`, si apre nel browser e nel lettore di sistema, è **diritto** come l'originale,
|
||||
ha l'audio e la stessa durata, e le proprietà del file (Windows: Proprietà ▸ Dettagli) hanno la stessa data di
|
||||
ripresa; la foto convertita ha ancora l'EXIF (data, fotocamera, posizione) e l'orientamento giusto.
|
||||
4. Cambia Foto in **PNG** e rifai «Copia in…» sugli stessi file. Atteso: «già copiati, saltati» e nel resoconto «Già
|
||||
copiato in un altro formato»; nessun file nuovo. Togli a mano un JPG convertito dalla cartella, «Controlla le copie»,
|
||||
poi «Copia di nuovo» dal visualizzatore: atteso di nuovo il JPG (la forma di quella copia), non un PNG.
|
||||
5. Rimetti i formati su «Originale».
|
||||
|
||||
### F6. Fotogrammi (tappa E3)
|
||||
|
||||
1. Apri nel visualizzatore un video vero H.264 (un reel scaricato) e uno HEVC (un MOV dell'iPhone recente). Ferma il
|
||||
lettore su un'immagine riconoscibile e premi «Fotogramma». Atteso: la finestra si apre a quell'istante e
|
||||
l'anteprima è **la stessa immagine** che vedevi; «Il fotogramma non ha l'audio.».
|
||||
2. «Scarica» in PNG. Atteso: un file `…_t0m…s….png` della piena risoluzione del video, diritto come il video si vede.
|
||||
3. «N in tutto» = 5, «Scarica». Atteso: uno zip `febe-fotogrammi-AAAA-MM-GG.zip` con una cartella dell'account e
|
||||
cinque file `…_f001.png` … `…_f005.png`, distribuiti lungo il video.
|
||||
4. Su un video VP9 o AV1 (o una tessera neutra): atteso «Fotogramma non disponibile per questo video».
|
||||
5. Dalla Libreria: «Seleziona», scegli alcuni video e qualche foto, «Fotogrammi…», «Uno ogni 10 secondi», «Nella
|
||||
cartella delle copie». Atteso: «le N foto si saltano»; il lavoro nella Dashboard; nella cartella i fotogrammi accanto
|
||||
alle copie, con l'istante nel nome. Le tessere dei video copiati solo come fotogrammi hanno il segno «Solo
|
||||
fotogrammi» e il filtro «Copie» li mette fra i «Non ancora copiati».
|
||||
6. Facoltativo: durante una sessione del motore chiedi lo zip di 30 fotogrammi. Atteso: «Il motore è in sessione: per
|
||||
più di 20 fotogrammi riprova fra poco»; fuori dalla sessione lo zip parte.
|
||||
|
||||
### F7. Conversione della libreria (tappa E3)
|
||||
|
||||
Prima: annota il numero dei file di una cartella di account e lo SHA-256 di due o tre originali (`Get-FileHash` o
|
||||
`sha256sum`). Alla fine gli originali devono essere **identici** e i file solo in più.
|
||||
|
||||
1. Impostazioni ▸ Esportazione ▸ «Conversione della libreria»: Foto **PNG**. Atteso il dialogo «Convertire anche i N
|
||||
file già in libreria?» con lo spazio degli originali; scegli **«Solo i nuovi»**. Atteso: niente in coda.
|
||||
2. Importa (o lascia scaricare) due o tre foto JPG nuove. Atteso, fuori dalle sessioni del motore e entro un minuto o
|
||||
due: «convertiti 3» nella riga di stato; accanto a ogni `foto.jpg` della libreria un `foto.png`; il visualizzatore
|
||||
mostra «Convertito in PNG · …» con «Mostra nella cartella» (Windows) o «Scarica».
|
||||
3. Avvia un'importazione grande mentre la conversione lavora (con «Anche i N già in libreria» su un account piccolo).
|
||||
Atteso: l'importazione parte subito; la conversione dice «Un'importazione, una copia o una ricostruzione è al
|
||||
lavoro…» e riprende dopo.
|
||||
4. «Interrompi», poi «Riprendi». Atteso: si ferma e riparte; i file già convertiti restano.
|
||||
5. Elimina dalla libreria un elemento con un convertito. Atteso: la conferma dice «… e 1 file convertito»; dopo,
|
||||
originale e convertito non ci sono più, le copie esterne restano.
|
||||
6. Rimetti Foto su «Originale». Atteso: la coda si svuota, i file convertiti restano dove sono.
|
||||
|
||||
### F8. Che cosa riferire
|
||||
|
||||
- Per ogni passo «come atteso» oppure il testo esatto di ciò che hai visto, con l'ora.
|
||||
- Il conteggio dei file della cartella delle copie prima e dopo (F2, F4): solo file in più, mai meno o cambiati.
|
||||
- In F5 e F7 gli SHA-256 degli originali prima e dopo (devono coincidere) e, per F5 passo 3, se data, posizione e
|
||||
rotazione sono rimaste; in F6 se l'anteprima era davvero l'immagine che il lettore mostrava.
|
||||
- Le righe del registro dell'avvio che parlano di copie esterne (F1, F2) e quelle della pausa (F2 passo 8, F4).
|
||||
- In F2 passo 1 l'esito di `stat -c '%u:%g' /mnt/user/Febe-copie /mnt/user/Febe-copie/disco` dal terminale di Unraid.
|
||||
- Se un file è finito nel posto sbagliato (per esempio nella cartella vuota del server con il disco smontato): il
|
||||
|
||||
|
Before Width: | Height: | Size: 101 KiB After Width: | Height: | Size: 112 KiB |
|
Before Width: | Height: | Size: 97 KiB After Width: | Height: | Size: 141 KiB |
|
Before Width: | Height: | Size: 148 KiB After Width: | Height: | Size: 163 KiB |
|
Before Width: | Height: | Size: 143 KiB After Width: | Height: | Size: 144 KiB |
|
Before Width: | Height: | Size: 515 KiB After Width: | Height: | Size: 482 KiB |
|
Before Width: | Height: | Size: 238 KiB After Width: | Height: | Size: 233 KiB |
|
Before Width: | Height: | Size: 447 KiB After Width: | Height: | Size: 257 KiB |
|
Before Width: | Height: | Size: 64 KiB After Width: | Height: | Size: 76 KiB |
|
After Width: | Height: | Size: 160 KiB |
|
After Width: | Height: | Size: 174 KiB |
|
After Width: | Height: | Size: 187 KiB |
|
After Width: | Height: | Size: 128 KiB |
|
After Width: | Height: | Size: 546 KiB |
|
After Width: | Height: | Size: 129 KiB |
@@ -41,14 +41,20 @@ solo per l'interfaccia di Febe (§10.7).
|
||||
| `doppioni-download.png` | `/doppioni` | confronto di `miniature/09-importa-revisione.png` (§9.5) |
|
||||
| `primo-avvio.png` | `/libreria?scena=scollegato`, libreria vuota disegnata dal passo `benvenuto.js` | (nessuno: §10.3) |
|
||||
| `errore-configurazione.png` | `/libreria?scena=errore` | (nessuno) |
|
||||
| `15-impostazioni-esportazione.png` | `/impostazioni/esportazione` (presa il 27/11 da Windows, come le righe seguenti) | composta da `docs/mockup/08-impostazioni-generali.png` e `miniature/07-limiti-e-comportamento.png` |
|
||||
| `15-impostazioni-esportazione.png` | `/impostazioni/esportazione`, 1440 × 1470 (presa il 27/11 da Windows, come le righe seguenti fino alla 21; tutte rifatte il 28/11 con i formati della tappa E3) | composta da `docs/mockup/08-impostazioni-generali.png` e `miniature/07-limiti-e-comportamento.png` |
|
||||
| `15-impostazioni-esportazione-docker.png` | `/impostazioni/esportazione?veste=docker`, con la nota su `/esporta` | come sopra |
|
||||
| `16-destinazione.png` | `/impostazioni/esportazione`, «Modifica…» della cartella generale, «Uno schema suo» con il primo schema cambiato (passo `destinazione.js`), 1440 × 1000 | composta dal mockup 08 («Nomi dei file», «Risultato») e dai dialoghi di `miniature/13-foglio-di-stile.png` |
|
||||
| `17-account-copie-esterne.png` | `/account/3/impostazioni` (@studio.lumen.demo, cartella sua), scorsa fino a «Cartella» (passo `account-copie.js`), 1440 × 1000 | composta da `miniature/05-account-impostazioni.png` |
|
||||
| `18-copia-in.png` | `/libreria`, menu dell'icona CSV → «Copia i file in…» su tutta la libreria (passo `copia-in.js`) | composta dai dialoghi del 13 e da `miniature/09-importa-revisione.png` |
|
||||
| `19-libreria-copie.png` | `/libreria?copie=copiati`, menu dell'icona CSV aperto (passo `menu-csv.js`) | composta da `docs/mockup/01-libreria.png` |
|
||||
| `20-visualizzatore-copie.png` | `/libreria?copie=tolti`, la prima foto con «Copia di nuovo» (passo `visualizzatore-copie.js`) | composta da `miniature/02-visualizzatore.png` |
|
||||
| `21-dashboard-esportazione.png` | `/dashboard/esportazione` | composta da `miniature/06-attivita.png` e dal passo 2 dell'importazione (mockup 09) |
|
||||
| `21-dashboard-esportazione.png` | `/dashboard/esportazione`, con il riquadro «Conversione della libreria» | composta da `miniature/06-attivita.png` e dal passo 2 dell'importazione (mockup 09) |
|
||||
| `22-fotogrammi-visualizzatore.png` | `/libreria`, il video di @marta.demo con un fotogramma copiato, il lettore a 1,25 s, «Fotogramma»: «Questo istante» con l'anteprima (passo `fotogrammi-visualizzatore.js`), 1440 × 1000 (presa il 28/11 da Windows, come le righe seguenti) | composta dai dialoghi di `miniature/13-foglio-di-stile.png` sopra `miniature/02-visualizzatore.png` |
|
||||
| `22-fotogrammi-striscia.png` | come sopra, «N in tutto» 8, JPG, «Nella cartella delle copie» (passo `fotogrammi-striscia.js`), 1440 × 1000 | come sopra, con la riga delle cartelle di `miniature/09-importa-revisione.png` |
|
||||
| `23-fotogrammi-selezione.png` | `/libreria?account=2` (@marta.demo), «Seleziona», quattro video e quattro foto, «Fotogrammi…» (passo `fotogrammi-selezione.js`), 1440 × 1000 | composta dai dialoghi del 13 sopra `docs/mockup/01-libreria.png` |
|
||||
| `24-visualizzatore-fotogramma.png` | `/libreria`, lo stesso video, righe «Copia» con «· intero» e «· fotogramma a 0:01,125 · PNG» (passo `visualizzatore-fotogramma.js`) | composta da `miniature/02-visualizzatore.png` |
|
||||
| `25-copia-in-formati.png` | come la 18, con «Cambia» aperto e PNG per le foto (passo `copia-in-formati.js`), 1440 × 1000 | composta dai dialoghi del 13 e dai controlli segmentati di `miniature/07-limiti-e-comportamento.png` |
|
||||
| `26-conversione-libreria.png` | `/impostazioni/esportazione`, «Conversione della libreria» → PNG: la domanda «Convertire anche i N file già in libreria?» (passo `conversione-libreria.js`; nessuna risposta, l'impostazione resta «Originale») | composta da `docs/mockup/08-impostazioni-generali.png` e dai dialoghi del 13 |
|
||||
|
||||
## Differenze che restano
|
||||
|
||||
@@ -228,14 +234,15 @@ da cui nascono. Le prove dell'interfaccia (`ExportInterfaceTests`: impostazioni
|
||||
destinazione, blocco dell'account, «Copia in…» dalla selezione, filtro «Copie» e segno sulle tessere, righe del
|
||||
visualizzatore, scheda della Dashboard) girano solo nella CI, con Chromium: qui non sono state eseguite. Differenze:
|
||||
|
||||
- **Formati e conversione non ci sono (E3).** La tappa E2 copia solo gli originali: la finestra della destinazione non
|
||||
ha la parte dei formati, Impostazioni → Esportazione non ha «Formati predefiniti delle copie» né «Conversione della
|
||||
libreria», e il riepilogo di «Copia in…» non ha mai «3 HEIC copiati come sono» né «con perdita». I controlli mancano,
|
||||
non sono spenti: un controllo grigio senza niente dietro non dice che cosa succede (§10.4).
|
||||
- **Formati e conversione non c'erano (E3).** Nelle schermate del 27/11 la finestra della destinazione non aveva la
|
||||
parte dei formati, Impostazioni → Esportazione non aveva «Formati delle copie» né «Conversione della libreria», e
|
||||
«Copia in…» non aveva la riga del formato: sono arrivati con la tappa E3, e le schermate 15–21 sono state rifatte il
|
||||
28/11 con loro (qui sotto, «Formati e fotogrammi»).
|
||||
- **«Automatica» non c'è (E5).** La scelta si conserva ma non si mostra, con la domanda «Solo i nuovi»: senza il giro
|
||||
orario della tappa E5 un interruttore acceso non farebbe nulla.
|
||||
- **«Fotogrammi…» e «Fotogramma» non ci sono (E3)**: né nella barra della selezione della Libreria e della scheda
|
||||
account, né nel visualizzatore. Neppure la finestra «Fotogrammi…».
|
||||
- **«Fotogrammi…» e «Fotogramma» non c'erano (E3)** nelle schermate del 27/11: né nella barra della selezione della
|
||||
Libreria e della scheda account, né nel visualizzatore. Sono arrivati con la tappa E3 (qui sotto; nella 20 rifatta
|
||||
il 28/11 la foto non ha «Fotogramma», che è solo dei video).
|
||||
- **«È un video fermo?» non c'è (E4)** nel visualizzatore.
|
||||
- **Segno sulla tessera** (voluto, §4.10): l'ultimo dei segni in alto a destra, un riquadro scuro con l'icona `copy`
|
||||
quando i file dovuti dell'elemento sono tutti copiati, con «2/3» quando lo sono solo in parte. Nel mockup 01 non c'è.
|
||||
@@ -287,6 +294,81 @@ visualizzatore, scheda della Dashboard) girano solo nella CI, con Chromium: qui
|
||||
visualizzatore, la finestra della destinazione in Docker, il «Resoconto», una copia in corso con Interrompi, una
|
||||
cartella in pausa con «Riprova», il tema scuro, la finestra stretta e il telefono.
|
||||
|
||||
### Formati e fotogrammi (tappa E3, issue #58, dal 28 novembre 2026)
|
||||
|
||||
Anche queste parti non hanno un mockup (§10.3 «Schermate dell'esportazione»): sono composte dai mockup esistenti, come
|
||||
dice la tabella. Il 28/11 le schermate `15-…` – `21-…` sono state rifatte e le sei nuove `22-…` – `26-…` prese con il
|
||||
programma delle schermate da Windows (`tools/Febe.Schermate`, browser senza finestra, scala 1,25), una alla volta con
|
||||
`una`, su una dimostrazione appena avviata (`--demo --porta 8490`), nell'ordine della tabella; nessun passo converte,
|
||||
scarica o copia, e la domanda della conversione resta senza risposta. Misure: 1440 × 900; 1440 × 1000 per le finestre
|
||||
alte (fotogrammi, «Copia in…» con «Cambia» aperto); 1440 × 1470 per Impostazioni → Esportazione intera, che ora arriva
|
||||
fino a «Conversione della libreria». Poi sono state messe accanto ai mockup da cui nascono; le stesse finestre sono state
|
||||
guardate anche in tema scuro e a 390 × 844 (senza schermata nella cartella). Le prove dell'interfaccia girano solo nella
|
||||
CI. Differenze:
|
||||
|
||||
- **Impostazioni → Esportazione** (mockup 08 e 07): due blocchi nuovi, «Formati delle copie» dopo «Cartella generale» e
|
||||
«Conversione della libreria» in fondo, con i controlli segmentati del mockup 07 (Foto: Originale · JPG · PNG · WEBP
|
||||
senza perdita; Video: Originale · MP4) e la nota sotto il controllo («con perdita: qualità 92», «solo rimuxaggio, mai
|
||||
ricodifica»). Il blocco della conversione ha la riga di stato («In coda 12 · convertiti 340 · …») con «Interrompi» o
|
||||
«Riprendi» e «Riprova i non riusciti», e l'avviso del motivo dell'attesa; la domanda «Convertire anche i N file già
|
||||
in libreria?» è un dialogo del mockup 13 con «Solo i nuovi» come pulsante principale.
|
||||
- **Finestra della destinazione**: una parte «Formati» con gli stessi controlli e la prima voce «Come le impostazioni
|
||||
generali».
|
||||
- **«Copia in…»**: una riga «Formato: come la destinazione · Cambia» sopra il riepilogo; «Cambia» apre i due controlli
|
||||
per quella copia sola. Il riepilogo aggiunge «circa 3 HEIC copiati come sono» e «con perdita».
|
||||
- **Finestra «Fotogrammi…»** (dialoghi del mockup 13, elenco delle scelte del passo 3 del mockup 09): dal visualizzatore
|
||||
anteprima grande del fotogramma (al più 480 pixel), cursore e campo dell'istante, la riga «Fotogramma a 0:01,125»,
|
||||
una striscia con le prime sei anteprime e «e altri N»; poi formato (PNG, JPG con la nota «con perdita», WEBP senza
|
||||
perdita), «Il fotogramma non ha l'audio.» e l'uscita, «Scarica» o «Nella cartella delle copie» (spenta senza una
|
||||
cartella). **Dalla selezione** la finestra ha solo il campo dell'istante, senza anteprime né cursore (non c'è un
|
||||
video solo), e il riepilogo dice «4 fotogrammi da 4 video · le 6 foto si saltano» (23).
|
||||
- **Visualizzatore** (mockup 02): «Fotogramma» fra le azioni dei video (ferma il video e apre la finestra al suo
|
||||
istante), o la riga «Fotogramma non disponibile per questo video»; le righe delle copie aggiungono la forma («· intero»,
|
||||
«· PNG», «· fotogramma a 0:01,125 · PNG») e le note su una seconda riga; i file convertiti della libreria hanno una
|
||||
riga loro («Convertito in PNG · 2,1 MB») con «Mostra nella cartella» su Windows o «Scarica».
|
||||
- **Segno «Solo fotogrammi»** sulla tessera (mockup 01): un piccolo riquadro disegnato in CSS, senza un'icona nuova,
|
||||
nello stesso posto del segno delle copie. Nel mockup non c'è (come il segno delle copie, voluto).
|
||||
- **Dashboard → Esportazione**: un riquadro «Conversione della libreria» fra «Da riprendere» e «Ultimi lavori», solo
|
||||
quando la conversione è accesa o ha righe; nel resoconto la colonna «Come sono» e la parte «Note». Aggiunte senza
|
||||
mockup.
|
||||
- **Conferma dell'eliminazione**: aggiunge i file convertiti («… elimino gli elementi interi, 9 file e 2 file
|
||||
convertiti»).
|
||||
- **Dialoghi sopra il visualizzatore**: un dialogo aperto dal visualizzatore (la finestra «Fotogrammi», «Copia in…»)
|
||||
ora sta sopra di lui; prima restava sotto.
|
||||
- **Contenuti dimostrativi.** Ogni video della dimostrazione è lo stesso video di 2 secondi, 240 × 432: le informazioni
|
||||
del file nel visualizzatore (720 × 1280, 0:11 nella 22 e nella 24) non coincidono con quelle della finestra dei
|
||||
fotogrammi («Video di 0:02, 240 × 432 pixel»), e l'anteprima è stretta in mezzo a un riquadro nero largo. «Nella
|
||||
cartella delle copie» dei fotogrammi e una «Copia in…» di un video finiscono in errore nella dimostrazione («non
|
||||
corrisponde»), perché i video dimostrativi hanno lo SHA-256 della loro copertina; le anteprime e «Scarica» funzionano.
|
||||
Le foto della dimostrazione sono tutte JPEG: nella 25 il riepilogo di «Copia in…» con PNG resta uguale a quello della
|
||||
18 (994 file; i 28.865 già copiati restano «già copiati» in qualunque formato, decisione D3) e non può mostrare né
|
||||
«con perdita» né «copiati come sono» («con perdita» si vede nella 22-striscia: «8 fotogrammi da 1 video · con
|
||||
perdita»). Il segno
|
||||
«Solo fotogrammi» non si vede in nessuna tessera: il video del fotogramma dimostrativo ha anche la copia intera (per
|
||||
SHA-256, come sopra), quindi la sua tessera ha il segno delle copie. I numeri delle schermate 15–21 sono quelli della
|
||||
dimostrazione del 28/11 e non coincidono con quelli citati qui sopra per la tappa E2 (per esempio «335 su 657 non ancora
|
||||
copiati» invece di «371 su 648»).
|
||||
- **Confronto con le immagini** (28/11): la finestra «Fotogrammi» ha intestazione, piede con «Annulla» e il pulsante
|
||||
principale, titoli delle parti e righe divisorie dei dialoghi del 13; le scelte «Scarica» / «Nella cartella delle
|
||||
copie» sono le scelte a pallino con la riga d'aiuto del passo 3 del mockup 09; la riga della cartella nella 22-striscia
|
||||
e nella 25 è quella dell'elenco delle cartelle dell'importazione. I controlli dei formati sono i segmentati del mockup
|
||||
07, con l'etichetta a sinistra come le righe del mockup 08. Il visualizzatore (24) è quello del mockup 02 con le righe
|
||||
«Copia» e cinque azioni in fondo invece di due («Copia in…» e «Fotogramma» si aggiungono). Nessuna differenza da
|
||||
segnalare oltre a quelle elencate qui sopra e ai ritocchi seguenti.
|
||||
- **Sistemato il 28/11** dopo il confronto:
|
||||
- nella finestra «Fotogrammi» la riga «Fotogramma a 0:01,25» accanto al campo dell'istante (e «Lo stesso istante in ogni
|
||||
video…» dalla selezione) stava 6 px più in alto del campo, perché la regola dei paragrafi dei dialoghi le dava 12 px
|
||||
sotto: ora è centrata sul campo;
|
||||
- sotto «Formato» la nota «Il fotogramma non ha l'audio.» (e «con perdita: qualità 92») aveva 12 px in più sotto, e la
|
||||
parte «Formato» finiva più larga delle altre: ora le parti hanno lo stesso respiro;
|
||||
- in «Copia in…» con «Cambia» aperto il controllo delle foto (cinque voci) non stava accanto all'etichetta «Foto» e
|
||||
andava a capo, mentre quello dei video restava accanto a «Video»: i due controlli partivano da punti diversi. Ora in
|
||||
«Copia in…» le etichette stanno sopra i controlli, e i due controlli sono allineati.
|
||||
- **Senza schermata:** la veste Docker («Scarica» del convertito), la linguetta della scheda account con «Fotogrammi…»,
|
||||
«Uno ogni k secondi», la riga «Convertito in PNG» del visualizzatore, la conferma dell'eliminazione con i file
|
||||
convertiti, il resoconto con «Come sono» e «Note», il tema scuro, la finestra stretta e il telefono (guardati, senza
|
||||
difetti da correggere), uno zip di più di 20 fotogrammi durante una sessione.
|
||||
|
||||
### Carattere e icone (dal 18 novembre 2026)
|
||||
|
||||
Mockup e schermate di questa cartella sono stati presi con il carattere Archivo e le icone Lucide, che dal 18 novembre
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
# Stato
|
||||
|
||||
Filo fra le sessioni (specifica §15): che cosa è fatto, che cosa è in corso, che cosa è rimandato e perché.
|
||||
Aggiornato il 27 novembre 2026 (tappa E2 Copie esterne; prima, E1 Schema unita in `main` con #69 e la catena della
|
||||
Aggiornato il 29 novembre 2026 (confermate da Alberto le risposte delle domande 19–38 di §16; tappa E3 Formati e
|
||||
fotogrammi; prima, E2 Copie esterne e E1 Schema unita in `main` con #69 e la catena della
|
||||
0.3.0, #60 … #66), versione 0.1.2 in
|
||||
`main` (il tag `v0.1.2` non è stato creato). **Le attività stanno
|
||||
su Gitea**: issue, etichette e traguardi di https://gitea.encke-hake.ts.net/Alby96/Febe. Questo file resta il resoconto
|
||||
@@ -9,9 +10,70 @@ fra le sessioni; ciò che è da fare si legge nelle issue aperte.
|
||||
|
||||
## In breve
|
||||
|
||||
**28 novembre 2026: tappa E3 «Formati e fotogrammi» dell'esportazione** (#58, ramo
|
||||
`funzione/esportazione-formati`). Le undici domande nuove della tappa sono in §16 (righe 28–38): il 29 novembre
|
||||
2026 Alberto ha confermato le proposte adottate.
|
||||
|
||||
- **Foto** (`src/Febe.Core/Codecs/Images/`, `ImageConverter`): copie e libreria in JPG (qualità 92, 4:4:4, trasparenza
|
||||
su bianco, «con perdita»), PNG o WEBP senza perdita; stesso formato = copia byte per byte (anche un WEBP con perdita
|
||||
verso «WEBP senza perdita»). EXIF, ICC e XMP nei loro blocchi; ciò che non si tiene diventa una nota (elenco di
|
||||
codici). Si copiano come sono, con una nota: HEIC, AVIF, raw, animate, illeggibili, CMYK o più di 8 bit verso
|
||||
PNG/WEBP, oltre 40/100 MP o 16.384 px. Stessi byte a ogni conversione sullo stesso runtime (logaritmo a virgola fissa
|
||||
nel WEBP).
|
||||
- **Video**: rimuxaggio in MP4 (MOV, M4V, 3GP, Matroska/WebM con H.264 o HEVC e AAC/MP3) con campioni, tempi, edit
|
||||
list, rotazione e lingua; ciò che non si rimuxa si copia intero con il motivo. **Fotogrammi esatti** (`VideoFrameReader`):
|
||||
un istante, «uno ogni k secondi» da 0:00, «N in tutto» al centro di N parti; PNG di base; nomi `_t0m12s340` e `_f001`;
|
||||
verso le destinazioni (segno «Solo fotogrammi», «Copiato in parte»), «Scarica» di un'immagine o di uno zip (fino a
|
||||
20 sempre, 21–500 fuori dalle sessioni del motore, oltre solo nella cartella delle copie).
|
||||
- **Copie**: formato scelto da «Copia in…», poi dalla destinazione, poi dalle impostazioni; si converte prima dei
|
||||
controlli di spazio e FAT32; adozione per lunghezza e SHA-256 della conversione; «già copiato» in qualunque forma
|
||||
tranne il fotogramma; «Copia di nuovo» con l'identità esatta. Nessuna migrazione: bastano le tabelle di E1.
|
||||
- **Conversione della libreria** (`LibraryConversionWorker`): un file convertito accanto all'originale, mai al suo
|
||||
posto, con la riga di `media_conversion` sempre vera (anche dopo un arresto, un'eliminazione, un doppione, una
|
||||
ricostruzione, un'importazione); permesso di sottofondo di `LongWorkGate` che cede al lavoro in primo piano; una
|
||||
conversione alla volta nel processo; pausa con poco spazio o durante una sessione del motore; «Solo i nuovi» o
|
||||
«Anche i N già in libreria», per tipo; mai nella dimostrazione. Nuove chiavi
|
||||
`esportazione.libreria-formato-foto-dal` e `-video-dal` per sapere che cosa è «nuovo».
|
||||
- **Interfaccia**: menu dei formati con «con perdita» in Impostazioni, destinazioni e «Copia in…» («Cambia»); dialogo
|
||||
«Fotogrammi…» dal visualizzatore (all'istante del lettore, con anteprima) e dalla selezione; righe di copia e di
|
||||
conversione nel visualizzatore; conteggio dei convertiti nella conferma di eliminazione. Nessun controllo di E4.
|
||||
- **Revisione a più lenti**, due giri prima dell'unione: 16 rilievi confermati e corretti (`958cb71`), poi 4 sulle
|
||||
correzioni stesse (`2efb408`). I più seri: un JPEG progressivo fra circa 57 e 100 MP segnato «illeggibile» per sempre
|
||||
invece che «troppo grande»; «N in tutto» con N oltre la durata in ms perdeva istanti e spostava i nomi `_fNNN`; i video
|
||||
di durata ignota sfuggivano ai limiti di 1.000 e 20.000 fotogrammi; il rimuxaggio mostrava la coda nascosta di un
|
||||
video tagliato in fondo; «Riprova» riconvertiva in un formato spento; «Anche i N» di un tipo metteva in coda anche
|
||||
l'altro; uno zip lento si interrompeva dopo 60 s; due cambi rapidi delle impostazioni ne perdevano uno.
|
||||
- Documenti: SPECIFICA §4.10, §16 righe 28–38; righe del 28/11 in `decisioni.md`; guida `Esportazione.md`;
|
||||
schermate 15–21 rifatte e sei nuove (22–26) con il confronto in `docs/schermate/differenze.md`.
|
||||
- Controlli, su Windows: `dotnet build -warnaserror` 0 avvisi, 0 errori; `dotnet test tests/Febe.Tests` 3187
|
||||
superate, 110 ignorate (Chromium e Xvfb: solo nella CI), 0 non superate; `dotnet test tests/Febe.Tests.Windows` 24
|
||||
superate. Nella CI l'esecuzione 502 (prima delle correzioni) si è fermata 42 minuti con tutto il processo delle prove
|
||||
(anche le prove H.265 da 1 s), e due prove d'interfaccia nuove sono scadute in quella pausa; la stessa revisione
|
||||
nell'immagine della CI in locale è verde in 10 m 33 s e nel codice di E3 non c'è nulla che blocchi i thread. Se si
|
||||
ripete, il prossimo passo è limitare i Chromium paralleli nelle prove (`UiBrowser`) e aggiungere `--blame-hang`.
|
||||
La 510 è stata verde alla seconda prova: al primo giro la prova da capo a fondo con il sito di prova
|
||||
(`TheRealServerCollectsFromTheTestSite…`) ha passato i 90 s, come già una volta prima di E3 (2 min 10 s nella 107).
|
||||
Dopo l'unione la 518 di main è caduta nell'immagine su `APreviewPastItsBudgetSaysToUseTheFolderOfTheCopies`: con
|
||||
un tempo zero il fotogramma si annullava con un timer, che su una macchina carica scattava dopo la decodifica;
|
||||
ora un tempo zero annulla subito, come già in `VideoFrameDecoder` (ramo `correzione/fotogramma-senza-tempo`).
|
||||
- **Non verificato**:
|
||||
- le sette prove d'interfaccia nuove (`ExportInterfaceTests.Formats.cs`) girano solo nella CI di Linux; nessuna
|
||||
clicca «Scarica» o avvia un lavoro di fotogrammi o di video nella dimostrazione;
|
||||
- file veri grandi: foto da 40–100 MP, video oltre 4 GiB (`co64`), HEVC di telefoni veri; le prove usano media
|
||||
costruiti dalle prove;
|
||||
- senza prova loro: più edit di seguito, AAC di Matroska vecchio stile, Opus, tracce Matroska codificate, un flusso
|
||||
che comincia solo con CRA, una pausa in mezzo a un gruppo di fotogrammi, l'eliminazione di un account con file
|
||||
convertiti su un disco vero;
|
||||
- stessi byte fra versioni diverse di .NET (lo zlib del PNG è quello del runtime: scritto in `decisioni.md`);
|
||||
- nessuna schermata di: veste Docker, «Uno ogni k secondi», riga «Convertito in PNG» del visualizzatore, conferma
|
||||
di eliminazione, Resoconto; tema scuro e 390 px visti solo su prove scartate;
|
||||
- nella dimostrazione «con perdita» non compare in «Copia in…» (le foto di esempio sono tutte JPEG) e nessuna
|
||||
tessera ha il segno «Solo fotogrammi».
|
||||
- **Prossima tappa**: E4 «Video fermi» oppure E5 «Esportazione automatica», a scelta di Alberto.
|
||||
|
||||
**27 novembre 2026: tappa E2 «Copie esterne» dell'esportazione** (#58). Decisione di Alberto di oggi: «Esporta questo
|
||||
account» senza una scelta registrata (nessuna riga in `export_account`) è **acceso**. Le altre sei domande della tappa
|
||||
sono in §16 (righe 22–27) con la proposta adottata, da confermare.
|
||||
sono in §16 (righe 22–27) con la proposta adottata, confermata da Alberto il 29 novembre 2026.
|
||||
|
||||
- **Motore** (`src/Febe.Core/Export/`): destinazioni (cartella generale e cartelle degli account; la destinazione di un
|
||||
account è la sua cartella, se c'è, altrimenti la generale), controlli delle cartelle (mai dentro o sopra Libreria,
|
||||
@@ -138,7 +200,9 @@ la pagina Collegamento (11 prove d'interfaccia), ora `stored`, con la prova di s
|
||||
dell'immagine Docker manca `docs/`, quindi le due prove che lo leggono si saltano lì (`Repository.Docs`); la prova
|
||||
d'interfaccia di «Tutte le foto» sotto «Video» ora cerca con l'API un video in seconda posizione e accetta la copertina
|
||||
di un video mancante (la demo non ha i file dei video). Una prova di Collegamento in H.264 è caduta una volta
|
||||
(about:blank invece di `/benvenuto`) ed è passata alla ripetizione: la corsa è descritta in #67, non corretta.
|
||||
(about:blank invece di `/benvenuto`) ed è passata alla ripetizione: la corsa è descritta in #67, non corretta. Il 29
|
||||
novembre 2026 Alberto ha deciso come correggerla (aspettare il browser entro un limite, poi la pagina di accesso; riga
|
||||
in `decisioni.md`): non ancora fatto.
|
||||
L'esecuzione 448 di HEVC si è fermata per oltre 3 ore nelle prove senza uscita, oltre i 60 minuti del lavoro: con ogni
|
||||
probabilità il runner già malato, non le prove; la verifica di HEVC dopo il riavvio (464) ha fatto le prove in 17
|
||||
minuti.
|
||||
@@ -181,7 +245,7 @@ tachimetro, schermate 06, 11 e 14 rifatte, prova d'interfaccia a 860 × 900); do
|
||||
|
||||
Poi le correzioni della revisione di D1: la prova di accesso aspettava ancora `/libreria` per un «torna» mancante (ora
|
||||
`/dashboard`, letto dal modulo `return-path.js`); §6.0 e §6.5/§7.2 dicono proposte i 5 secondi di grazia in Docker e il
|
||||
posto su otto della coda, con le domande 20 e 21 di §16; §4.6 cita la conferma di «Elimina» com'è costruita e dice che
|
||||
posto su otto della coda, con le domande 20 e 21 di §16 (confermate da Alberto il 29 novembre 2026); §4.6 cita la conferma di «Elimina» com'è costruita e dice che
|
||||
in «In evidenza» l'interruttore manca e che «Tutte le foto» mostra solo i file in libreria; il messaggio d'esempio di §0,
|
||||
il rimando del mockup 06 e due righe di `prove-dal-vivo.md` non nominano più Attività.
|
||||
|
||||
@@ -197,11 +261,13 @@ il rimando del mockup 06 e due righe di `prove-dal-vivo.md` non nominano più At
|
||||
ai riferimenti e SVC è parziale; le schermate sono confrontate con i mockup a occhio. Niente su Instagram (regola 1).
|
||||
- **Domande per Alberto**:
|
||||
- i 5 secondi di grazia in Docker prima che lasciare la pagina del browser copi la sessione vanno bene (§16 domanda
|
||||
20)?
|
||||
20)? Sì, confermati da Alberto il 29 novembre 2026.
|
||||
- i pesi dei tipi 16, 8, 4, 2, 1 di «Cosa scaricare prima» (proposta, da tarare con la simulazione)?
|
||||
- le raccolte in evidenza subito dopo le storie nell'ordine predefinito (§16 domanda 19)?
|
||||
- le raccolte in evidenza subito dopo le storie nell'ordine predefinito (§16 domanda 19)? Sì, confermate da Alberto il
|
||||
29 novembre 2026.
|
||||
- nella coda dei file basta il posto su otto al file più vecchio (nessun file aspetta per sempre) o serve un vero
|
||||
minimo per tipo (oggi un tipo trovato dopo un arretrato più vecchio aspetta che finisca; §16 domanda 21)?
|
||||
minimo per tipo (oggi un tipo trovato dopo un arretrato più vecchio aspetta che finisca; §16 domanda 21)? Basta il
|
||||
posto su otto, confermato da Alberto il 29 novembre 2026.
|
||||
- un HEIC danneggiato ha solo la tessera neutra e non è mai segnato «File danneggiato o incompleto»: va bene?
|
||||
- i due MP4 minuscoli di `tools/Febe.SitoDiProva/Risorse` sono stati generati una volta con ffmpeg: rifarli con lo
|
||||
scrittore MP4 di casa o tenerli?
|
||||
@@ -660,7 +726,8 @@ protezione di `main` sono in `docs/processo.md`.
|
||||
3. **Windows**: C5.2–C5.5 (C5.1, l'accesso con l'account di prova, è riuscito il 20/10), S2 con la finestra ridotta a
|
||||
icona e con lo schermo bloccato, C2 (installatore della 0.1.2 su un Windows pulito). **Docker su Unraid**: S3–S6 nel contenitore
|
||||
vero.
|
||||
4. Le domande aperte di §16 (sono state adottate le proposte della terza colonna, vedi `docs/decisioni.md`).
|
||||
4. Le domande aperte di §16 (sono state adottate le proposte della terza colonna, vedi `docs/decisioni.md`); quelle
|
||||
delle righe 19–38 le ha confermate Alberto il 29 novembre 2026.
|
||||
5. **Tag `v0.1.2`** sul commit di unione di `rilascio/0.1.2` in `main`: `git tag -a v0.1.2 -m "Febe 0.1.2"` e
|
||||
`git push origin v0.1.2` (`docs/processo.md`, «Rilasci»). Poi su Unraid basta `:latest`. `REGISTRY_TOKEN` c'è dal
|
||||
26/10; il flusso del tag `v0.1.1` non serve più rilanciarlo: pubblicherebbe la 0.1.1, senza la lettura di Instagram.
|
||||
@@ -671,12 +738,9 @@ protezione di `main` sono in `docs/processo.md`.
|
||||
7. **Pulizia**: la prima vera è girata il 26/10 (esecuzione 56, store classico) e ha tolto solo immagini che nessun
|
||||
contenitore usava; da guardare, se serve, il suo registro. Dal lunedì 2/11 toglie anche le `:sha-` del registro oltre
|
||||
le 10 più recenti.
|
||||
8. Da decidere:
|
||||
- dopo ogni esecuzione la cache di costruzione si toglie solo se nessuno la usa da 24 ore (`--filter until=24h`).
|
||||
Senza filtro, a ogni push se ne andrebbe anche quella appena usata dagli altri progetti; per cambiare basta togliere
|
||||
il filtro in `pulizia-docker.sh penzolanti`;
|
||||
- gli script di shell di `.gitea/` e `installer/` hanno i commenti in italiano, contro «codice e commenti in
|
||||
inglese»: o un'eccezione in `docs/decisioni.md`, o una traduzione in un ramo a parte.
|
||||
8. Da decidere: dopo ogni esecuzione la cache di costruzione si toglie solo se nessuno la usa da 24 ore
|
||||
(`--filter until=24h`). Senza filtro, a ogni push se ne andrebbe anche quella appena usata dagli altri progetti; per
|
||||
cambiare basta togliere il filtro in `pulizia-docker.sh penzolanti`.
|
||||
|
||||
## Rilievi aperti (20 ottobre)
|
||||
|
||||
@@ -709,8 +773,6 @@ protezione di `main` sono in `docs/processo.md`.
|
||||
|
||||
## Rilievi aperti (21 ottobre)
|
||||
|
||||
- Le note della release scritte da `rilascio.yml` senza immagine dicono «`:latest` resta sulla versione precedente», ma
|
||||
sul registro un'immagine precedente non c'è mai stata. Da riformulare per il caso della prima pubblicazione.
|
||||
- Un solo timeout di `OpenAsync` all'apertura di `/browser` (`AfterHoFinitoLeavingTheBrowserPageChangesNothingMore`) in
|
||||
migliaia di esecuzioni delle prove d'interfaccia, senza causa trovata. Se ricompare nella CI, va fatto dire a
|
||||
`OpenAsync` quale condizione mancava.
|
||||
@@ -718,6 +780,9 @@ protezione di `main` sono in `docs/processo.md`.
|
||||
|
||||
## Rimandato, e perché
|
||||
|
||||
- #67: deciso il 29 novembre 2026 (subito dopo «Scollega», con l'indirizzo della pagina sconosciuto, aspettare il
|
||||
browser entro un limite, poi la pagina di accesso), non ancora fatto: oggi Febe scrive «Alberto usa il browser» e non
|
||||
apre nulla. Da fare in un ramo a parte, con la sua prova.
|
||||
- Via `HttpClient` verso il CDN (§6.5 punto 3): dipende da H7.
|
||||
- Riconoscitore di 4K Stogram vero e lettura di `stogram.sqlite`: servono i nomi veri dei file (domanda 4).
|
||||
- M9 (desktop collegato a un Febe remoto, seconda lingua): facoltativa.
|
||||
@@ -1,16 +1,16 @@
|
||||
#!/usr/bin/env bash
|
||||
# Febe per Windows: pubblica Febe.exe in un file solo e ne fa il programma di installazione e lo zip portabile.
|
||||
# Febe for Windows: publishes Febe.exe as a single file and makes the installer and the portable zip from it.
|
||||
#
|
||||
# installer/costruisci.sh [versione]
|
||||
#
|
||||
# Gira su Linux (CI e rilascio) come su Windows con bash: serve solo il .NET SDK 10. Nessun altro programma: il
|
||||
# programma di installazione è nostro (src/Febe.Installer) e lo stesso progetto, compilato per il sistema che lo
|
||||
# costruisce, fa il pacchetto, lo controlla e scrive lo zip. La versione, se non la si passa, è quella di
|
||||
# Directory.Build.props (il tag deve coincidere).
|
||||
# Risultato in out/:
|
||||
# Febe-Setup-<versione>.exe installazione per l'utente, senza permessi di amministratore
|
||||
# Febe-<versione>-portabile.zip Febe.exe e LEGGIMI.txt, da copiare dove si vuole
|
||||
# Ognuno deve restare sotto i 100 MB (limite degli allegati di Gitea).
|
||||
# Runs on Linux (CI and release) as on Windows with bash: only the .NET SDK 10 is needed. No other program: the
|
||||
# installer is our own (src/Febe.Installer) and the same project, built for the system that builds it, makes the
|
||||
# package, checks it and writes the zip. The version, if not given, is the one in Directory.Build.props (the tag must
|
||||
# match).
|
||||
# Result in out/:
|
||||
# Febe-Setup-<versione>.exe per-user installation, without administrator rights
|
||||
# Febe-<versione>-portabile.zip Febe.exe and LEGGIMI.txt, to copy wherever you like
|
||||
# Each must stay under 100 MB (the Gitea attachment limit).
|
||||
set -euo pipefail
|
||||
|
||||
radice="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
||||
@@ -36,7 +36,7 @@ dotnet publish src/Febe.Desktop/Febe.Desktop.csproj -c Release -r win-x64 --self
|
||||
-p:PublishSingleFile=true -p:IncludeNativeLibrariesForSelfExtract=true -p:EnableCompressionInSingleFile=true \
|
||||
-p:Version="$versione" -nologo -o "$pubblicazione"
|
||||
|
||||
# Un file solo: niente accanto all'eseguibile.
|
||||
# A single file: nothing next to the executable.
|
||||
solo_un_file() {
|
||||
local cartella="$1" nome="$2" altri
|
||||
altri="$(find "$cartella" -mindepth 1 ! -name "$nome")"
|
||||
@@ -49,7 +49,7 @@ solo_un_file() {
|
||||
solo_un_file "$pubblicazione" Febe.exe
|
||||
|
||||
echo "== Programma di installazione (win-x64, un file solo, ridotto)"
|
||||
# Le proprietà della pubblicazione (autosufficiente, un file solo, trimming, compressione) sono nel progetto.
|
||||
# The publish properties (self-contained, single file, trimming, compression) are in the project.
|
||||
dotnet publish src/Febe.Installer/Febe.Installer.csproj -c Release -r win-x64 \
|
||||
-p:Version="$versione" -nologo -o "$installatore"
|
||||
solo_un_file "$installatore" Febe.Installer.exe
|
||||
|
||||
@@ -178,8 +178,8 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
|
||||
/// <summary>
|
||||
/// How long after Alberto left the page of the browser in Docker (<see cref="LeavePageAsync"/>, or its remote view
|
||||
/// closed by the page: <see cref="RemoteViewClosed"/>) no view may open again before Febe takes it as letting go of
|
||||
/// the browser (answer of 25 November 2026, proposal of 5 seconds): a reload of the page opens its view again well
|
||||
/// before. Read at every look; tests shorten it.
|
||||
/// the browser (answer of 25 November 2026; the 5 seconds confirmed by Alberto on 29 November 2026, spec §16
|
||||
/// question 20): a reload of the page opens its view again well before. Read at every look; tests shorten it.
|
||||
/// </summary>
|
||||
public TimeSpan PageLeaveGrace { get; set; } = TimeSpan.FromSeconds(5);
|
||||
|
||||
|
||||
@@ -14,6 +14,7 @@ using Febe.Core.Engine;
|
||||
using Febe.Core.Export;
|
||||
using Febe.Core.Import;
|
||||
using Febe.Core.Library;
|
||||
using Febe.Core.Library.Conversion;
|
||||
using Febe.Core.Security;
|
||||
using Febe.Core.Storage;
|
||||
using Febe.Data;
|
||||
@@ -194,9 +195,12 @@ public sealed class FebeApp : IAsyncDisposable
|
||||
DataFolder = data.Root,
|
||||
Gate = longWork,
|
||||
});
|
||||
var idleConversion = new LibraryConversionWorker(new LibraryConversionEnvironment { Storage = Database, Layout = () => library.Layout, Clock = Clock, Gate = longWork });
|
||||
await StartWebAsync(hooks, services =>
|
||||
{
|
||||
services.AddSingleton(longWork);
|
||||
services.AddSingleton(idleConversion);
|
||||
services.AddSingleton(new LibraryConversionQueue(Database, Clock));
|
||||
services.AddSingleton(ExportRootOptions.Docker(Path.Combine(_temporaryFolder, "esporta"), declared: false));
|
||||
services.AddSingleton<IFebeStorage>(Database);
|
||||
services.AddSingleton(library);
|
||||
@@ -336,12 +340,28 @@ public sealed class FebeApp : IAsyncDisposable
|
||||
_telegram = new TelegramClient(hooks.TelegramHandler);
|
||||
var telegramChannel = new TelegramAlertChannel(_telegram);
|
||||
|
||||
// The conversion for the library (tappa E3, spec §4.10): one worker, started below in the background; it yields
|
||||
// to import, copies and rebuild through the gate and never runs during an engine session. Never in the demo.
|
||||
var sessionState = new RuntimeSessionState(services.Runtime);
|
||||
var conversion = new LibraryConversionWorker(new LibraryConversionEnvironment
|
||||
{
|
||||
Storage = Database,
|
||||
Layout = () => library.Layout,
|
||||
Clock = Clock,
|
||||
Gate = longWork,
|
||||
Session = sessionState,
|
||||
FreeSpace = hooks.FreeSpace ?? new DriveFreeSpaceProbe(),
|
||||
Log = message => Log.Write(LogLevel.Warning, "conversione", message),
|
||||
});
|
||||
|
||||
await StartWebAsync(hooks, s =>
|
||||
{
|
||||
s.AddSingleton(longWork);
|
||||
s.AddSingleton(conversion);
|
||||
s.AddSingleton(new LibraryConversionQueue(Database, Clock));
|
||||
s.AddSingleton(exportRoot);
|
||||
s.AddSingleton<IExportDisk>(hooks.ExportDisk ?? new SystemExportDisk(exportRoot.Mounts));
|
||||
s.AddSingleton<IEngineSessionState>(new RuntimeSessionState(services.Runtime));
|
||||
s.AddSingleton<IEngineSessionState>(sessionState);
|
||||
s.AddSingleton<IFebeStorage>(Database);
|
||||
s.AddSingleton(library);
|
||||
s.AddSingleton<IClock>(Clock);
|
||||
@@ -398,6 +418,7 @@ public sealed class FebeApp : IAsyncDisposable
|
||||
InBackground(() => BackupLoopAsync(new DailyBackup(Database, Clock, data.Backups), lifetime));
|
||||
InBackground(() => BringUpBrowserAsync(ingest, staging, services, engine, runner, search, lifetime));
|
||||
InBackground(() => Alerts.WatchDiskSpaceAsync(lifetime));
|
||||
InBackground(() => conversion.RunAsync(lifetime));
|
||||
}
|
||||
|
||||
/// <summary>Runs <paramref name="work"/> in the background; the stop waits for it.</summary>
|
||||
|
||||
@@ -13,19 +13,38 @@ public enum LongWorkKind
|
||||
|
||||
/// <summary>«Ricostruisci il database dalla libreria» (spec §8.5).</summary>
|
||||
Rebuild,
|
||||
|
||||
/// <summary>
|
||||
/// The conversion for the library (tappa E3, spec §4.10): held only as a <see cref="LongWorkGate.BackgroundLease"/>,
|
||||
/// which any of the others pre-empts.
|
||||
/// </summary>
|
||||
LibraryConversion,
|
||||
|
||||
/// <summary>A zip of 21 to 500 frames being prepared for «Scarica» (tappa E3, D14).</summary>
|
||||
FrameDownload,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Lets only one of import, export and rebuild run at a time, in both directions. One instance is shared by the whole
|
||||
/// process (the composition registers it once). A lease is taken when a job starts and disposed when it ends; disposing
|
||||
/// it twice releases nothing more.
|
||||
/// Lets only one of import, export, rebuild and frame download run at a time, in both directions. One instance is
|
||||
/// shared by the whole process (the composition registers it once). A lease is taken when a job starts and disposed when
|
||||
/// it ends; disposing it twice releases nothing more.
|
||||
/// <para>
|
||||
/// The conversion for the library takes a <see cref="BackgroundLease"/> instead (tappa E3, WP2.1): it runs only while
|
||||
/// no foreground lease is held, and a foreground <see cref="TryEnter"/> pre-empts it. Outside a commit the conversion
|
||||
/// only reads an original and writes its own temporary file, so it simply stops; a commit (one rename and one
|
||||
/// transaction) is waited for, at most <see cref="CommitWait"/>.
|
||||
/// </para>
|
||||
/// </summary>
|
||||
public sealed class LongWorkGate
|
||||
{
|
||||
private readonly Lock _lock = new();
|
||||
private Lease? _holder;
|
||||
private BackgroundLease? _background;
|
||||
|
||||
/// <summary>Who holds the gate, or null when it is free.</summary>
|
||||
/// <summary>How long a foreground <see cref="TryEnter"/> waits for a commit of the background work to end.</summary>
|
||||
public TimeSpan CommitWait { get; init; } = TimeSpan.FromSeconds(10);
|
||||
|
||||
/// <summary>Who holds the gate in the foreground, or null when it is free. The background lease does not count.</summary>
|
||||
public LongWorkKind? Busy
|
||||
{
|
||||
get
|
||||
@@ -37,12 +56,34 @@ public sealed class LongWorkGate
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>True while the background lease (the conversion for the library) is held and not pre-empted.</summary>
|
||||
public bool BackgroundRunning
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
return _background is not null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Takes the gate for <paramref name="kind"/>. False, with <paramref name="busyWith"/> set, when another job (of any
|
||||
/// kind, the same one included) holds it.
|
||||
/// kind, the same one included) holds it in the foreground. A background lease is pre-empted: its token is
|
||||
/// cancelled and, if it is committing a file, the commit is waited for (at most <see cref="CommitWait"/>; past it,
|
||||
/// false with <see cref="LongWorkKind.LibraryConversion"/>).
|
||||
/// </summary>
|
||||
public bool TryEnter(LongWorkKind kind, [NotNullWhen(true)] out IDisposable? lease, out LongWorkKind? busyWith)
|
||||
{
|
||||
if (kind == LongWorkKind.LibraryConversion)
|
||||
{
|
||||
throw new ArgumentException("La conversione della libreria prende il cancello solo in sottofondo.", nameof(kind));
|
||||
}
|
||||
|
||||
Lease taken;
|
||||
BackgroundLease? preempted;
|
||||
bool committing;
|
||||
lock (_lock)
|
||||
{
|
||||
if (_holder is { } holder)
|
||||
@@ -52,10 +93,47 @@ public sealed class LongWorkGate
|
||||
return false;
|
||||
}
|
||||
|
||||
var taken = new Lease(this, kind);
|
||||
taken = new Lease(this, kind);
|
||||
_holder = taken;
|
||||
lease = taken;
|
||||
busyWith = null;
|
||||
preempted = _background;
|
||||
_background = null;
|
||||
committing = preempted?.MarkPreempted() ?? false;
|
||||
}
|
||||
|
||||
if (preempted is not null)
|
||||
{
|
||||
// Outside the lock: the token's callbacks run synchronously and may take the gate's lock.
|
||||
preempted.CancelPreempted();
|
||||
if (committing && !preempted.WaitForCommit(CommitWait))
|
||||
{
|
||||
taken.Dispose();
|
||||
lease = null;
|
||||
busyWith = LongWorkKind.LibraryConversion;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
lease = taken;
|
||||
busyWith = null;
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Takes the gate in the background for the conversion for the library. False while any foreground lease, or
|
||||
/// another background lease, is held.
|
||||
/// </summary>
|
||||
public bool TryEnterBackground([NotNullWhen(true)] out BackgroundLease? lease)
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
if (_holder is not null || _background is not null)
|
||||
{
|
||||
lease = null;
|
||||
return false;
|
||||
}
|
||||
|
||||
lease = new BackgroundLease(this);
|
||||
_background = lease;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -68,14 +146,20 @@ public sealed class LongWorkGate
|
||||
(LongWorkKind.Rebuild, LongWorkKind.Rebuild) => "La ricostruzione è già in corso.",
|
||||
(_, LongWorkKind.Import) => $"C'è un'importazione al lavoro: aspetta che finisca o interrompila, poi {Verb(wanted)}.",
|
||||
(_, LongWorkKind.Export) => $"C'è una copia nelle cartelle esterne al lavoro: aspetta che finisca o interrompila, poi {Verb(wanted)}.",
|
||||
_ => "La ricostruzione del database è in corso: aspetta che finisca.",
|
||||
(_, LongWorkKind.LibraryConversion) => "La conversione della libreria sta salvando un file: riprova fra un attimo.",
|
||||
(_, LongWorkKind.FrameDownload) => $"Si sta preparando uno zip di fotogrammi: aspetta che finisca, poi {Verb(wanted)}.",
|
||||
(_, LongWorkKind.Rebuild) => "La ricostruzione del database è in corso: aspetta che finisca.",
|
||||
_ => "Un altro lavoro lungo è in corso: aspetta che finisca.",
|
||||
};
|
||||
|
||||
private static string Verb(LongWorkKind kind) => kind switch
|
||||
{
|
||||
LongWorkKind.Import => "importa",
|
||||
LongWorkKind.Export => "copia",
|
||||
_ => "ricostruisci",
|
||||
LongWorkKind.Rebuild => "ricostruisci",
|
||||
LongWorkKind.FrameDownload => "scarica i fotogrammi",
|
||||
LongWorkKind.LibraryConversion => "converti",
|
||||
_ => "riprova",
|
||||
};
|
||||
|
||||
private void Release(Lease lease)
|
||||
@@ -89,6 +173,17 @@ public sealed class LongWorkGate
|
||||
}
|
||||
}
|
||||
|
||||
private void Release(BackgroundLease lease)
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
if (ReferenceEquals(_background, lease))
|
||||
{
|
||||
_background = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class Lease(LongWorkGate gate, LongWorkKind kind) : IDisposable
|
||||
{
|
||||
private int _disposed;
|
||||
@@ -103,4 +198,112 @@ public sealed class LongWorkGate
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The background lease of the conversion for the library. <see cref="Preempted"/> is cancelled when a foreground
|
||||
/// job wants the gate; a commit (<see cref="TryBeginCommit"/>) is waited for by that job, and none begins once
|
||||
/// pre-empted or disposed.
|
||||
/// </summary>
|
||||
public sealed class BackgroundLease : IDisposable
|
||||
{
|
||||
private readonly LongWorkGate _gate;
|
||||
|
||||
// Neither is disposed: a foreground TryEnter may cancel or wait on them after the lease ended, and without a
|
||||
// timer or a wait handle asked for they hold nothing but memory.
|
||||
private readonly CancellationTokenSource _preempted = new();
|
||||
private readonly ManualResetEventSlim _noCommit = new(initialState: true);
|
||||
private bool _isPreempted;
|
||||
private bool _committing;
|
||||
private int _disposed;
|
||||
|
||||
internal BackgroundLease(LongWorkGate gate)
|
||||
{
|
||||
_gate = gate;
|
||||
Preempted = _preempted.Token;
|
||||
}
|
||||
|
||||
/// <summary>Cancelled when a foreground job takes the gate.</summary>
|
||||
public CancellationToken Preempted { get; }
|
||||
|
||||
/// <summary>True once a foreground job asked for the gate (or the lease ended).</summary>
|
||||
public bool IsPreempted
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (_gate._lock)
|
||||
{
|
||||
return _isPreempted;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Begins a commit (a rename and its record) that a foreground job waits for. False once pre-empted or disposed,
|
||||
/// or while another commit of this lease runs: then nothing may be renamed or recorded.
|
||||
/// </summary>
|
||||
public bool TryBeginCommit([NotNullWhen(true)] out IDisposable? commit)
|
||||
{
|
||||
lock (_gate._lock)
|
||||
{
|
||||
if (_isPreempted || _disposed != 0 || _committing)
|
||||
{
|
||||
commit = null;
|
||||
return false;
|
||||
}
|
||||
|
||||
_committing = true;
|
||||
_noCommit.Reset();
|
||||
commit = new Commit(this);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (Interlocked.Exchange(ref _disposed, 1) != 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
EndCommit();
|
||||
_gate.Release(this);
|
||||
lock (_gate._lock)
|
||||
{
|
||||
_isPreempted = true;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Under the gate's lock: marks the lease pre-empted and tells whether a commit is running.</summary>
|
||||
internal bool MarkPreempted()
|
||||
{
|
||||
_isPreempted = true;
|
||||
return _committing;
|
||||
}
|
||||
|
||||
internal void CancelPreempted() => _preempted.Cancel();
|
||||
|
||||
internal bool WaitForCommit(TimeSpan timeout) => _noCommit.Wait(timeout);
|
||||
|
||||
private void EndCommit()
|
||||
{
|
||||
lock (_gate._lock)
|
||||
{
|
||||
_committing = false;
|
||||
_noCommit.Set();
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class Commit(BackgroundLease lease) : IDisposable
|
||||
{
|
||||
private int _disposed;
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (Interlocked.Exchange(ref _disposed, 1) == 0)
|
||||
{
|
||||
lease.EndCommit();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,12 @@ namespace Febe.Core.Codecs.Containers;
|
||||
/// </summary>
|
||||
public static class ContainerReader
|
||||
{
|
||||
/// <summary>
|
||||
/// A «now» far in the future, for readers that must not depend on the clock (frames, remux): every plausible date
|
||||
/// in the file is accepted.
|
||||
/// </summary>
|
||||
internal static readonly DateTimeOffset AnyDate = new(9000, 1, 1, 0, 0, 0, TimeSpan.Zero);
|
||||
|
||||
/// <summary>The largest sample read into memory: an 8K frame of H.264 at its highest level stays far below.</summary>
|
||||
public const int MaxSampleSize = 64 * 1024 * 1024;
|
||||
|
||||
|
||||
@@ -39,6 +39,7 @@ public static class IsoBmffReader
|
||||
long position = 0;
|
||||
Span<byte> header = stackalloc byte[16];
|
||||
Movie? movie = null;
|
||||
string? brand = null;
|
||||
var pending = new List<(long Start, byte[] Body)>();
|
||||
for (var i = 0; i < MaxTopLevelBoxes && position + 8 <= length; i++)
|
||||
{
|
||||
@@ -75,6 +76,12 @@ public static class IsoBmffReader
|
||||
}
|
||||
|
||||
var type = header.Slice(4, 4);
|
||||
if (type.SequenceEqual("ftyp"u8) && brand is null && size - headerSize >= 4)
|
||||
{
|
||||
stream.ReadExactly(header[..4]); // the size field is read already: its bytes can hold the brand
|
||||
brand = System.Text.Encoding.Latin1.GetString(header[..4]);
|
||||
}
|
||||
|
||||
if (type.SequenceEqual("moov"u8) && movie is null)
|
||||
{
|
||||
movie = ParseMoov(ReadBody(stream, position + headerSize, size - headerSize), now, samples, length);
|
||||
@@ -112,7 +119,7 @@ public static class IsoBmffReader
|
||||
throw new ContainerException("Manca il box moov.");
|
||||
}
|
||||
|
||||
return movie.Build();
|
||||
return movie.Build(brand);
|
||||
}
|
||||
|
||||
private static byte[] ReadBody(Stream stream, long offset, long count)
|
||||
@@ -141,7 +148,11 @@ public static class IsoBmffReader
|
||||
case "mvhd":
|
||||
movie.ParseMvhd(body, now);
|
||||
break;
|
||||
case "udta" or "meta":
|
||||
movie.HasUserData = true;
|
||||
break;
|
||||
case "trak":
|
||||
movie.TrackCount++;
|
||||
try
|
||||
{
|
||||
movie.ParseTrak(moov, start, count);
|
||||
@@ -269,6 +280,12 @@ public static class IsoBmffReader
|
||||
internal byte[]? Hvcc;
|
||||
internal byte[]? Asc;
|
||||
internal long EditOffset;
|
||||
internal bool HasEdits;
|
||||
internal long EmptyEditMovie;
|
||||
internal long EditSegmentMovie;
|
||||
internal int EditCount;
|
||||
internal string? Language;
|
||||
internal int ObjectType;
|
||||
internal List<MediaSample> Samples = [];
|
||||
internal long FragmentTime = -1;
|
||||
}
|
||||
@@ -279,6 +296,7 @@ public static class IsoBmffReader
|
||||
internal readonly Dictionary<uint, (uint Duration, uint Size, uint Flags)> TrackDefaults = [];
|
||||
private readonly List<Track> tracks = [];
|
||||
private DateTimeOffset? created;
|
||||
private DateTimeOffset? modified;
|
||||
private long timescale;
|
||||
private long duration;
|
||||
|
||||
@@ -288,6 +306,12 @@ public static class IsoBmffReader
|
||||
/// <summary>fragment_duration of the <c>mehd</c> box, in movie units; 0 when absent.</summary>
|
||||
internal long FragmentDuration;
|
||||
|
||||
/// <summary>The <c>trak</c> boxes of the movie, of every kind.</summary>
|
||||
internal int TrackCount;
|
||||
|
||||
/// <summary>True when the movie has a <c>udta</c> or <c>meta</c> box.</summary>
|
||||
internal bool HasUserData;
|
||||
|
||||
/// <summary>A fragmented movie whose headers give no duration: only its fragments tell it.</summary>
|
||||
internal bool NeedsFragmentsForDuration =>
|
||||
Fragmented && duration <= 0 && FragmentDuration <= 0 && !tracks.Exists(t => t.Handler == "vide" && t.Duration > 0);
|
||||
@@ -295,15 +319,18 @@ public static class IsoBmffReader
|
||||
internal void ParseMvhd(ReadOnlySpan<byte> body, DateTimeOffset now)
|
||||
{
|
||||
ulong creation;
|
||||
ulong modification;
|
||||
if (body[0] == 1)
|
||||
{
|
||||
creation = BinaryPrimitives.ReadUInt64BigEndian(body[4..]);
|
||||
modification = BinaryPrimitives.ReadUInt64BigEndian(body[12..]);
|
||||
timescale = BinaryPrimitives.ReadUInt32BigEndian(body[20..]);
|
||||
duration = (long)Math.Min(BinaryPrimitives.ReadUInt64BigEndian(body[24..]), long.MaxValue);
|
||||
}
|
||||
else
|
||||
{
|
||||
creation = BinaryPrimitives.ReadUInt32BigEndian(body[4..]);
|
||||
modification = BinaryPrimitives.ReadUInt32BigEndian(body[8..]);
|
||||
timescale = BinaryPrimitives.ReadUInt32BigEndian(body[12..]);
|
||||
duration = BinaryPrimitives.ReadUInt32BigEndian(body[16..]);
|
||||
if (duration == uint.MaxValue)
|
||||
@@ -312,14 +339,22 @@ public static class IsoBmffReader
|
||||
}
|
||||
}
|
||||
|
||||
if (creation > 0 && creation < 400UL * 366 * 86400)
|
||||
created = Plausible(creation, now);
|
||||
modified = Plausible(modification, now);
|
||||
}
|
||||
|
||||
private static DateTimeOffset? Plausible(ulong seconds, DateTimeOffset now)
|
||||
{
|
||||
if (seconds > 0 && seconds < 400UL * 366 * 86400)
|
||||
{
|
||||
var instant = Epoch1904.AddSeconds(creation);
|
||||
var instant = Epoch1904.AddSeconds(seconds);
|
||||
if (instant >= Earliest && instant <= now.AddDays(1))
|
||||
{
|
||||
created = instant;
|
||||
return instant;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
internal void ParseTrak(byte[] data, int start, int count)
|
||||
@@ -365,15 +400,34 @@ public static class IsoBmffReader
|
||||
var v1 = body[0] == 1;
|
||||
var entries = BinaryPrimitives.ReadUInt32BigEndian(body[4..]);
|
||||
var offset = 8;
|
||||
var leading = true;
|
||||
for (var i = 0; i < entries && i < 16; i++)
|
||||
{
|
||||
var segment = v1 ? (long)Math.Min(BinaryPrimitives.ReadUInt64BigEndian(body[offset..]), long.MaxValue / 4) : BinaryPrimitives.ReadUInt32BigEndian(body[offset..]);
|
||||
long mediaTime = v1 ? BinaryPrimitives.ReadInt64BigEndian(body[(offset + 8)..]) : BinaryPrimitives.ReadInt32BigEndian(body[(offset + 4)..]);
|
||||
var rate = BinaryPrimitives.ReadInt16BigEndian(body[(offset + (v1 ? 16 : 8))..]);
|
||||
offset += v1 ? 20 : 12;
|
||||
if (mediaTime >= 0)
|
||||
if (leading && mediaTime < 0)
|
||||
{
|
||||
track.EditOffset = mediaTime; // the first non-empty edit: media time shown at presentation zero
|
||||
return;
|
||||
track.EmptyEditMovie += segment; // a delayed start
|
||||
continue;
|
||||
}
|
||||
|
||||
if (leading)
|
||||
{
|
||||
leading = false;
|
||||
track.HasEdits = true;
|
||||
track.EditOffset = mediaTime; // the first non-empty edit: media time shown at presentation zero
|
||||
track.EditSegmentMovie = segment; // and how long it is shown (movie units; 0: to the end)
|
||||
}
|
||||
|
||||
// A rate other than 1 (a slowed or still segment) is not an ordinary edit either.
|
||||
track.EditCount += rate == 1 ? 1 : 2;
|
||||
}
|
||||
|
||||
if (entries > 16)
|
||||
{
|
||||
track.EditCount += 2;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -397,6 +451,7 @@ public static class IsoBmffReader
|
||||
track.Duration = d == uint.MaxValue ? 0 : d;
|
||||
}
|
||||
|
||||
track.Language = Language(body[0] == 1 ? body[32..] : body[20..]);
|
||||
break;
|
||||
case "hdlr":
|
||||
track.Handler = System.Text.Encoding.Latin1.GetString(body.Slice(8, 4));
|
||||
@@ -478,6 +533,39 @@ public static class IsoBmffReader
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The ISO 639-2/T code packed in an <c>mdhd</c> (three letters of five bits each); null for «und», for a
|
||||
/// QuickTime Macintosh language code (below 0x400) or for a damaged value.
|
||||
/// </summary>
|
||||
private static string? Language(ReadOnlySpan<byte> field)
|
||||
{
|
||||
if (field.Length < 2)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var packed = BinaryPrimitives.ReadUInt16BigEndian(field) & 0x7FFF;
|
||||
if (packed < 0x400)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
Span<char> code = stackalloc char[3];
|
||||
for (var i = 0; i < 3; i++)
|
||||
{
|
||||
var letter = (packed >> (10 - (5 * i))) & 0x1F;
|
||||
if (letter is < 1 or > 26)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
code[i] = (char)('a' + letter - 1);
|
||||
}
|
||||
|
||||
var text = new string(code);
|
||||
return text == "und" ? null : text;
|
||||
}
|
||||
|
||||
private static void ParseStsd(byte[] data, int start, int count, Track track)
|
||||
{
|
||||
if (count < 16)
|
||||
@@ -524,16 +612,31 @@ public static class IsoBmffReader
|
||||
{
|
||||
if (t == "esds")
|
||||
{
|
||||
track.Asc = EsdsConfig(data.AsSpan(s, c));
|
||||
(track.ObjectType, track.Asc) = EsdsConfig(data.AsSpan(s, c));
|
||||
}
|
||||
else if (t == "wave" && track.ObjectType == 0)
|
||||
{
|
||||
// QuickTime keeps the esds of an mp4a entry inside a wave box (QTFF, sound sample description).
|
||||
foreach (var (wt, ws, wc) in Children(data, s, c))
|
||||
{
|
||||
if (wt == "esds")
|
||||
{
|
||||
(track.ObjectType, track.Asc) = EsdsConfig(data.AsSpan(ws, wc));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The DecoderSpecificInfo of an <c>esds</c> box (ISO/IEC 14496-1 descriptors).</summary>
|
||||
private static byte[]? EsdsConfig(ReadOnlySpan<byte> body)
|
||||
/// <summary>
|
||||
/// The objectTypeIndication (0 when absent) and the DecoderSpecificInfo of an <c>esds</c> box (ISO/IEC 14496-1
|
||||
/// descriptors).
|
||||
/// </summary>
|
||||
private static (int ObjectType, byte[]? Config) EsdsConfig(ReadOnlySpan<byte> body)
|
||||
{
|
||||
var objectType = 0;
|
||||
var p = 4; // version and flags
|
||||
while (p + 2 <= body.Length)
|
||||
{
|
||||
@@ -555,7 +658,7 @@ public static class IsoBmffReader
|
||||
{
|
||||
if (p + 3 > body.Length)
|
||||
{
|
||||
return null;
|
||||
return (objectType, null);
|
||||
}
|
||||
|
||||
var flags = body[p + 2];
|
||||
@@ -569,7 +672,7 @@ public static class IsoBmffReader
|
||||
{
|
||||
if (p >= body.Length)
|
||||
{
|
||||
return null;
|
||||
return (objectType, null);
|
||||
}
|
||||
|
||||
p += 1 + body[p];
|
||||
@@ -583,18 +686,23 @@ public static class IsoBmffReader
|
||||
break;
|
||||
}
|
||||
|
||||
case 0x04: // DecoderConfigDescriptor: its fixed fields, then the children
|
||||
case 0x04: // DecoderConfigDescriptor: objectTypeIndication and the other fixed fields, then the children
|
||||
if (p < body.Length)
|
||||
{
|
||||
objectType = body[p];
|
||||
}
|
||||
|
||||
p += 13;
|
||||
break;
|
||||
case 0x05:
|
||||
return p + length <= body.Length ? body.Slice(p, length).ToArray() : null;
|
||||
return (objectType, p + length <= body.Length ? body.Slice(p, length).ToArray() : null);
|
||||
default:
|
||||
p += length;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
return (objectType, null);
|
||||
}
|
||||
|
||||
private void BuildSamples(Track track, byte[] stts, byte[]? ctts, byte[] stsc, byte[] stsz, bool stz2, byte[] stco, bool co64, byte[]? stss)
|
||||
@@ -903,7 +1011,7 @@ public static class IsoBmffReader
|
||||
return total;
|
||||
}
|
||||
|
||||
internal MediaContainer Build()
|
||||
internal MediaContainer Build(string? brand)
|
||||
{
|
||||
var video = tracks.Find(t => t.Handler == "vide");
|
||||
var audio = tracks.Find(t => t.Handler == "soun");
|
||||
@@ -932,6 +1040,11 @@ public static class IsoBmffReader
|
||||
AvcConfiguration = video.Avcc,
|
||||
HevcConfiguration = video.Hvcc,
|
||||
Samples = video.Samples,
|
||||
EditMediaTime = video.HasEdits ? video.EditOffset : null,
|
||||
EmptyEditDuration = EmptyEdit(video),
|
||||
EditSegmentDuration = EditSegment(video),
|
||||
EditCount = video.EditCount,
|
||||
Language = video.Language,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -942,6 +1055,8 @@ public static class IsoBmffReader
|
||||
{
|
||||
Codec = audio.Format switch
|
||||
{
|
||||
// objectTypeIndication 0x69 and 0x6B are MPEG-1/2 audio (MP3) in an mp4a entry (ISO/IEC 14496-1 Table 5).
|
||||
"mp4a" when audio.ObjectType is 0x69 or 0x6B => AudioCodec.Mp3,
|
||||
"mp4a" => AudioCodec.Aac,
|
||||
".mp3" => AudioCodec.Mp3,
|
||||
"Opus" => AudioCodec.Opus,
|
||||
@@ -951,10 +1066,16 @@ public static class IsoBmffReader
|
||||
CodecTag = audio.Format,
|
||||
Channels = audio.Channels,
|
||||
SampleRate = audio.SampleRate,
|
||||
AacConfiguration = audio.Asc,
|
||||
AacConfiguration = audio.ObjectType is 0x69 or 0x6B ? null : audio.Asc,
|
||||
AudioObjectType = audio.ObjectType is 0x69 or 0x6B ? null : AudioTrack.ObjectTypeOf(audio.Asc),
|
||||
Timescale = audio.Timescale > 0 ? audio.Timescale : 1,
|
||||
Duration = DurationOf(audio),
|
||||
Samples = audio.Samples,
|
||||
EditMediaTime = audio.HasEdits ? audio.EditOffset : null,
|
||||
EmptyEditDuration = EmptyEdit(audio),
|
||||
EditSegmentDuration = EditSegment(audio),
|
||||
EditCount = audio.EditCount,
|
||||
Language = audio.Language,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -965,7 +1086,45 @@ public static class IsoBmffReader
|
||||
total = Seconds(v.Seconds(v.Duration));
|
||||
}
|
||||
|
||||
return new MediaContainer { Format = ContainerFormat.IsoBmff, CreatedAt = created, Duration = total, Video = v, Audio = a };
|
||||
return new MediaContainer
|
||||
{
|
||||
Format = ContainerFormat.IsoBmff,
|
||||
CreatedAt = created,
|
||||
ModifiedAt = modified,
|
||||
MajorBrand = brand,
|
||||
TrackCount = TrackCount,
|
||||
HasUserData = HasUserData,
|
||||
Duration = total,
|
||||
Video = v,
|
||||
Audio = a,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The segment of the first non-empty edit (movie units) in track units, rounded to the nearest; null when the
|
||||
/// edit has none (0, as fragmented files write it) or the track has no edit list.
|
||||
/// </summary>
|
||||
private long? EditSegment(Track track)
|
||||
{
|
||||
if (!track.HasEdits || track.EditSegmentMovie <= 0 || timescale <= 0 || track.Timescale <= 0)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var value = (((Int128)track.EditSegmentMovie * track.Timescale) + (timescale / 2)) / timescale;
|
||||
return value > long.MaxValue / 4 ? null : (long)value;
|
||||
}
|
||||
|
||||
/// <summary>The leading empty edits of a track (movie units) in track units, rounded to the nearest.</summary>
|
||||
private long EmptyEdit(Track track)
|
||||
{
|
||||
if (track.EmptyEditMovie <= 0 || timescale <= 0 || track.Timescale <= 0)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
var value = (((Int128)track.EmptyEditMovie * track.Timescale) + (timescale / 2)) / timescale;
|
||||
return value > long.MaxValue / 4 ? 0 : (long)value;
|
||||
}
|
||||
|
||||
/// <summary>A duration in seconds; null when it is beyond what a video can last (a damaged header).</summary>
|
||||
|
||||
@@ -107,6 +107,9 @@ public static class MatroskaReader
|
||||
case TracksId:
|
||||
ParseTracks(reader, bodyEnd, state);
|
||||
break;
|
||||
case TagsId:
|
||||
state.HasTags = true;
|
||||
break;
|
||||
case ClusterId:
|
||||
if (!samples)
|
||||
{
|
||||
@@ -214,6 +217,13 @@ public static class MatroskaReader
|
||||
case 0x23E383:
|
||||
track.DefaultDuration = (long)reader.Unsigned(tsize);
|
||||
break;
|
||||
case 0x22B59C:
|
||||
track.Language = reader.String(tsize);
|
||||
break;
|
||||
case 0x6D80: // ContentEncodings: the frames are compressed, stripped or encrypted
|
||||
track.Encoded = true;
|
||||
reader.Skip(tsize);
|
||||
break;
|
||||
case 0x55EE: // MaxBlockAdditionID, and others: ignored
|
||||
reader.Skip(tsize);
|
||||
break;
|
||||
@@ -289,6 +299,7 @@ public static class MatroskaReader
|
||||
}
|
||||
|
||||
stream.Position = Math.Min(entryEnd, stream.Length);
|
||||
state.TrackCount++;
|
||||
if (track.Type == 1 && state.Video is null)
|
||||
{
|
||||
state.Video = track;
|
||||
@@ -498,6 +509,8 @@ public static class MatroskaReader
|
||||
internal double Roll;
|
||||
internal int SampleRate;
|
||||
internal int Channels;
|
||||
internal string? Language;
|
||||
internal bool Encoded;
|
||||
internal readonly List<MediaSample> Samples = [];
|
||||
}
|
||||
|
||||
@@ -509,6 +522,12 @@ public static class MatroskaReader
|
||||
internal TrackEntry? Video;
|
||||
internal TrackEntry? Audio;
|
||||
|
||||
/// <summary>Every TrackEntry of the file.</summary>
|
||||
internal int TrackCount;
|
||||
|
||||
/// <summary>True when the segment has a Tags element.</summary>
|
||||
internal bool HasTags;
|
||||
|
||||
/// <summary>Nanoseconds of one unit of the sample times; fixed by the first block, 0 before.</summary>
|
||||
private long unit;
|
||||
|
||||
@@ -599,12 +618,15 @@ public static class MatroskaReader
|
||||
Timescale = timescale,
|
||||
Duration = trackUnits,
|
||||
Samples = samples,
|
||||
Language = Language(v.Language),
|
||||
Encoded = v.Encoded,
|
||||
};
|
||||
}
|
||||
|
||||
AudioTrack? audio = null;
|
||||
if (Audio is { } a)
|
||||
{
|
||||
var asc = a.CodecId == "A_AAC" ? a.CodecPrivate : a.CodecId.StartsWith("A_AAC/", StringComparison.Ordinal) ? LegacyAacConfig(a) : null;
|
||||
audio = new AudioTrack
|
||||
{
|
||||
Codec = a.CodecId switch
|
||||
@@ -619,16 +641,91 @@ public static class MatroskaReader
|
||||
CodecTag = a.CodecId,
|
||||
SampleRate = a.SampleRate,
|
||||
Channels = a.Channels,
|
||||
AacConfiguration = a.CodecId == "A_AAC" ? a.CodecPrivate : null,
|
||||
AacConfiguration = asc,
|
||||
AudioObjectType = AudioTrack.ObjectTypeOf(asc),
|
||||
Timescale = timescale,
|
||||
Duration = trackUnits,
|
||||
Samples = a.Samples,
|
||||
Language = Language(a.Language),
|
||||
Encoded = a.Encoded,
|
||||
};
|
||||
}
|
||||
|
||||
var seconds = DurationTicks * TimecodeScale / 1e9;
|
||||
TimeSpan? duration = seconds is > 0 and < 1e9 ? TimeSpan.FromSeconds(seconds) : null;
|
||||
return new MediaContainer { Format = ContainerFormat.Matroska, CreatedAt = Created, Duration = duration, Video = video, Audio = audio };
|
||||
return new MediaContainer
|
||||
{
|
||||
Format = ContainerFormat.Matroska,
|
||||
CreatedAt = Created,
|
||||
Duration = duration,
|
||||
Video = video,
|
||||
Audio = audio,
|
||||
TrackCount = TrackCount,
|
||||
HasUserData = HasTags,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>A three-letter ISO 639-2 language; null for «und», absent or malformed.</summary>
|
||||
private static string? Language(string? code) =>
|
||||
code is { Length: 3 } && code != "und" && code.All(char.IsAsciiLetterLower) ? code : null;
|
||||
|
||||
/// <summary>
|
||||
/// The AudioSpecificConfig (ISO/IEC 14496-3 §1.6.2.1) of a track with an old codec ID that names the profile
|
||||
/// («A_AAC/MPEG4/LC», «A_AAC/MPEG2/MAIN», «…/SBR»...) instead of carrying the configuration in CodecPrivate:
|
||||
/// object type, sampling frequency index (or the explicit frequency), channel configuration, then a
|
||||
/// GASpecificConfig of zeros (1024-sample frames, no core coder, no extension).
|
||||
/// </summary>
|
||||
private static byte[]? LegacyAacConfig(TrackEntry track)
|
||||
{
|
||||
if (track.CodecPrivate is { Length: >= 2 })
|
||||
{
|
||||
return track.CodecPrivate;
|
||||
}
|
||||
|
||||
var profile = track.CodecId[(track.CodecId.LastIndexOf('/') + 1)..];
|
||||
var objectType = profile switch
|
||||
{
|
||||
"MAIN" => 1,
|
||||
"LC" or "SBR" => 2, // SBR is signalled implicitly: the core rate in SamplingFrequency
|
||||
"SSR" => 3,
|
||||
"LTP" => 4,
|
||||
_ => 0,
|
||||
};
|
||||
if (objectType == 0 || track.SampleRate <= 0 || track.Channels is < 1 or > 7)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
int[] rates = [96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350];
|
||||
var index = Array.IndexOf(rates, track.SampleRate);
|
||||
var bits = new List<(int Value, int Count)> { (objectType, 5) };
|
||||
if (index >= 0)
|
||||
{
|
||||
bits.Add((index, 4));
|
||||
}
|
||||
else
|
||||
{
|
||||
bits.Add((15, 4));
|
||||
bits.Add((track.SampleRate & 0xFFFFFF, 24));
|
||||
}
|
||||
|
||||
bits.Add((track.Channels, 4));
|
||||
bits.Add((0, 3));
|
||||
var total = bits.Sum(b => b.Count);
|
||||
var config = new byte[(total + 7) / 8];
|
||||
var position = 0;
|
||||
foreach (var (value, count) in bits)
|
||||
{
|
||||
for (var i = count - 1; i >= 0; i--, position++)
|
||||
{
|
||||
if (((value >> i) & 1) != 0)
|
||||
{
|
||||
config[position / 8] |= (byte)(0x80 >> (position % 8));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return config;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -94,6 +94,38 @@ public abstract class MediaTrack
|
||||
/// <summary>The four-character code or codec identifier of the container, for messages.</summary>
|
||||
public string CodecTag { get; init; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// The media time (track units) shown at the start of the presentation, from the first non-empty edit of an ISO edit
|
||||
/// list; null when the track has no edit list (Matroska never has one). The reader's presentation times already
|
||||
/// have it subtracted.
|
||||
/// </summary>
|
||||
public long? EditMediaTime { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// The empty edits before the first non-empty one (a delayed start), in track units; 0 when none. A sample is shown
|
||||
/// at its <see cref="MediaSample.PresentationTime"/> plus this.
|
||||
/// </summary>
|
||||
public long EmptyEditDuration { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// How long the first non-empty edit shows the media from <see cref="EditMediaTime"/>, in track units; null when the
|
||||
/// edit runs to the end of the media (no segment written) or there is no edit list. Shorter than the media after
|
||||
/// <see cref="EditMediaTime"/>: the end of the media is hidden (a trim, the padding of AAC).
|
||||
/// </summary>
|
||||
public long? EditSegmentDuration { get; init; }
|
||||
|
||||
/// <summary>The edits of the edit list after the leading empty ones (1 for an ordinary one, 0 without edit list).</summary>
|
||||
public int EditCount { get; init; }
|
||||
|
||||
/// <summary>The language of the track as an ISO 639-2 code («ita», «eng»); null when unknown or undetermined.</summary>
|
||||
public string? Language { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// True when the frames of the track are stored transformed (Matroska ContentEncodings: compression, header
|
||||
/// stripping, encryption): their bytes are not the codec's.
|
||||
/// </summary>
|
||||
public bool Encoded { get; init; }
|
||||
|
||||
/// <summary>Time in seconds of a value in track units.</summary>
|
||||
public double Seconds(long ticks) => Timescale > 0 ? (double)ticks / Timescale : 0;
|
||||
}
|
||||
@@ -143,6 +175,26 @@ public sealed class AudioTrack : MediaTrack
|
||||
|
||||
/// <summary>The AudioSpecificConfig of an AAC track.</summary>
|
||||
public byte[]? AacConfiguration { get; init; }
|
||||
|
||||
/// <summary>The audio object type of an AAC track (ISO/IEC 14496-3: 2 is AAC LC, 5 SBR, 29 PS); null when unknown.</summary>
|
||||
public int? AudioObjectType { get; init; }
|
||||
|
||||
/// <summary>The audio object type of an AudioSpecificConfig (5 bits, 31 escaping to 32 + 6 more).</summary>
|
||||
internal static int? ObjectTypeOf(byte[]? asc)
|
||||
{
|
||||
if (asc is not { Length: > 0 })
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var type = asc[0] >> 3;
|
||||
if (type == 31)
|
||||
{
|
||||
return asc.Length > 1 ? 32 + (((asc[0] & 7) << 3) | (asc[1] >> 5)) : null;
|
||||
}
|
||||
|
||||
return type == 0 ? null : type;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>What a container says: its creation time, duration and first video and audio tracks.</summary>
|
||||
@@ -153,6 +205,21 @@ public sealed class MediaContainer
|
||||
/// <summary>Creation time written in the container, when plausible.</summary>
|
||||
public DateTimeOffset? CreatedAt { get; init; }
|
||||
|
||||
/// <summary>Modification time written in the container (ISO <c>mvhd</c>), when plausible.</summary>
|
||||
public DateTimeOffset? ModifiedAt { get; init; }
|
||||
|
||||
/// <summary>The major brand of an ISO file («isom», «qt », «M4V », «3gp4»...), null for other containers or without <c>ftyp</c>.</summary>
|
||||
public string? MajorBrand { get; init; }
|
||||
|
||||
/// <summary>Tracks of every kind in the file (video, audio, timecode, subtitles...), of which only the first video and audio are read.</summary>
|
||||
public int TrackCount { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// True when the file has metadata of its own that the readers do not interpret (ISO <c>udta</c> or <c>meta</c>
|
||||
/// boxes, Matroska tags): a remux does not carry it.
|
||||
/// </summary>
|
||||
public bool HasUserData { get; init; }
|
||||
|
||||
/// <summary>Duration of the whole presentation.</summary>
|
||||
public TimeSpan? Duration { get; init; }
|
||||
|
||||
|
||||
@@ -0,0 +1,337 @@
|
||||
namespace Febe.Core.Codecs.Containers;
|
||||
|
||||
/// <summary>Why a video cannot be brought into MP4 without re-encoding it (tappa E3: then it is copied as it is).</summary>
|
||||
public enum RemuxRefusal
|
||||
{
|
||||
/// <summary>It can.</summary>
|
||||
None,
|
||||
|
||||
/// <summary>Not a video Febe recognises, or a file without a video track.</summary>
|
||||
NotAVideo,
|
||||
|
||||
/// <summary>Already an MP4 (an ISO file with an <c>.mp4</c> name and a brand other than QuickTime's): copied byte for byte.</summary>
|
||||
AlreadyMp4,
|
||||
|
||||
/// <summary>A container whose frames MP4 cannot take as they are (AVI, ASF, FLV, MPEG-PS, Annex B streams).</summary>
|
||||
ContainerNotRemuxable,
|
||||
|
||||
/// <summary>A video codec other than H.264 and HEVC.</summary>
|
||||
VideoCodec,
|
||||
|
||||
/// <summary>An audio codec other than AAC and MP3.</summary>
|
||||
AudioCodec,
|
||||
|
||||
/// <summary>A track without the configuration record of its codec.</summary>
|
||||
MissingConfiguration,
|
||||
|
||||
/// <summary>A Matroska track whose frames are stored transformed (ContentEncodings).</summary>
|
||||
EncodedTrack,
|
||||
|
||||
/// <summary>A track with more than one edit (a cut or a still segment), which the writer does not reproduce.</summary>
|
||||
EditList,
|
||||
|
||||
/// <summary>A video track without samples.</summary>
|
||||
NoSamples,
|
||||
|
||||
/// <summary>A damaged or truncated file.</summary>
|
||||
Unreadable,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A remux planned by <see cref="Mp4Remuxer.Check(Stream, string, out RemuxPlan, CancellationToken)"/>: the source as
|
||||
/// read, the MP4 to write (its exact length is <see cref="OutputLength"/>) and the note codes of what it does not keep.
|
||||
/// </summary>
|
||||
public sealed record RemuxPlan(MediaContainer Source, Mp4Layout Layout, IReadOnlyList<string> Losses)
|
||||
{
|
||||
/// <summary>Bytes of the MP4 that <see cref="Mp4Remuxer.Write"/> writes.</summary>
|
||||
public long OutputLength => Layout.Length;
|
||||
|
||||
/// <summary>The stream the sample writers of <see cref="Layout"/> read from, set by <see cref="Mp4Remuxer.Write"/>.</summary>
|
||||
internal RemuxSource Reading { get; init; } = new();
|
||||
}
|
||||
|
||||
/// <summary>Where the samples of a planned remux are read from while it is written.</summary>
|
||||
internal sealed class RemuxSource
|
||||
{
|
||||
internal Stream? Stream { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Brings a MOV, M4V, 3GP or Matroska video into MP4 by copying its samples (tappa E3, «MOV → MP4 solo rimuxaggio»):
|
||||
/// one H.264 or HEVC video track and at most one AAC or MP3 audio track, with their configuration records, sync
|
||||
/// samples, composition offsets, edit (the delayed start and the hidden AAC priming), rotation, language and dates.
|
||||
/// Nothing is re-encoded; anything that would need it is refused with its reason. Only the tables and the
|
||||
/// <c>moov</c> are in memory: the samples are read and written one at a time, and the same source always gives the
|
||||
/// same bytes (the reader's «now» is fixed).
|
||||
/// </summary>
|
||||
public static class Mp4Remuxer
|
||||
{
|
||||
/// <summary>Note code (with «:n») of the tracks left behind: timecode, subtitles, a second audio track...</summary>
|
||||
public const string LostTracks = "LostTracks";
|
||||
|
||||
/// <summary>Note code of the metadata of the source the MP4 does not carry (ISO <c>udta</c>/<c>meta</c>, Matroska tags).</summary>
|
||||
public const string LostVideoMetadata = "LostVideoMetadata";
|
||||
|
||||
/// <summary>Plans the remux of a seekable <paramref name="source"/> without knowing its name: never <see cref="RemuxRefusal.AlreadyMp4"/>.</summary>
|
||||
public static RemuxRefusal Check(Stream source, out RemuxPlan? plan, CancellationToken ct) => Check(source, null, out plan, ct);
|
||||
|
||||
/// <summary>
|
||||
/// Plans the remux of a seekable <paramref name="source"/>; <paramref name="fileName"/> (or a path) tells an MP4
|
||||
/// already (<see cref="RemuxRefusal.AlreadyMp4"/>). Never throws for a bad file.
|
||||
/// </summary>
|
||||
public static RemuxRefusal Check(Stream source, string? fileName, out RemuxPlan? plan, CancellationToken ct)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(source);
|
||||
plan = null;
|
||||
MediaContainer? container;
|
||||
try
|
||||
{
|
||||
container = ContainerReader.Read(source, ContainerReader.AnyDate, samples: true, ct);
|
||||
}
|
||||
catch (Exception ex) when (ex is ContainerException or EndOfStreamException or IOException or ArgumentException
|
||||
or IndexOutOfRangeException or OverflowException or InvalidDataException)
|
||||
{
|
||||
return RemuxRefusal.Unreadable;
|
||||
}
|
||||
|
||||
if (container is null)
|
||||
{
|
||||
return RemuxRefusal.NotAVideo;
|
||||
}
|
||||
|
||||
if (container.Format is not (ContainerFormat.IsoBmff or ContainerFormat.Matroska))
|
||||
{
|
||||
return container.Video is null ? RemuxRefusal.NotAVideo : RemuxRefusal.ContainerNotRemuxable;
|
||||
}
|
||||
|
||||
if (container.Format == ContainerFormat.IsoBmff && container.MajorBrand != "qt "
|
||||
&& string.Equals(Path.GetExtension(fileName ?? string.Empty), ".mp4", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return RemuxRefusal.AlreadyMp4;
|
||||
}
|
||||
|
||||
if (container.Video is not { } video)
|
||||
{
|
||||
return RemuxRefusal.NotAVideo;
|
||||
}
|
||||
|
||||
var audio = container.Audio is { Samples.Count: > 0 } a ? a : null;
|
||||
var refusal = Refusal(video, audio);
|
||||
if (refusal != RemuxRefusal.None)
|
||||
{
|
||||
return refusal;
|
||||
}
|
||||
|
||||
var length = source.Length;
|
||||
if (!InFile(video, length) || (audio is not null && !InFile(audio, length)))
|
||||
{
|
||||
return RemuxRefusal.Unreadable;
|
||||
}
|
||||
|
||||
var reading = new RemuxSource();
|
||||
var tracks = new List<Mp4OutputTrack> { VideoTrackOf(container, video, reading) };
|
||||
if (audio is not null)
|
||||
{
|
||||
tracks.Add(AudioTrackOf(container, audio, reading));
|
||||
}
|
||||
|
||||
Mp4Layout layout;
|
||||
try
|
||||
{
|
||||
layout = Mp4Writer.Prepare(tracks, new Mp4MovieInfo(container.CreatedAt, container.ModifiedAt));
|
||||
}
|
||||
catch (Exception ex) when (ex is ArgumentException or OverflowException)
|
||||
{
|
||||
return RemuxRefusal.Unreadable;
|
||||
}
|
||||
|
||||
var losses = new List<string>();
|
||||
var dropped = container.TrackCount - tracks.Count;
|
||||
if (dropped > 0)
|
||||
{
|
||||
losses.Add(FormattableString.Invariant($"{LostTracks}:{dropped}"));
|
||||
}
|
||||
|
||||
if (container.HasUserData)
|
||||
{
|
||||
losses.Add(LostVideoMetadata);
|
||||
}
|
||||
|
||||
plan = new RemuxPlan(container, layout, losses) { Reading = reading };
|
||||
return RemuxRefusal.None;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes the MP4 of <paramref name="plan"/> into <paramref name="output"/>, reading the samples from
|
||||
/// <paramref name="source"/> (the same file the plan was made from, seekable). <paramref name="ct"/> is checked
|
||||
/// between samples.
|
||||
/// </summary>
|
||||
/// <exception cref="ContainerException">A sample lies outside the file (it changed since the plan).</exception>
|
||||
public static void Write(RemuxPlan plan, Stream source, Stream output, CancellationToken ct)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(plan);
|
||||
ArgumentNullException.ThrowIfNull(source);
|
||||
ArgumentNullException.ThrowIfNull(output);
|
||||
lock (plan.Reading)
|
||||
{
|
||||
plan.Reading.Stream = source;
|
||||
try
|
||||
{
|
||||
plan.Layout.WriteTo(output, ct);
|
||||
}
|
||||
finally
|
||||
{
|
||||
plan.Reading.Stream = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static RemuxRefusal Refusal(VideoTrack video, AudioTrack? audio)
|
||||
{
|
||||
if (video.Encoded || audio?.Encoded == true)
|
||||
{
|
||||
return RemuxRefusal.EncodedTrack;
|
||||
}
|
||||
|
||||
if (video.Codec is not (VideoCodec.H264 or VideoCodec.Hevc))
|
||||
{
|
||||
return RemuxRefusal.VideoCodec;
|
||||
}
|
||||
|
||||
if (video.AnnexB)
|
||||
{
|
||||
return RemuxRefusal.ContainerNotRemuxable;
|
||||
}
|
||||
|
||||
if ((video.Codec == VideoCodec.H264 ? video.AvcConfiguration : video.HevcConfiguration) is not { Length: > 0 })
|
||||
{
|
||||
return RemuxRefusal.MissingConfiguration;
|
||||
}
|
||||
|
||||
if (video.Samples.Count == 0)
|
||||
{
|
||||
return RemuxRefusal.NoSamples;
|
||||
}
|
||||
|
||||
if (video.EditCount > 1)
|
||||
{
|
||||
return RemuxRefusal.EditList;
|
||||
}
|
||||
|
||||
if (audio is null)
|
||||
{
|
||||
return RemuxRefusal.None;
|
||||
}
|
||||
|
||||
if (audio.Codec is not (AudioCodec.Aac or AudioCodec.Mp3))
|
||||
{
|
||||
return RemuxRefusal.AudioCodec;
|
||||
}
|
||||
|
||||
if (audio.Codec == AudioCodec.Aac && audio.AacConfiguration is not { Length: >= 2 })
|
||||
{
|
||||
return RemuxRefusal.MissingConfiguration;
|
||||
}
|
||||
|
||||
return audio.EditCount > 1 ? RemuxRefusal.EditList : RemuxRefusal.None;
|
||||
}
|
||||
|
||||
private static bool InFile(MediaTrack track, long length)
|
||||
{
|
||||
foreach (var s in track.Samples)
|
||||
{
|
||||
if (s.Offset < 0 || s.Size < 0 || s.Size > ContainerReader.MaxSampleSize || s.Offset + s.Size > length)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private static Mp4OutputTrack VideoTrackOf(MediaContainer container, VideoTrack video, RemuxSource reading)
|
||||
{
|
||||
var (samples, edit) = Times(container, video);
|
||||
return new Mp4OutputTrack
|
||||
{
|
||||
IsVideo = true,
|
||||
Timescale = video.Timescale,
|
||||
Samples = samples,
|
||||
WriteSample = Writer(video, reading),
|
||||
Width = video.Width,
|
||||
Height = video.Height,
|
||||
Rotation = video.Rotation,
|
||||
AvcConfiguration = video.Codec == VideoCodec.H264 ? video.AvcConfiguration : null,
|
||||
HevcConfiguration = video.Codec == VideoCodec.Hevc ? video.HevcConfiguration : null,
|
||||
SampleEntryType = container.Format == ContainerFormat.IsoBmff ? video.CodecTag : null,
|
||||
Language = video.Language,
|
||||
EditMediaTime = edit,
|
||||
EmptyEditDuration = video.EmptyEditDuration,
|
||||
EditSegmentDuration = video.EditSegmentDuration,
|
||||
LastSampleDuration = LastDuration(video),
|
||||
};
|
||||
}
|
||||
|
||||
private static Mp4OutputTrack AudioTrackOf(MediaContainer container, AudioTrack audio, RemuxSource reading)
|
||||
{
|
||||
var (samples, edit) = Times(container, audio);
|
||||
return new Mp4OutputTrack
|
||||
{
|
||||
IsVideo = false,
|
||||
Timescale = audio.Timescale,
|
||||
Samples = samples,
|
||||
WriteSample = Writer(audio, reading),
|
||||
AacConfiguration = audio.Codec == AudioCodec.Aac ? audio.AacConfiguration : null,
|
||||
IsMp3 = audio.Codec == AudioCodec.Mp3,
|
||||
SampleRate = audio.SampleRate,
|
||||
Channels = audio.Channels,
|
||||
Language = audio.Language,
|
||||
EditMediaTime = edit,
|
||||
EmptyEditDuration = audio.EmptyEditDuration,
|
||||
EditSegmentDuration = audio.EditSegmentDuration,
|
||||
LastSampleDuration = LastDuration(audio),
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The samples with their composition times and the media time shown first: an ISO reader's presentation times
|
||||
/// have the edit's media time taken off, so it is put back and becomes the edit of the output; without an edit
|
||||
/// list (and in Matroska, whose block times are presentation times) the media time 0 is shown at 0.
|
||||
/// </summary>
|
||||
private static (Mp4OutputSample[] Samples, long Edit) Times(MediaContainer container, MediaTrack track)
|
||||
{
|
||||
var edit = container.Format == ContainerFormat.IsoBmff ? track.EditMediaTime ?? 0 : 0;
|
||||
var samples = new Mp4OutputSample[track.Samples.Count];
|
||||
for (var i = 0; i < samples.Length; i++)
|
||||
{
|
||||
var s = track.Samples[i];
|
||||
samples[i] = new Mp4OutputSample(s.Size, s.DecodeTime, s.PresentationTime + edit, s.Key);
|
||||
}
|
||||
|
||||
return (samples, edit);
|
||||
}
|
||||
|
||||
/// <summary>The duration of the last sample from the track's duration, when it is plausible (else the writer's default).</summary>
|
||||
private static long LastDuration(MediaTrack track)
|
||||
{
|
||||
var samples = track.Samples;
|
||||
var last = track.Duration - samples[^1].DecodeTime;
|
||||
if (last <= 0)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
var before = samples.Count > 1 ? samples[^1].DecodeTime - samples[^2].DecodeTime : last;
|
||||
return before > 0 && last > 4 * before ? 0 : last;
|
||||
}
|
||||
|
||||
private static Action<int, Stream> Writer(MediaTrack track, RemuxSource reading)
|
||||
{
|
||||
var buffer = new byte[64 * 1024];
|
||||
return (i, output) =>
|
||||
{
|
||||
var source = reading.Stream ?? throw new InvalidOperationException("Il rimuxaggio non ha la sua sorgente.");
|
||||
output.Write(ContainerReader.ReadSample(source, track.Samples[i], ref buffer));
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -41,6 +41,135 @@ public sealed class Mp4OutputTrack
|
||||
|
||||
/// <summary>Duration of the last sample, when the times cannot tell it (0: as the one before it).</summary>
|
||||
public long LastSampleDuration { get; init; }
|
||||
|
||||
/// <summary>The ISO 639-2/T language of the <c>mdhd</c> («ita»); null writes «und».</summary>
|
||||
public string? Language { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// The sample entry of a video track: «avc1» or «avc3» (H.264), «hvc1» or «hev1» (HEVC), as the source has it;
|
||||
/// null writes «avc1» or «hvc1».
|
||||
/// </summary>
|
||||
public string? SampleEntryType { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// MPEG-1/2 audio layer III in an <c>mp4a</c> entry (objectTypeIndication 0x6B, or 0x69 at 24 kHz and below,
|
||||
/// ISO/IEC 14496-1): it has no AudioSpecificConfig, so <see cref="AacConfiguration"/> stays null.
|
||||
/// </summary>
|
||||
public bool IsMp3 { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// The media time, on the scale of <see cref="Mp4OutputSample.PresentationTime"/>, shown at the start of the
|
||||
/// presentation (the source's edit, so that AAC priming stays hidden); null lets the writer start at the first
|
||||
/// shown sample, as before tappa E3.
|
||||
/// </summary>
|
||||
public long? EditMediaTime { get; init; }
|
||||
|
||||
/// <summary>A delayed start in track units: an empty edit before the media (0: none).</summary>
|
||||
public long EmptyEditDuration { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// How long the edit shows the media, in track units (the source's segment: a trimmed end stays hidden); null shows
|
||||
/// it from <see cref="EditMediaTime"/> to the end. Never longer than the media.
|
||||
/// </summary>
|
||||
public long? EditSegmentDuration { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>The dates of the movie header; the modification date falls back to the creation date.</summary>
|
||||
public sealed record Mp4MovieInfo(DateTimeOffset? Created, DateTimeOffset? Modified);
|
||||
|
||||
/// <summary>
|
||||
/// An MP4 file planned by <see cref="Mp4Writer.Prepare"/>: its exact <see cref="Length"/> is known before a byte is
|
||||
/// written, and <see cref="WriteTo"/> streams it, one sample at a time.
|
||||
/// </summary>
|
||||
public sealed class Mp4Layout
|
||||
{
|
||||
private readonly IReadOnlyList<Mp4OutputTrack> tracks;
|
||||
private readonly List<(int Track, int First, int Count)> chunks;
|
||||
private readonly byte[] head;
|
||||
|
||||
internal Mp4Layout(IReadOnlyList<Mp4OutputTrack> tracks, List<(int Track, int First, int Count)> chunks, byte[] head, long payload)
|
||||
{
|
||||
this.tracks = tracks;
|
||||
this.chunks = chunks;
|
||||
this.head = head;
|
||||
Length = head.LongLength + payload;
|
||||
}
|
||||
|
||||
/// <summary>Bytes of the whole file.</summary>
|
||||
public long Length { get; }
|
||||
|
||||
/// <summary>Writes the file into <paramref name="output"/> (from its current position).</summary>
|
||||
/// <exception cref="InvalidOperationException">A sample writer wrote another number of bytes than its size.</exception>
|
||||
public void WriteTo(Stream output, CancellationToken ct = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(output);
|
||||
var counting = new CountingStream(output);
|
||||
counting.Write(head);
|
||||
foreach (var (track, first, count) in chunks)
|
||||
{
|
||||
for (var k = first; k < first + count; k++)
|
||||
{
|
||||
ct.ThrowIfCancellationRequested();
|
||||
var before = counting.Count;
|
||||
tracks[track].WriteSample(k, counting);
|
||||
if (counting.Count - before != tracks[track].Samples[k].Size)
|
||||
{
|
||||
throw new InvalidOperationException("Un campione non ha la lunghezza dichiarata.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (counting.Count != Length)
|
||||
{
|
||||
throw new InvalidOperationException("Il file scritto non ha la lunghezza prevista.");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Counts the bytes written through it, whatever the stream below can tell.</summary>
|
||||
private sealed class CountingStream(Stream inner) : Stream
|
||||
{
|
||||
public long Count { get; private set; }
|
||||
|
||||
public override bool CanRead => false;
|
||||
|
||||
public override bool CanSeek => false;
|
||||
|
||||
public override bool CanWrite => true;
|
||||
|
||||
public override long Length => throw new NotSupportedException();
|
||||
|
||||
public override long Position
|
||||
{
|
||||
get => Count;
|
||||
set => throw new NotSupportedException();
|
||||
}
|
||||
|
||||
public override void Flush() => inner.Flush();
|
||||
|
||||
public override int Read(byte[] buffer, int offset, int count) => throw new NotSupportedException();
|
||||
|
||||
public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException();
|
||||
|
||||
public override void SetLength(long value) => throw new NotSupportedException();
|
||||
|
||||
public override void Write(byte[] buffer, int offset, int count)
|
||||
{
|
||||
inner.Write(buffer, offset, count);
|
||||
Count += count;
|
||||
}
|
||||
|
||||
public override void Write(ReadOnlySpan<byte> buffer)
|
||||
{
|
||||
inner.Write(buffer);
|
||||
Count += buffer.Length;
|
||||
}
|
||||
|
||||
public override void WriteByte(byte value)
|
||||
{
|
||||
inner.WriteByte(value);
|
||||
Count++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -57,6 +186,16 @@ public static class Mp4Writer
|
||||
public static void Write(Stream output, IReadOnlyList<Mp4OutputTrack> tracks, DateTimeOffset? created = null)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(output);
|
||||
Prepare(tracks, created is null ? null : new Mp4MovieInfo(created, created)).WriteTo(output);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Plans the file of <paramref name="tracks"/>: every box but the media data is built, so the length is known;
|
||||
/// <see cref="Mp4Layout.WriteTo"/> writes it.
|
||||
/// </summary>
|
||||
/// <exception cref="ArgumentException">A track has no samples, no timescale or no codec configuration.</exception>
|
||||
public static Mp4Layout Prepare(IReadOnlyList<Mp4OutputTrack> tracks, Mp4MovieInfo? info)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(tracks);
|
||||
if (tracks.Count == 0 || tracks.Any(t => t.Samples.Count == 0 || t.Timescale <= 0))
|
||||
{
|
||||
@@ -65,7 +204,7 @@ public static class Mp4Writer
|
||||
|
||||
foreach (var track in tracks)
|
||||
{
|
||||
if (track.IsVideo ? (track.AvcConfiguration is null) == (track.HevcConfiguration is null) : track.AacConfiguration is null)
|
||||
if (track.IsVideo ? (track.AvcConfiguration is null) == (track.HevcConfiguration is null) : track.AacConfiguration is null && !track.IsMp3)
|
||||
{
|
||||
throw new ArgumentException("Manca la configurazione del codificatore.", nameof(tracks));
|
||||
}
|
||||
@@ -84,7 +223,9 @@ public static class Mp4Writer
|
||||
|
||||
var wideMdat = payload + 8 > uint.MaxValue;
|
||||
var ftyp = Ftyp();
|
||||
var time = created is { } c && c > Epoch1904 ? (ulong)(c - Epoch1904).TotalSeconds : 0UL;
|
||||
var creation = info?.Created is { } c && c > Epoch1904 ? (ulong)(c - Epoch1904).TotalSeconds : 0UL;
|
||||
var modification = (info?.Modified ?? info?.Created) is { } m && m > Epoch1904 ? (ulong)(m - Epoch1904).TotalSeconds : 0UL;
|
||||
var time = (creation, modification);
|
||||
|
||||
// The moov box has the same size whatever the chunk offsets: build it once to know where the data starts.
|
||||
var co64 = false;
|
||||
@@ -110,40 +251,35 @@ public static class Mp4Writer
|
||||
}
|
||||
|
||||
moov = Moov(tracks, timing, chunks, offsets, co64, time);
|
||||
output.Write(ftyp);
|
||||
output.Write(moov);
|
||||
Span<byte> header = stackalloc byte[16];
|
||||
var head = new byte[ftyp.Length + moov.Length + (wideMdat ? 16 : 8)];
|
||||
ftyp.CopyTo(head, 0);
|
||||
moov.CopyTo(head, ftyp.Length);
|
||||
var header = head.AsSpan(ftyp.Length + moov.Length);
|
||||
if (wideMdat)
|
||||
{
|
||||
BinaryPrimitives.WriteUInt32BigEndian(header, 1);
|
||||
"mdat"u8.CopyTo(header[4..]);
|
||||
BinaryPrimitives.WriteUInt64BigEndian(header[8..], (ulong)(payload + 16));
|
||||
output.Write(header);
|
||||
}
|
||||
else
|
||||
{
|
||||
BinaryPrimitives.WriteUInt32BigEndian(header, (uint)(payload + 8));
|
||||
"mdat"u8.CopyTo(header[4..]);
|
||||
output.Write(header[..8]);
|
||||
}
|
||||
|
||||
foreach (var (track, first, count) in chunks)
|
||||
{
|
||||
for (var k = first; k < first + count; k++)
|
||||
{
|
||||
var before = output.CanSeek ? output.Position : -1;
|
||||
tracks[track].WriteSample(k, output);
|
||||
if (before >= 0 && output.Position - before != tracks[track].Samples[k].Size)
|
||||
{
|
||||
throw new InvalidOperationException("Un campione non ha la lunghezza dichiarata.");
|
||||
}
|
||||
}
|
||||
}
|
||||
return new Mp4Layout(tracks, chunks, head, payload);
|
||||
}
|
||||
|
||||
/// <summary>Times of a track as the boxes need them.</summary>
|
||||
private sealed record Timing(long[] Durations, int[] CompositionOffsets, long MediaDuration, long EditMediaTime, bool AllKey)
|
||||
/// <summary>
|
||||
/// Times of a track as the boxes need them; <paramref name="EmptyEdit"/>, <paramref name="Shown"/> (the media
|
||||
/// the edit shows, from <paramref name="EditMediaTime"/>) and <paramref name="PresentationEnd"/> (where the last
|
||||
/// sample stops being shown, in composition time) are in track units.
|
||||
/// </summary>
|
||||
private sealed record Timing(long[] Durations, int[] CompositionOffsets, long MediaDuration, long EditMediaTime, bool AllKey, long EmptyEdit, long Shown, long PresentationEnd)
|
||||
{
|
||||
/// <summary>Whether the edit hides the end of the media (it must then be written).</summary>
|
||||
public bool TrimsEnd => Shown < PresentationEnd - EditMediaTime;
|
||||
|
||||
internal static Timing Of(Mp4OutputTrack track)
|
||||
{
|
||||
var samples = track.Samples;
|
||||
@@ -180,9 +316,31 @@ public static class Mp4Writer
|
||||
total += d;
|
||||
}
|
||||
|
||||
// The edit list starts the presentation at the first shown sample.
|
||||
var editTime = minPts - first + shift;
|
||||
return new Timing(durations, offsets, total, editTime, allKey);
|
||||
// The presentation ends where the sample shown last stops, in composition time: with B frames that is later
|
||||
// than the decoding durations add up to (by the first composition offset), and the edit starts there too.
|
||||
long presentationEnd = 0;
|
||||
for (var i = 0; i < n; i++)
|
||||
{
|
||||
presentationEnd = Math.Max(presentationEnd, samples[i].DecodeTime - first + offsets[i] + durations[i]);
|
||||
}
|
||||
|
||||
// The edit list starts the presentation at the first shown sample, or where the track says; a start before
|
||||
// the first sample becomes an empty edit.
|
||||
var editTime = (track.EditMediaTime ?? minPts) - first + shift;
|
||||
var empty = Math.Max(0, track.EmptyEditDuration);
|
||||
if (editTime < 0)
|
||||
{
|
||||
empty += -editTime;
|
||||
editTime = 0;
|
||||
}
|
||||
|
||||
var shown = Math.Max(0, presentationEnd - editTime);
|
||||
if (track.EditSegmentDuration is { } segment && segment > 0)
|
||||
{
|
||||
shown = Math.Min(shown, segment);
|
||||
}
|
||||
|
||||
return new Timing(durations, offsets, total, editTime, allKey, empty, shown, presentationEnd);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -222,17 +380,17 @@ public static class Mp4Writer
|
||||
return box.ToArray();
|
||||
}
|
||||
|
||||
private static byte[] Moov(IReadOnlyList<Mp4OutputTrack> tracks, Timing[] timing, List<(int Track, int First, int Count)> chunks, long[] offsets, bool co64, ulong time)
|
||||
private static byte[] Moov(IReadOnlyList<Mp4OutputTrack> tracks, Timing[] timing, List<(int Track, int First, int Count)> chunks, long[] offsets, bool co64, (ulong Created, ulong Modified) time)
|
||||
{
|
||||
long movieDuration = 0;
|
||||
for (var t = 0; t < tracks.Count; t++)
|
||||
{
|
||||
movieDuration = Math.Max(movieDuration, ToMovie(timing[t].MediaDuration - timing[t].EditMediaTime, tracks[t].Timescale));
|
||||
movieDuration = Math.Max(movieDuration, EmptyMovie(timing[t], tracks[t].Timescale) + ToMovie(timing[t].Shown, tracks[t].Timescale));
|
||||
}
|
||||
|
||||
var moov = new Box("moov");
|
||||
var mvhd = new Box("mvhd");
|
||||
var wide = movieDuration > uint.MaxValue || time > uint.MaxValue;
|
||||
var wide = movieDuration > uint.MaxValue || Wide(time);
|
||||
mvhd.U32(wide ? 0x01000000u : 0);
|
||||
Times(mvhd, wide, time, MovieTimescale, movieDuration);
|
||||
mvhd.U32(0x00010000);
|
||||
@@ -253,19 +411,25 @@ public static class Mp4Writer
|
||||
|
||||
private static long ToMovie(long ticks, long timescale) => (long)Math.Ceiling(Math.Max(0, ticks) * (double)MovieTimescale / timescale);
|
||||
|
||||
private static void Times(Box box, bool wide, ulong time, long timescale, long duration)
|
||||
/// <summary>The empty edit of a track in movie units, rounded to the nearest.</summary>
|
||||
private static long EmptyMovie(Timing timing, long timescale) =>
|
||||
timing.EmptyEdit <= 0 ? 0 : (long)((((Int128)timing.EmptyEdit * MovieTimescale) + (timescale / 2)) / timescale);
|
||||
|
||||
private static bool Wide((ulong Created, ulong Modified) time) => time.Created > uint.MaxValue || time.Modified > uint.MaxValue;
|
||||
|
||||
private static void Times(Box box, bool wide, (ulong Created, ulong Modified) time, long timescale, long duration)
|
||||
{
|
||||
if (wide)
|
||||
{
|
||||
box.U64(time);
|
||||
box.U64(time);
|
||||
box.U64(time.Created);
|
||||
box.U64(time.Modified);
|
||||
box.U32((uint)timescale);
|
||||
box.U64((ulong)duration);
|
||||
}
|
||||
else
|
||||
{
|
||||
box.U32((uint)time);
|
||||
box.U32((uint)time);
|
||||
box.U32((uint)time.Created);
|
||||
box.U32((uint)time.Modified);
|
||||
box.U32((uint)timescale);
|
||||
box.U32((uint)duration);
|
||||
}
|
||||
@@ -293,25 +457,27 @@ public static class Mp4Writer
|
||||
}
|
||||
}
|
||||
|
||||
private static Box Trak(Mp4OutputTrack track, Timing timing, int index, List<(int Track, int First, int Count)> chunks, long[] offsets, bool co64, ulong time)
|
||||
private static Box Trak(Mp4OutputTrack track, Timing timing, int index, List<(int Track, int First, int Count)> chunks, long[] offsets, bool co64, (ulong Created, ulong Modified) time)
|
||||
{
|
||||
var trak = new Box("trak");
|
||||
var duration = ToMovie(timing.MediaDuration - timing.EditMediaTime, track.Timescale);
|
||||
var wide = duration > uint.MaxValue || time > uint.MaxValue;
|
||||
var segment = ToMovie(timing.Shown, track.Timescale);
|
||||
var empty = EmptyMovie(timing, track.Timescale);
|
||||
var duration = empty + segment;
|
||||
var wide = duration > uint.MaxValue || Wide(time);
|
||||
var tkhd = new Box("tkhd");
|
||||
tkhd.U32((wide ? 0x01000000u : 0) | 3);
|
||||
if (wide)
|
||||
{
|
||||
tkhd.U64(time);
|
||||
tkhd.U64(time);
|
||||
tkhd.U64(time.Created);
|
||||
tkhd.U64(time.Modified);
|
||||
tkhd.U32((uint)index + 1);
|
||||
tkhd.U32(0);
|
||||
tkhd.U64((ulong)duration);
|
||||
}
|
||||
else
|
||||
{
|
||||
tkhd.U32((uint)time);
|
||||
tkhd.U32((uint)time);
|
||||
tkhd.U32((uint)time.Created);
|
||||
tkhd.U32((uint)time.Modified);
|
||||
tkhd.U32((uint)index + 1);
|
||||
tkhd.U32(0);
|
||||
tkhd.U32((uint)duration);
|
||||
@@ -327,13 +493,21 @@ public static class Mp4Writer
|
||||
tkhd.U32(track.IsVideo ? (uint)track.Height << 16 : 0);
|
||||
trak.Child(tkhd);
|
||||
|
||||
if (timing.EditMediaTime != 0)
|
||||
if (timing.EditMediaTime != 0 || empty > 0 || timing.TrimsEnd)
|
||||
{
|
||||
var edts = new Box("edts");
|
||||
var elst = new Box("elst");
|
||||
elst.U32(0x01000000);
|
||||
elst.U32(1);
|
||||
elst.U64((ulong)duration);
|
||||
elst.U32(empty > 0 ? 2u : 1u);
|
||||
if (empty > 0)
|
||||
{
|
||||
elst.U64((ulong)empty);
|
||||
elst.U64(ulong.MaxValue); // media_time −1: an empty edit
|
||||
elst.U16(1);
|
||||
elst.U16(0);
|
||||
}
|
||||
|
||||
elst.U64((ulong)segment);
|
||||
elst.U64((ulong)timing.EditMediaTime);
|
||||
elst.U16(1);
|
||||
elst.U16(0);
|
||||
@@ -343,10 +517,10 @@ public static class Mp4Writer
|
||||
|
||||
var mdia = new Box("mdia");
|
||||
var mdhd = new Box("mdhd");
|
||||
var mediaWide = timing.MediaDuration > uint.MaxValue || time > uint.MaxValue;
|
||||
var mediaWide = timing.MediaDuration > uint.MaxValue || Wide(time);
|
||||
mdhd.U32(mediaWide ? 0x01000000u : 0);
|
||||
Times(mdhd, mediaWide, time, track.Timescale, timing.MediaDuration);
|
||||
mdhd.U16(0x55C4); // «und»
|
||||
mdhd.U16(PackedLanguage(track.Language));
|
||||
mdhd.U16(0);
|
||||
mdia.Child(mdhd);
|
||||
|
||||
@@ -389,6 +563,17 @@ public static class Mp4Writer
|
||||
return trak;
|
||||
}
|
||||
|
||||
/// <summary>An ISO 639-2/T code packed in 15 bits (ISO/IEC 14496-12 §8.4.2.3); «und» for anything else.</summary>
|
||||
private static ushort PackedLanguage(string? language)
|
||||
{
|
||||
if (language is not { Length: 3 } || !language.All(char.IsAsciiLetterLower))
|
||||
{
|
||||
return 0x55C4; // «und»
|
||||
}
|
||||
|
||||
return (ushort)(((language[0] - 0x60) << 10) | ((language[1] - 0x60) << 5) | (language[2] - 0x60));
|
||||
}
|
||||
|
||||
private static Box Stbl(Mp4OutputTrack track, Timing timing, int index, List<(int Track, int First, int Count)> chunks, long[] offsets, bool co64)
|
||||
{
|
||||
var stbl = new Box("stbl");
|
||||
@@ -540,7 +725,10 @@ public static class Mp4Writer
|
||||
private static Box Avc1(Mp4OutputTrack track)
|
||||
{
|
||||
var hevc = track.HevcConfiguration is not null;
|
||||
var entry = new Box(hevc ? "hvc1" : "avc1");
|
||||
var type = hevc
|
||||
? track.SampleEntryType is "hvc1" or "hev1" ? track.SampleEntryType : "hvc1"
|
||||
: track.SampleEntryType is "avc1" or "avc3" ? track.SampleEntryType : "avc1";
|
||||
var entry = new Box(type);
|
||||
entry.Zero(6);
|
||||
entry.U16(1);
|
||||
entry.Zero(16);
|
||||
@@ -571,10 +759,11 @@ public static class Mp4Writer
|
||||
entry.U16(0);
|
||||
entry.U32((uint)Math.Min(track.SampleRate, 65535) << 16);
|
||||
|
||||
var asc = track.AacConfiguration!;
|
||||
var decoderSpecific = Descriptor(0x05, asc);
|
||||
var decoderSpecific = track.IsMp3 ? [] : Descriptor(0x05, track.AacConfiguration!);
|
||||
var config = new byte[13 + decoderSpecific.Length];
|
||||
config[0] = 0x40; // MPEG-4 audio
|
||||
// MPEG-4 audio, or layer III: MPEG-1 audio (ISO/IEC 11172-3, 32 to 48 kHz) or the MPEG-2 audio of the lower
|
||||
// rates (ISO/IEC 13818-3, 16 to 24 kHz and the 8 to 12 kHz of «MPEG-2.5»): ISO/IEC 14496-1 Table 5.
|
||||
config[0] = !track.IsMp3 ? (byte)0x40 : track.SampleRate is > 0 and <= 24000 ? (byte)0x69 : (byte)0x6B;
|
||||
config[1] = 0x15; // audio stream
|
||||
decoderSpecific.CopyTo(config, 13);
|
||||
byte[] es = [0, 0, 0, .. Descriptor(0x04, config), .. Descriptor(0x06, [0x02])];
|
||||
|
||||
@@ -216,6 +216,93 @@ public sealed partial class H264Decoder
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Whether the access unit carries a recovery point SEI (H.264 §D.1.8) with recovery_frame_cnt 0 and exact_match_flag
|
||||
/// 1: decoding from it gives exact pictures from it on in output order, as from an IDR picture. Only the SEI before
|
||||
/// the first slice counts.
|
||||
/// </summary>
|
||||
internal static bool HasExactRecoveryPoint(ReadOnlySpan<byte> accessUnit, int lengthSize)
|
||||
{
|
||||
var position = 0;
|
||||
while (true)
|
||||
{
|
||||
Range unit;
|
||||
var more = lengthSize == 0
|
||||
? NalUnits.NextAnnexB(accessUnit, ref position, out unit)
|
||||
: NalUnits.NextLengthPrefixed(accessUnit, lengthSize, ref position, out unit);
|
||||
if (!more)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var nal = accessUnit[unit];
|
||||
var type = nal[0] & 0x1F;
|
||||
if (type is 1 or 2 or 5)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (type != 6)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var sei = NalUnits.Parse(nal);
|
||||
var data = sei.Rbsp;
|
||||
var length = sei.Length;
|
||||
var p = sei.HeaderLength;
|
||||
while (p < length - 1)
|
||||
{
|
||||
var payloadType = 0;
|
||||
while (p < length && data[p] == 0xFF)
|
||||
{
|
||||
payloadType += 255;
|
||||
p++;
|
||||
}
|
||||
|
||||
var payloadSize = 0;
|
||||
if (p < length)
|
||||
{
|
||||
payloadType += data[p++];
|
||||
}
|
||||
|
||||
while (p < length && data[p] == 0xFF)
|
||||
{
|
||||
payloadSize += 255;
|
||||
p++;
|
||||
}
|
||||
|
||||
if (p >= length)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
payloadSize += data[p++];
|
||||
if (payloadType == 6)
|
||||
{
|
||||
// recovery_frame_cnt 0, then exact_match_flag 1 (§D.2.8): with 0 the pictures from here may
|
||||
// differ from those decoded from the IDR before, so it is no exact start.
|
||||
if (payloadSize <= 0)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var reader = new RbspReader(data, Math.Min(length, p + payloadSize), p);
|
||||
return reader.ReadUe() == 0 && reader.BitsLeft > 0 && reader.ReadFlag();
|
||||
}
|
||||
|
||||
p += payloadSize;
|
||||
}
|
||||
}
|
||||
catch (H264Exception)
|
||||
{
|
||||
// A damaged SEI says nothing.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void DecodeUnitsAnnexB(ReadOnlySpan<byte> stream)
|
||||
{
|
||||
var position = 0;
|
||||
|
||||
@@ -0,0 +1,322 @@
|
||||
using Febe.Core.Codecs.Containers;
|
||||
|
||||
namespace Febe.Core.Codecs.H264;
|
||||
|
||||
/// <summary>
|
||||
/// One picture of an I_PCM stream in 4:2:0: <see cref="Y"/> is <c>Width × Height</c> luma samples, <see cref="Cb"/> and
|
||||
/// <see cref="Cr"/> are <c>Width/2 × Height/2</c>, row by row. Width and height are multiples of 16.
|
||||
/// </summary>
|
||||
public sealed class H264PcmPicture
|
||||
{
|
||||
public H264PcmPicture(int width, int height)
|
||||
{
|
||||
if (width <= 0 || height <= 0 || width % 16 != 0 || height % 16 != 0)
|
||||
{
|
||||
throw new ArgumentOutOfRangeException(nameof(width), "Larghezza e altezza devono essere multipli di 16.");
|
||||
}
|
||||
|
||||
Width = width;
|
||||
Height = height;
|
||||
Y = new byte[width * height];
|
||||
Cb = new byte[width / 2 * (height / 2)];
|
||||
Cr = new byte[width / 2 * (height / 2)];
|
||||
}
|
||||
|
||||
public int Width { get; }
|
||||
|
||||
public int Height { get; }
|
||||
|
||||
public byte[] Y { get; }
|
||||
|
||||
public byte[] Cb { get; }
|
||||
|
||||
public byte[] Cr { get; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes H.264 streams made only of IDR pictures of I_PCM macroblocks (ITU-T H.264 §7.3: Baseline parameter sets, one
|
||||
/// slice per picture, every sample written as it is), muxed in MP4 with <see cref="Mp4Writer"/>. Every pixel is known
|
||||
/// and every picture is an exact start for a decoder: the demo's video (frames in <c>--demo</c>) and the tests use it.
|
||||
/// Nothing is compressed, so the files are large (about 1,5 bytes per pixel per picture): for short, small videos only.
|
||||
/// </summary>
|
||||
public static class H264PcmWriter
|
||||
{
|
||||
/// <summary>Width of the demo video (15 macroblocks, no cropping).</summary>
|
||||
public const int DemoWidth = 240;
|
||||
|
||||
/// <summary>Height of the demo video (27 macroblocks, no cropping).</summary>
|
||||
public const int DemoHeight = 432;
|
||||
|
||||
/// <summary>Pictures per second of the demo video.</summary>
|
||||
public const int DemoFps = 8;
|
||||
|
||||
/// <summary>Pictures of the demo video (two seconds).</summary>
|
||||
public const int DemoPictures = 16;
|
||||
|
||||
/// <summary>The sequence parameter set (RBSP with emulation prevention, no start code), POC type 2, no VUI.</summary>
|
||||
public static byte[] Sps(int width, int height)
|
||||
{
|
||||
var bits = new Bits();
|
||||
bits.Write(66, 8); // profile_idc: Baseline
|
||||
bits.Write(0, 8); // constraint_set flags
|
||||
bits.Write(30, 8); // level_idc 3.0
|
||||
bits.Ue(0); // seq_parameter_set_id
|
||||
bits.Ue(0); // log2_max_frame_num_minus4
|
||||
bits.Ue(2); // pic_order_cnt_type: output order = decoding order
|
||||
bits.Ue(1); // max_num_ref_frames
|
||||
bits.Write(0, 1); // gaps_in_frame_num_value_allowed_flag
|
||||
bits.Ue((uint)(width / 16) - 1); // pic_width_in_mbs_minus1
|
||||
bits.Ue((uint)(height / 16) - 1); // pic_height_in_map_units_minus1
|
||||
bits.Write(1, 1); // frame_mbs_only_flag
|
||||
bits.Write(1, 1); // direct_8x8_inference_flag
|
||||
bits.Write(0, 1); // frame_cropping_flag
|
||||
bits.Write(0, 1); // vui_parameters_present_flag
|
||||
return Nal(0x67, bits);
|
||||
}
|
||||
|
||||
/// <summary>The picture parameter set (CAVLC, one slice group, deblocking control present).</summary>
|
||||
public static byte[] Pps()
|
||||
{
|
||||
var bits = new Bits();
|
||||
bits.Ue(0); // pic_parameter_set_id
|
||||
bits.Ue(0); // seq_parameter_set_id
|
||||
bits.Write(0, 1); // entropy_coding_mode_flag: CAVLC
|
||||
bits.Write(0, 1); // bottom_field_pic_order_in_frame_present_flag
|
||||
bits.Ue(0); // num_slice_groups_minus1
|
||||
bits.Ue(0); // num_ref_idx_l0_default_active_minus1
|
||||
bits.Ue(0); // num_ref_idx_l1_default_active_minus1
|
||||
bits.Write(0, 1); // weighted_pred_flag
|
||||
bits.Write(0, 2); // weighted_bipred_idc
|
||||
bits.Se(0); // pic_init_qp_minus26
|
||||
bits.Se(0); // pic_init_qs_minus26
|
||||
bits.Se(0); // chroma_qp_index_offset
|
||||
bits.Write(1, 1); // deblocking_filter_control_present_flag
|
||||
bits.Write(0, 1); // constrained_intra_pred_flag
|
||||
bits.Write(0, 1); // redundant_pic_cnt_present_flag
|
||||
return Nal(0x68, bits);
|
||||
}
|
||||
|
||||
/// <summary>An IDR picture of I_PCM macroblocks (one slice, deblocking off), as a NAL unit without start code.</summary>
|
||||
/// <param name="picture">The samples.</param>
|
||||
/// <param name="idrPicId">idr_pic_id: two IDR pictures in a row must differ (0 and 1 alternate).</param>
|
||||
public static byte[] Idr(H264PcmPicture picture, int idrPicId)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(picture);
|
||||
var bits = new Bits(picture.Y.Length * 3 / 2 + 1024);
|
||||
bits.Ue(0); // first_mb_in_slice
|
||||
bits.Ue(7); // slice_type: I (all slices of the picture)
|
||||
bits.Ue(0); // pic_parameter_set_id
|
||||
bits.Write(0, 4); // frame_num
|
||||
bits.Ue((uint)idrPicId);
|
||||
bits.Write(0, 1); // no_output_of_prior_pics_flag
|
||||
bits.Write(0, 1); // long_term_reference_flag
|
||||
bits.Se(0); // slice_qp_delta
|
||||
bits.Ue(1); // disable_deblocking_filter_idc: off
|
||||
var mbWidth = picture.Width / 16;
|
||||
var mbHeight = picture.Height / 16;
|
||||
var chromaWidth = picture.Width / 2;
|
||||
for (var my = 0; my < mbHeight; my++)
|
||||
{
|
||||
for (var mx = 0; mx < mbWidth; mx++)
|
||||
{
|
||||
bits.Ue(25); // mb_type: I_PCM
|
||||
bits.Align(); // pcm_alignment_zero_bit
|
||||
for (var y = 0; y < 16; y++)
|
||||
{
|
||||
bits.Bytes(picture.Y.AsSpan(((my * 16) + y) * picture.Width + (mx * 16), 16));
|
||||
}
|
||||
|
||||
foreach (var plane in new[] { picture.Cb, picture.Cr })
|
||||
{
|
||||
for (var y = 0; y < 8; y++)
|
||||
{
|
||||
bits.Bytes(plane.AsSpan(((my * 8) + y) * chromaWidth + (mx * 8), 8));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return Nal(0x65, bits);
|
||||
}
|
||||
|
||||
/// <summary>The <c>avcC</c> of a stream with these parameter sets (ISO/IEC 14496-15 §5.3.3.1), lengths on 4 bytes.</summary>
|
||||
public static byte[] AvcConfiguration(byte[] sps, byte[] pps)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(sps);
|
||||
ArgumentNullException.ThrowIfNull(pps);
|
||||
return
|
||||
[
|
||||
1, sps[1], sps[2], sps[3], 0xFF, 0xE1,
|
||||
(byte)(sps.Length >> 8), (byte)sps.Length, .. sps,
|
||||
1, (byte)(pps.Length >> 8), (byte)pps.Length, .. pps,
|
||||
];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes an MP4 of <paramref name="count"/> pictures at <paramref name="fps"/> per second, picture <c>i</c> given by
|
||||
/// <paramref name="picture"/>, every one an IDR sync sample.
|
||||
/// </summary>
|
||||
/// <param name="output">Where the file goes (from its current position).</param>
|
||||
/// <param name="width">Width, a multiple of 16.</param>
|
||||
/// <param name="height">Height, a multiple of 16.</param>
|
||||
/// <param name="count">Pictures.</param>
|
||||
/// <param name="fps">Pictures per second.</param>
|
||||
/// <param name="picture">The samples of picture <c>i</c> (called once per picture, in order).</param>
|
||||
/// <param name="created">The creation date of the movie; null writes none.</param>
|
||||
public static void WriteMp4(Stream output, int width, int height, int count, int fps, Func<int, H264PcmPicture> picture, DateTimeOffset? created = null)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(output);
|
||||
ArgumentNullException.ThrowIfNull(picture);
|
||||
ArgumentOutOfRangeException.ThrowIfLessThan(count, 1);
|
||||
ArgumentOutOfRangeException.ThrowIfLessThan(fps, 1);
|
||||
var sps = Sps(width, height);
|
||||
var pps = Pps();
|
||||
var samples = new List<byte[]>(count);
|
||||
for (var i = 0; i < count; i++)
|
||||
{
|
||||
var p = picture(i);
|
||||
if (p.Width != width || p.Height != height)
|
||||
{
|
||||
throw new ArgumentException("Ogni fotogramma deve avere le dimensioni del video.", nameof(picture));
|
||||
}
|
||||
|
||||
var nal = Idr(p, i % 2);
|
||||
var sample = new byte[nal.Length + 4];
|
||||
System.Buffers.Binary.BinaryPrimitives.WriteInt32BigEndian(sample, nal.Length);
|
||||
nal.CopyTo(sample, 4);
|
||||
samples.Add(sample);
|
||||
}
|
||||
|
||||
const int Ticks = 1000;
|
||||
var track = new Mp4OutputTrack
|
||||
{
|
||||
IsVideo = true,
|
||||
Timescale = (long)fps * Ticks,
|
||||
Samples = [.. samples.Select((s, i) => new Mp4OutputSample(s.Length, (long)i * Ticks, (long)i * Ticks, true))],
|
||||
WriteSample = (i, s) => s.Write(samples[i]),
|
||||
Width = width,
|
||||
Height = height,
|
||||
AvcConfiguration = AvcConfiguration(sps, pps),
|
||||
LastSampleDuration = Ticks,
|
||||
};
|
||||
Mp4Writer.Write(output, [track], created);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The demo's video: <see cref="DemoWidth"/>×<see cref="DemoHeight"/>, <see cref="DemoFps"/> pictures per second for
|
||||
/// two seconds, a diagonal gradient that moves to the right with colours that change over time.
|
||||
/// </summary>
|
||||
public static byte[] DemoVideo()
|
||||
{
|
||||
using var output = new MemoryStream();
|
||||
WriteMp4(output, DemoWidth, DemoHeight, DemoPictures, DemoFps, DemoPicture, new DateTimeOffset(2026, 1, 1, 12, 0, 0, TimeSpan.Zero));
|
||||
return output.ToArray();
|
||||
}
|
||||
|
||||
/// <summary>Picture <paramref name="index"/> of the demo video (luma 16-235, chroma 16-240: no zero byte).</summary>
|
||||
public static H264PcmPicture DemoPicture(int index)
|
||||
{
|
||||
var p = new H264PcmPicture(DemoWidth, DemoHeight);
|
||||
var shift = index * 219 / DemoPictures;
|
||||
for (var y = 0; y < DemoHeight; y++)
|
||||
{
|
||||
for (var x = 0; x < DemoWidth; x++)
|
||||
{
|
||||
var ramp = ((x * 219 / DemoWidth) + (y * 219 / DemoHeight / 2) + 219 - shift) % 219;
|
||||
p.Y[(y * DemoWidth) + x] = (byte)(16 + ramp);
|
||||
}
|
||||
}
|
||||
|
||||
var chromaWidth = DemoWidth / 2;
|
||||
for (var y = 0; y < DemoHeight / 2; y++)
|
||||
{
|
||||
for (var x = 0; x < chromaWidth; x++)
|
||||
{
|
||||
p.Cb[(y * chromaWidth) + x] = (byte)(64 + (y * 128 / (DemoHeight / 2)));
|
||||
p.Cr[(y * chromaWidth) + x] = (byte)(64 + ((x * 64 / chromaWidth) + (index * 64 / DemoPictures)));
|
||||
}
|
||||
}
|
||||
|
||||
return p;
|
||||
}
|
||||
|
||||
/// <summary>A NAL unit (header byte, then the RBSP with its trailing bits and emulation prevention).</summary>
|
||||
private static byte[] Nal(byte header, Bits bits)
|
||||
{
|
||||
bits.Write(1, 1); // rbsp_stop_one_bit
|
||||
bits.Align();
|
||||
var rbsp = bits.ToArray();
|
||||
var output = new List<byte>(rbsp.Length + (rbsp.Length / 64) + 2) { header };
|
||||
var zeros = 0;
|
||||
foreach (var b in rbsp)
|
||||
{
|
||||
// Never two zero bytes followed by a byte up to 3 (§7.4.1).
|
||||
if (zeros >= 2 && b <= 3)
|
||||
{
|
||||
output.Add(3);
|
||||
zeros = 0;
|
||||
}
|
||||
|
||||
output.Add(b);
|
||||
zeros = b == 0 ? zeros + 1 : 0;
|
||||
}
|
||||
|
||||
return [.. output];
|
||||
}
|
||||
|
||||
/// <summary>A big-endian bit writer for the RBSP.</summary>
|
||||
private sealed class Bits(int capacity = 64)
|
||||
{
|
||||
private readonly List<byte> _bytes = new(capacity);
|
||||
private int _current;
|
||||
private int _used;
|
||||
|
||||
public void Write(uint value, int count)
|
||||
{
|
||||
for (var i = count - 1; i >= 0; i--)
|
||||
{
|
||||
_current = (_current << 1) | (int)((value >> i) & 1);
|
||||
if (++_used == 8)
|
||||
{
|
||||
_bytes.Add((byte)_current);
|
||||
_current = 0;
|
||||
_used = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void Ue(uint value)
|
||||
{
|
||||
var code = value + 1;
|
||||
var length = 32 - System.Numerics.BitOperations.LeadingZeroCount(code);
|
||||
Write(0, length - 1);
|
||||
Write(code, length);
|
||||
}
|
||||
|
||||
public void Se(int value) => Ue(value <= 0 ? (uint)(-2 * value) : (uint)((2 * value) - 1));
|
||||
|
||||
public void Align()
|
||||
{
|
||||
while (_used != 0)
|
||||
{
|
||||
Write(0, 1);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Whole bytes, after <see cref="Align"/>.</summary>
|
||||
public void Bytes(ReadOnlySpan<byte> data)
|
||||
{
|
||||
if (_used != 0)
|
||||
{
|
||||
throw new InvalidOperationException("Bytes only at a byte boundary.");
|
||||
}
|
||||
|
||||
foreach (var b in data)
|
||||
{
|
||||
_bytes.Add(b);
|
||||
}
|
||||
}
|
||||
|
||||
public byte[] ToArray() => _used == 0 ? [.. _bytes] : throw new InvalidOperationException("Not aligned.");
|
||||
}
|
||||
}
|
||||
@@ -71,6 +71,67 @@ internal static class ExifOrientation
|
||||
return 1;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Whether <paramref name="tiff"/> is a TIFF structure an encoder can carry: the «II*\0» or «MM\0*» header and a
|
||||
/// first IFD whose entry count lies inside the block. A damaged EXIF block fails and is left behind by a conversion.
|
||||
/// </summary>
|
||||
public static bool IsTiff(ReadOnlySpan<byte> tiff)
|
||||
{
|
||||
if (tiff.Length < 8 || !(tiff.StartsWith("II*\0"u8) || tiff.StartsWith("MM\0*"u8)))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var ifd = U32(tiff[4..], tiff[0] == (byte)'I');
|
||||
return ifd >= 8 && ifd <= (uint)(tiff.Length - 2);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The smallest EXIF block that carries <paramref name="orientation"/>: a TIFF header in the byte order asked, a
|
||||
/// first IFD at offset 8 with the one Orientation entry (SHORT, count 1) and no next IFD. 26 bytes.
|
||||
/// </summary>
|
||||
public static byte[] Minimal(int orientation, bool littleEndian)
|
||||
{
|
||||
ArgumentOutOfRangeException.ThrowIfLessThan(orientation, 1);
|
||||
ArgumentOutOfRangeException.ThrowIfGreaterThan(orientation, 8);
|
||||
var block = new byte[26];
|
||||
var b = block.AsSpan();
|
||||
b[0] = b[1] = littleEndian ? (byte)'I' : (byte)'M';
|
||||
W16(b[2..], 42, littleEndian);
|
||||
W32(b[4..], 8, littleEndian); // the first IFD
|
||||
W16(b[8..], 1, littleEndian); // one entry
|
||||
W16(b[10..], OrientationTag, littleEndian);
|
||||
W16(b[12..], 3, littleEndian); // SHORT
|
||||
W32(b[14..], 1, littleEndian); // count
|
||||
W16(b[18..], (ushort)orientation, littleEndian); // the value, left-justified in the 4-byte field
|
||||
// Bytes 22-25: the offset of the next IFD, 0.
|
||||
return block;
|
||||
}
|
||||
|
||||
private static void W16(Span<byte> b, ushort value, bool little)
|
||||
{
|
||||
if (little)
|
||||
{
|
||||
BinaryPrimitives.WriteUInt16LittleEndian(b, value);
|
||||
}
|
||||
else
|
||||
{
|
||||
BinaryPrimitives.WriteUInt16BigEndian(b, value);
|
||||
}
|
||||
}
|
||||
|
||||
private static void W32(Span<byte> b, uint value, bool little)
|
||||
{
|
||||
if (little)
|
||||
{
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(b, value);
|
||||
}
|
||||
else
|
||||
{
|
||||
BinaryPrimitives.WriteUInt32BigEndian(b, value);
|
||||
}
|
||||
}
|
||||
|
||||
private static ushort U16(ReadOnlySpan<byte> b, bool little) =>
|
||||
little ? BinaryPrimitives.ReadUInt16LittleEndian(b) : BinaryPrimitives.ReadUInt16BigEndian(b);
|
||||
|
||||
|
||||
@@ -77,7 +77,10 @@ public static class GifDecoder
|
||||
CanvasHeight,
|
||||
Math.Max(1, FrameCount),
|
||||
true,
|
||||
Comments is null ? ImageMetadata.Empty : new ImageMetadata { Texts = Comments });
|
||||
Comments is null ? ImageMetadata.Empty : new ImageMetadata { Texts = Comments })
|
||||
{
|
||||
IsAnimated = FrameCount > 1,
|
||||
};
|
||||
}
|
||||
|
||||
private static GifFile Walk(ReadOnlySpan<byte> data, ImageLimits limits, bool countFrames)
|
||||
|
||||
@@ -33,6 +33,10 @@ public sealed record ImageConversionOptions
|
||||
/// </param>
|
||||
/// <param name="Metadata">The metadata written.</param>
|
||||
/// <param name="NotCarried">What of the source's metadata the target could not take, in Italian, for the interface.</param>
|
||||
/// <param name="Losses">
|
||||
/// The same as note codes (tappa E3, <see cref="ImageConversionLosses"/>), once each, in a fixed order: what the export
|
||||
/// and the library conversion record.
|
||||
/// </param>
|
||||
public sealed record ImageConversionResult(
|
||||
byte[] Data,
|
||||
ImageFormat Source,
|
||||
@@ -41,7 +45,60 @@ public sealed record ImageConversionResult(
|
||||
int Height,
|
||||
bool Lossy,
|
||||
ImageMetadata Metadata,
|
||||
IReadOnlyList<string> NotCarried);
|
||||
IReadOnlyList<string> NotCarried,
|
||||
IReadOnlyList<string> Losses);
|
||||
|
||||
/// <summary>What a conversion does with a source (tappa E3, decisions D5 and D6).</summary>
|
||||
public enum ImageConversionAction
|
||||
{
|
||||
/// <summary>The source is already in the target format: it is copied byte for byte, without a note.</summary>
|
||||
CopyAsIs,
|
||||
|
||||
/// <summary>The source is decoded and written in the target format.</summary>
|
||||
Convert,
|
||||
|
||||
/// <summary>The source cannot be converted without losing what matters: it is copied as it is, with a note.</summary>
|
||||
CopyOriginal,
|
||||
}
|
||||
|
||||
/// <summary>The outcome of <see cref="ImageConverter.Check"/>.</summary>
|
||||
/// <param name="Action">What to do.</param>
|
||||
/// <param name="Source">The format of the source by its bytes; null when it is not recognised.</param>
|
||||
/// <param name="NoteCode">For <see cref="ImageConversionAction.CopyOriginal"/>, why (<c>AsIsHeif</c>, <c>AsIsAnimated</c>...).</param>
|
||||
public sealed record ImageConversionCheck(ImageConversionAction Action, ImageFormat? Source, string? NoteCode);
|
||||
|
||||
/// <summary>The note codes of what a conversion copies as it is or does not keep (decision D19 of tappa E3).</summary>
|
||||
public static class ImageConversionLosses
|
||||
{
|
||||
public const string AsIsHeif = "AsIsHeif";
|
||||
public const string AsIsAvif = "AsIsAvif";
|
||||
public const string AsIsRaw = "AsIsRaw";
|
||||
public const string AsIsAnimated = "AsIsAnimated";
|
||||
public const string AsIsNotDecodable = "AsIsNotDecodable";
|
||||
public const string AsIsDeepColor = "AsIsDeepColor";
|
||||
public const string AsIsCmyk = "AsIsCmyk";
|
||||
public const string AsIsTooLarge = "AsIsTooLarge";
|
||||
|
||||
public const string LostTexts = "LostTexts";
|
||||
public const string LostColorChunks = "LostColorChunks";
|
||||
public const string LostIcc = "LostIcc";
|
||||
public const string LostIccTooLarge = "LostIccTooLarge";
|
||||
public const string LostExifTooLarge = "LostExifTooLarge";
|
||||
public const string LostXmpTooLarge = "LostXmpTooLarge";
|
||||
public const string LostExtendedXmp = "LostExtendedXmp";
|
||||
public const string LostExifUnreadable = "LostExifUnreadable";
|
||||
public const string LostIptc = "LostIptc";
|
||||
public const string LostOtherSegments = "LostOtherSegments";
|
||||
public const string LostCommentTooLarge = "LostCommentTooLarge";
|
||||
public const string TransparencyWhite = "TransparencyWhite";
|
||||
|
||||
/// <summary>The order in which the codes are listed, so that the same source always gives the same note.</summary>
|
||||
internal static readonly string[] Order =
|
||||
[
|
||||
TransparencyWhite, LostExifUnreadable, LostExifTooLarge, LostIcc, LostIccTooLarge, LostXmpTooLarge, LostExtendedXmp,
|
||||
LostIptc, LostTexts, LostCommentTooLarge, LostColorChunks, LostOtherSegments,
|
||||
];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Turns a picture into another format with the same pixels and the same metadata, so that the converted file is
|
||||
@@ -57,9 +114,101 @@ public sealed record ImageConversionResult(
|
||||
/// </summary>
|
||||
public static class ImageConverter
|
||||
{
|
||||
/// <summary>The largest source a conversion reads into memory (decision D6 of tappa E3: 512 MiB).</summary>
|
||||
public const long MaxSourceBytes = 512L * 1024 * 1024;
|
||||
|
||||
/// <summary>The largest picture written as WebP (decision D6 of tappa E3: about 1.1 GB of working memory).</summary>
|
||||
public const long MaxWebPPixels = 40_000_000;
|
||||
|
||||
/// <summary>The formats a conversion can write.</summary>
|
||||
public static bool CanWrite(ImageFormat format) => format is ImageFormat.Jpeg or ImageFormat.Png or ImageFormat.WebP;
|
||||
|
||||
/// <summary>
|
||||
/// What a conversion of <paramref name="data"/> to <paramref name="target"/> does, from its bytes and its header
|
||||
/// only (tappa E3, D5 and D6): the same format is copied byte for byte (a lossy WebP to WebP too); HEIF, AVIF, TIFF
|
||||
/// and raw files, animations, damaged or unknown files, CMYK and deep-colour sources to PNG or WebP and pictures
|
||||
/// over the pixel budget of the target are copied as they are, with the reason. Never throws for a bad file.
|
||||
/// </summary>
|
||||
/// <exception cref="ArgumentException">The target is not JPEG, PNG or WebP.</exception>
|
||||
public static ImageConversionCheck Check(ReadOnlyMemory<byte> data, ImageFormat target, ImageConversionOptions? options = null)
|
||||
{
|
||||
if (!CanWrite(target))
|
||||
{
|
||||
throw new ArgumentException($"Febe non scrive immagini {target.ToString().ToUpperInvariant()}.", nameof(target));
|
||||
}
|
||||
|
||||
options ??= ImageConversionOptions.Default;
|
||||
var source = ImageFormatSniffer.Detect(data.Span);
|
||||
if (source == target)
|
||||
{
|
||||
return new ImageConversionCheck(ImageConversionAction.CopyAsIs, source, null);
|
||||
}
|
||||
|
||||
string? asIs = source switch
|
||||
{
|
||||
ImageFormat.Heif => ImageConversionLosses.AsIsHeif,
|
||||
ImageFormat.Avif => ImageConversionLosses.AsIsAvif,
|
||||
ImageFormat.Tiff => ImageConversionLosses.AsIsRaw, // TIFF and the raw formats built on it (DNG, NEF, CR2...)
|
||||
ImageFormat.Unknown => ImageConversionLosses.AsIsNotDecodable,
|
||||
_ => null,
|
||||
};
|
||||
if (asIs is null && data.Length > MaxSourceBytes)
|
||||
{
|
||||
asIs = ImageConversionLosses.AsIsTooLarge;
|
||||
}
|
||||
|
||||
if (asIs is null)
|
||||
{
|
||||
asIs = IdentifyOutcome(data, target, options.Limits);
|
||||
}
|
||||
|
||||
return asIs is null
|
||||
? new ImageConversionCheck(ImageConversionAction.Convert, source, null)
|
||||
: new ImageConversionCheck(ImageConversionAction.CopyOriginal, source == ImageFormat.Unknown ? null : source, asIs);
|
||||
}
|
||||
|
||||
private static string? IdentifyOutcome(ReadOnlyMemory<byte> data, ImageFormat target, ImageLimits limits)
|
||||
{
|
||||
ImageInfo info;
|
||||
try
|
||||
{
|
||||
info = ImageDecoder.Identify(data, limits);
|
||||
}
|
||||
catch (ImageLimitException)
|
||||
{
|
||||
return ImageConversionLosses.AsIsTooLarge;
|
||||
}
|
||||
catch (ImageDecodeException)
|
||||
{
|
||||
return ImageConversionLosses.AsIsNotDecodable;
|
||||
}
|
||||
|
||||
if (info.IsAnimated)
|
||||
{
|
||||
return ImageConversionLosses.AsIsAnimated;
|
||||
}
|
||||
|
||||
if (target != ImageFormat.Jpeg && info.IsCmyk)
|
||||
{
|
||||
return ImageConversionLosses.AsIsCmyk;
|
||||
}
|
||||
|
||||
if (target != ImageFormat.Jpeg && info.BitsPerSample > 8)
|
||||
{
|
||||
return ImageConversionLosses.AsIsDeepColor;
|
||||
}
|
||||
|
||||
var pixels = (long)info.Width * info.Height;
|
||||
var tooLarge = target == ImageFormat.WebP
|
||||
? pixels > MaxWebPPixels || info.Width > WebPEncoder.MaxDimension || info.Height > WebPEncoder.MaxDimension
|
||||
: pixels > ImageLimits.Default.MaxPixels;
|
||||
|
||||
// What the decoder will ask besides the pixels (a progressive JPEG keeps its coefficients): a file the decoder
|
||||
// would refuse is too large for the conversion, never «not readable» (§4.10).
|
||||
tooLarge |= info.DecodeWorkingBytes > limits.MaxWorkingBytes;
|
||||
return tooLarge ? ImageConversionLosses.AsIsTooLarge : null;
|
||||
}
|
||||
|
||||
/// <summary>Converts <paramref name="source"/> (any format <see cref="ImageDecoder"/> reads) to <paramref name="target"/>.</summary>
|
||||
/// <exception cref="ArgumentException">The target is not JPEG, PNG or WebP.</exception>
|
||||
/// <exception cref="ImageDecodeException">The source is damaged, too large or in a format Febe does not read.</exception>
|
||||
@@ -85,8 +234,58 @@ public static class ImageConverter
|
||||
lossy = true;
|
||||
}
|
||||
|
||||
var metadata = info.Metadata;
|
||||
var losses = new HashSet<string>(StringComparer.Ordinal);
|
||||
var data = EncodeCore(image, target, info.Metadata, options, notCarried, losses, out var written);
|
||||
return new ImageConversionResult(data, info.Format, target, image.Width, image.Height, lossy, written, notCarried, Ordered(losses));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes <paramref name="image"/> (straight RGBA) as <paramref name="target"/> with what of
|
||||
/// <paramref name="metadata"/> the target can carry (none when null: the frames of tappa E3). A transparent image
|
||||
/// to JPEG is first flattened over the background of the options, on a copy: <paramref name="image"/> is never
|
||||
/// changed.
|
||||
/// </summary>
|
||||
/// <exception cref="ArgumentException">The target is not JPEG, PNG or WebP, or a WebP side is over 16384.</exception>
|
||||
public static byte[] Encode(RgbaImage image, ImageFormat target, ImageMetadata? metadata, ImageConversionOptions? options = null)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(image);
|
||||
if (!CanWrite(target))
|
||||
{
|
||||
throw new ArgumentException($"Febe non scrive immagini {target.ToString().ToUpperInvariant()}.", nameof(target));
|
||||
}
|
||||
|
||||
options ??= ImageConversionOptions.Default;
|
||||
if (target == ImageFormat.Jpeg && !image.IsOpaque())
|
||||
{
|
||||
using var copy = new RgbaImage(image.Width, image.Height, image.ToArray());
|
||||
return EncodeCore(copy, target, metadata ?? ImageMetadata.Empty, options, [], new HashSet<string>(StringComparer.Ordinal), out _);
|
||||
}
|
||||
|
||||
return EncodeCore(image, target, metadata ?? ImageMetadata.Empty, options, [], new HashSet<string>(StringComparer.Ordinal), out _);
|
||||
}
|
||||
|
||||
/// <summary>The codes of <paramref name="losses"/> in the order of <see cref="ImageConversionLosses.Order"/>.</summary>
|
||||
private static string[] Ordered(HashSet<string> losses) =>
|
||||
[.. ImageConversionLosses.Order.Where(losses.Contains)];
|
||||
|
||||
/// <summary>Encodes; flattens <paramref name="image"/> in place for a JPEG target that is not opaque.</summary>
|
||||
private static byte[] EncodeCore(
|
||||
RgbaImage image,
|
||||
ImageFormat target,
|
||||
ImageMetadata metadata,
|
||||
ImageConversionOptions options,
|
||||
List<string> notCarried,
|
||||
HashSet<string> losses,
|
||||
out ImageMetadata written)
|
||||
{
|
||||
var exif = metadata.Exif;
|
||||
if (exif is not null && !ExifOrientation.IsTiff(exif))
|
||||
{
|
||||
notCarried.Add("l'EXIF (rovinato: non è una struttura TIFF leggibile)");
|
||||
losses.Add(ImageConversionLosses.LostExifUnreadable);
|
||||
exif = OrientationOnly(metadata);
|
||||
}
|
||||
|
||||
var icc = metadata.IccProfile;
|
||||
var iccName = metadata.IccProfileName;
|
||||
if (icc is not null && IccColorSpace(icc) != "RGB ")
|
||||
@@ -97,6 +296,7 @@ public static class ImageConverter
|
||||
"GRAY" => "il profilo colore in scala di grigi (i pixel sono scritti in RGB)",
|
||||
_ => "il profilo colore (non descrive pixel RGB)",
|
||||
});
|
||||
losses.Add(ImageConversionLosses.LostIcc);
|
||||
icc = null;
|
||||
iccName = null;
|
||||
}
|
||||
@@ -104,23 +304,49 @@ public static class ImageConverter
|
||||
foreach (var chunk in metadata.ColorChunks)
|
||||
{
|
||||
notCarried.Add($"il blocco di colore {chunk} del PNG (non viene scritto)");
|
||||
losses.Add(ImageConversionLosses.LostColorChunks);
|
||||
}
|
||||
|
||||
foreach (var block in metadata.Unread)
|
||||
{
|
||||
switch (block)
|
||||
{
|
||||
case "APP13":
|
||||
notCarried.Add("i dati IPTC (segmento APP13)");
|
||||
losses.Add(ImageConversionLosses.LostIptc);
|
||||
break;
|
||||
case "ExtendedXmp":
|
||||
notCarried.Add("l'XMP esteso");
|
||||
losses.Add(ImageConversionLosses.LostExtendedXmp);
|
||||
break;
|
||||
default:
|
||||
notCarried.Add($"il blocco {block}");
|
||||
losses.Add(ImageConversionLosses.LostOtherSegments);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
var xmp = metadata.Xmp;
|
||||
var texts = metadata.Texts;
|
||||
IReadOnlyList<ImageText> writtenTexts = texts;
|
||||
byte[] data;
|
||||
switch (target)
|
||||
{
|
||||
case ImageFormat.Png:
|
||||
data = PngEncoder.Encode(image, new PngEncoderOptions
|
||||
{
|
||||
Exif = exif,
|
||||
IccProfile = icc,
|
||||
IccProfileName = ValidIccName(iccName) ?? PngEncoderOptions.Default.IccProfileName,
|
||||
Xmp = xmp,
|
||||
Texts = PngTexts(texts, notCarried),
|
||||
});
|
||||
break;
|
||||
var pngTexts = PngTexts(texts, notCarried, losses);
|
||||
writtenTexts = pngTexts;
|
||||
data = PngEncoder.Encode(image, new PngEncoderOptions
|
||||
{
|
||||
Exif = exif,
|
||||
IccProfile = icc,
|
||||
IccProfileName = ValidIccName(iccName) ?? PngEncoderOptions.Default.IccProfileName,
|
||||
Xmp = xmp,
|
||||
Texts = pngTexts,
|
||||
});
|
||||
break;
|
||||
}
|
||||
|
||||
case ImageFormat.WebP:
|
||||
if (image.Width > WebPEncoder.MaxDimension || image.Height > WebPEncoder.MaxDimension)
|
||||
{
|
||||
@@ -130,8 +356,10 @@ public static class ImageConverter
|
||||
if (texts.Count > 0)
|
||||
{
|
||||
notCarried.Add(texts.Count == 1 ? "un testo (WebP non ne ha)" : $"{texts.Count} testi (WebP non ne ha)");
|
||||
losses.Add(ImageConversionLosses.LostTexts);
|
||||
}
|
||||
|
||||
writtenTexts = [];
|
||||
data = WebPEncoder.Encode(image, new WebPEncoderOptions { Exif = exif, IccProfile = icc, Xmp = xmp });
|
||||
break;
|
||||
default:
|
||||
@@ -139,25 +367,47 @@ public static class ImageConverter
|
||||
if (exif is not null && exif.Length > JpegMaxSegmentPayload - 6)
|
||||
{
|
||||
notCarried.Add($"l'EXIF ({exif.Length} byte, più di quanto entra in un segmento JPEG)");
|
||||
exif = null;
|
||||
losses.Add(ImageConversionLosses.LostExifTooLarge);
|
||||
exif = OrientationOnly(metadata);
|
||||
}
|
||||
|
||||
if (xmp is not null && Encoding.UTF8.GetByteCount(xmp) > JpegMaxSegmentPayload - 29)
|
||||
{
|
||||
notCarried.Add("l'XMP (più di quanto entra in un segmento JPEG)");
|
||||
losses.Add(ImageConversionLosses.LostXmpTooLarge);
|
||||
xmp = null;
|
||||
}
|
||||
|
||||
var comments = new List<string>();
|
||||
foreach (var text in texts)
|
||||
if (icc is not null && (icc.Length + JpegIccChunk - 1) / JpegIccChunk > 255)
|
||||
{
|
||||
comments.Add(text.Keyword.Length == 0 || text.Keyword == "Comment" ? text.Text : $"{text.Keyword}: {text.Text}");
|
||||
notCarried.Add($"il profilo colore ({icc.Length} byte, più di quanto entra in 255 segmenti JPEG)");
|
||||
losses.Add(ImageConversionLosses.LostIccTooLarge);
|
||||
icc = null;
|
||||
iccName = null;
|
||||
}
|
||||
|
||||
var comments = new List<string>();
|
||||
var kept = new List<ImageText>();
|
||||
foreach (var text in texts)
|
||||
{
|
||||
var comment = text.Keyword.Length == 0 || text.Keyword == "Comment" ? text.Text : $"{text.Keyword}: {text.Text}";
|
||||
if (Encoding.UTF8.GetByteCount(comment) > JpegMaxSegmentPayload)
|
||||
{
|
||||
notCarried.Add("un commento (più lungo di quanto entra in un segmento JPEG)");
|
||||
losses.Add(ImageConversionLosses.LostCommentTooLarge);
|
||||
continue;
|
||||
}
|
||||
|
||||
comments.Add(comment);
|
||||
kept.Add(text);
|
||||
}
|
||||
|
||||
writtenTexts = kept;
|
||||
if (!image.IsOpaque())
|
||||
{
|
||||
ImageBackground.Flatten(image, options.JpegBackground);
|
||||
notCarried.Add("la trasparenza (JPEG non ce l'ha: le parti trasparenti diventano dello sfondo)");
|
||||
losses.Add(ImageConversionLosses.TransparencyWhite);
|
||||
}
|
||||
|
||||
data = JpegEncoder.Encode(image, new JpegEncoderOptions
|
||||
@@ -173,18 +423,28 @@ public static class ImageConverter
|
||||
}
|
||||
}
|
||||
|
||||
var written = new ImageMetadata
|
||||
written = new ImageMetadata
|
||||
{
|
||||
Exif = exif,
|
||||
Orientation = metadata.Orientation,
|
||||
Orientation = exif is null ? 1 : metadata.Orientation,
|
||||
IccProfile = icc,
|
||||
IccProfileName = icc is null ? null : iccName,
|
||||
Xmp = xmp,
|
||||
Texts = target == ImageFormat.WebP ? [] : texts,
|
||||
Texts = writtenTexts,
|
||||
};
|
||||
return new ImageConversionResult(data, info.Format, target, image.Width, image.Height, lossy, written, notCarried);
|
||||
return data;
|
||||
}
|
||||
|
||||
/// <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>
|
||||
internal static string? IccColorSpace(ReadOnlySpan<byte> profile)
|
||||
{
|
||||
@@ -211,6 +471,9 @@ public static class ImageConverter
|
||||
/// <summary>Bytes of payload in one JPEG marker segment (65535 less the two of the length).</summary>
|
||||
private const int JpegMaxSegmentPayload = 65533;
|
||||
|
||||
/// <summary>Bytes of an ICC profile in one APP2 segment (the payload less «ICC_PROFILE\0» and the two counters).</summary>
|
||||
private const int JpegIccChunk = 65519;
|
||||
|
||||
private static string? ValidIccName(string? name)
|
||||
{
|
||||
if (string.IsNullOrEmpty(name) || name.Length > 79)
|
||||
@@ -229,7 +492,7 @@ public static class ImageConverter
|
||||
return name.Trim().Length == name.Length ? name : null;
|
||||
}
|
||||
|
||||
private static List<ImageText> PngTexts(IReadOnlyList<ImageText> texts, List<string> notCarried)
|
||||
private static List<ImageText> PngTexts(IReadOnlyList<ImageText> texts, List<string> notCarried, HashSet<string> losses)
|
||||
{
|
||||
var result = new List<ImageText>(texts.Count);
|
||||
foreach (var text in texts)
|
||||
@@ -238,6 +501,7 @@ public static class ImageConverter
|
||||
if (!PngEncoder.IsValidKeyword(keyword))
|
||||
{
|
||||
notCarried.Add($"il testo «{keyword}» (nome non valido per un PNG)");
|
||||
losses.Add(ImageConversionLosses.LostTexts);
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -248,6 +512,7 @@ public static class ImageConverter
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// <summary>Composites an image over a plain colour.</summary>
|
||||
public static class ImageBackground
|
||||
{
|
||||
|
||||
@@ -39,6 +39,13 @@ public sealed class ImageMetadata
|
||||
/// not applied to the pixels and no encoder writes them, so a conversion says they are left behind.
|
||||
/// </summary>
|
||||
public IReadOnlyList<string> ColorChunks { get; init; } = [];
|
||||
|
||||
/// <summary>
|
||||
/// Blocks of the file that hold data no reader of Febe interprets and no encoder writes, in file order and once
|
||||
/// each: JPEG segments («APP13» for IPTC/Photoshop, «ExtendedXmp», «APP2» for MPF, other «APPn»), PNG ancillary
|
||||
/// chunks («pHYs», «tIME»...), WebP chunks. A conversion reports them as not kept.
|
||||
/// </summary>
|
||||
public IReadOnlyList<string> Unread { get; init; } = [];
|
||||
}
|
||||
|
||||
/// <summary>What a file says about its image, read without decoding the pixels.</summary>
|
||||
@@ -55,4 +62,20 @@ public sealed record ImageInfo(ImageFormat Format, int Width, int Height, int Fr
|
||||
/// for GIF and WebP). The decoders give 8-bit samples, so above 8 the decoded pixels have lost precision.
|
||||
/// </summary>
|
||||
public int BitsPerSample { get; init; } = 8;
|
||||
|
||||
/// <summary>
|
||||
/// Whether the file is an animation, by the presence of its marks (spec §4.10): a PNG with an <c>acTL</c> chunk
|
||||
/// before its image data, a WebP with an <c>ANIM</c> or <c>ANMF</c> chunk, a GIF with more than one image.
|
||||
/// </summary>
|
||||
public bool IsAnimated { get; init; }
|
||||
|
||||
/// <summary>Whether the pixels are stored as CMYK or YCCK (a JPEG with four components).</summary>
|
||||
public bool IsCmyk { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// The working memory a full decode asks besides the decoded image, as the decoder checks it against
|
||||
/// <see cref="ImageLimits.MaxWorkingBytes"/> (a progressive or lossless JPEG keeps its coefficients or samples:
|
||||
/// up to 9 bytes a pixel); 0 when the format's decoder needs none worth counting before it starts.
|
||||
/// </summary>
|
||||
public long DecodeWorkingBytes { get; init; }
|
||||
}
|
||||
@@ -76,6 +76,7 @@ internal sealed partial class JpegFile : IDisposable
|
||||
private string? _xmp;
|
||||
private List<(int Sequence, int Count, byte[] Data)>? _iccChunks;
|
||||
private List<ImageText>? _texts;
|
||||
private List<string>? _unread;
|
||||
|
||||
private bool _allocated;
|
||||
private bool _pooledArrays;
|
||||
@@ -320,7 +321,7 @@ internal sealed partial class JpegFile : IDisposable
|
||||
public ImageInfo ToInfo()
|
||||
{
|
||||
var icc = AssembleIcc();
|
||||
var metadata = _exif is null && icc is null && _xmp is null && _texts is null
|
||||
var metadata = _exif is null && icc is null && _xmp is null && _texts is null && _unread is null
|
||||
? ImageMetadata.Empty
|
||||
: new ImageMetadata
|
||||
{
|
||||
@@ -329,8 +330,14 @@ internal sealed partial class JpegFile : IDisposable
|
||||
IccProfile = icc,
|
||||
Xmp = _xmp,
|
||||
Texts = _texts ?? [],
|
||||
Unread = _unread ?? [],
|
||||
};
|
||||
return new ImageInfo(ImageFormat.Jpeg, Width, Height, 1, false, metadata) { BitsPerSample = Precision };
|
||||
return new ImageInfo(ImageFormat.Jpeg, Width, Height, 1, false, metadata)
|
||||
{
|
||||
BitsPerSample = Precision,
|
||||
IsCmyk = Components.Length == 4,
|
||||
DecodeWorkingBytes = Height == 0 ? 0 : WorkingBytes(Progressive, 0),
|
||||
};
|
||||
}
|
||||
|
||||
public JpegCoefficients ToCoefficients()
|
||||
@@ -476,6 +483,34 @@ internal sealed partial class JpegFile : IDisposable
|
||||
|
||||
private static int Ceil(int value, int divisor) => (value + divisor - 1) / divisor;
|
||||
|
||||
/// <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)
|
||||
{
|
||||
if (p.Length < 2)
|
||||
@@ -625,6 +660,12 @@ internal sealed partial class JpegFile : IDisposable
|
||||
return;
|
||||
}
|
||||
|
||||
if (marker is not (0xE1 or 0xE2))
|
||||
{
|
||||
NotRead(marker == 0xED ? "APP13" : $"APP{marker - 0xE0}");
|
||||
return;
|
||||
}
|
||||
|
||||
// Damaged or oversized metadata is skipped: it must never stop an image from being shown.
|
||||
if (marker == 0xE1)
|
||||
{
|
||||
@@ -644,8 +685,16 @@ internal sealed partial class JpegFile : IDisposable
|
||||
_xmp = Encoding.UTF8.GetString(packet);
|
||||
}
|
||||
}
|
||||
else if (p.StartsWith(ExtendedXmpNamespace))
|
||||
{
|
||||
NotRead("ExtendedXmp");
|
||||
}
|
||||
else if (!(p.Length > 6 && p[..4].SequenceEqual("Exif"u8)) && !p.StartsWith(XmpNamespace))
|
||||
{
|
||||
NotRead("APP1");
|
||||
}
|
||||
}
|
||||
else if (marker == 0xE2 && p.Length > 14 && p[..12].SequenceEqual("ICC_PROFILE\0"u8))
|
||||
else if (p.Length > 14 && p[..12].SequenceEqual("ICC_PROFILE\0"u8))
|
||||
{
|
||||
int sequence = p[12];
|
||||
int count = p[13];
|
||||
@@ -655,6 +704,22 @@ internal sealed partial class JpegFile : IDisposable
|
||||
(_iccChunks ??= []).Add((sequence, count, chunk.ToArray()));
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
NotRead("APP2"); // MPF and the like
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The namespace that starts an extended XMP APP1 segment (XMP part 3), with its terminating zero.</summary>
|
||||
private static ReadOnlySpan<byte> ExtendedXmpNamespace => "http://ns.adobe.com/xmp/extension/\0"u8;
|
||||
|
||||
private void NotRead(string name)
|
||||
{
|
||||
_unread ??= [];
|
||||
if (!_unread.Contains(name))
|
||||
{
|
||||
_unread.Add(name);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The namespace that starts an XMP APP1 segment, with its terminating zero.</summary>
|
||||
@@ -801,25 +866,7 @@ internal sealed partial class JpegFile : IDisposable
|
||||
|
||||
_limits.CheckSize(OutputWidth, OutputHeight);
|
||||
var keepCoefficients = Progressive || _mode == Mode.Coefficients;
|
||||
long bytes = 0;
|
||||
foreach (var c in Components)
|
||||
{
|
||||
var unit = Lossless ? 1 : 8;
|
||||
long samples = (long)c.PaddedUnitsWide * unit * c.PaddedUnitsHigh * unit;
|
||||
bytes += samples >> (2 * _scaleShift);
|
||||
if (keepCoefficients && !Lossless)
|
||||
{
|
||||
bytes += samples * 2;
|
||||
}
|
||||
|
||||
if (Lossless)
|
||||
{
|
||||
// The samples before the point transform, and for arithmetic coding the class of every difference.
|
||||
bytes += samples * (Arithmetic ? 3 : 2);
|
||||
}
|
||||
}
|
||||
|
||||
_limits.CheckWorkingBytes(bytes);
|
||||
_limits.CheckWorkingBytes(WorkingBytes(keepCoefficients, _scaleShift));
|
||||
_pooledArrays = _mode == Mode.Pixels;
|
||||
foreach (var c in Components)
|
||||
{
|
||||
|
||||
@@ -103,6 +103,8 @@ public static class PngDecoder
|
||||
public string? Xmp;
|
||||
public List<ImageText>? Texts;
|
||||
public List<string>? ColorChunks;
|
||||
public List<string>? Unread;
|
||||
public bool Animated;
|
||||
|
||||
public int Channels => ColorType switch { 2 => 3, 4 => 2, 6 => 4, _ => 1 };
|
||||
|
||||
@@ -114,7 +116,7 @@ public static class PngDecoder
|
||||
Height,
|
||||
FrameCount,
|
||||
ColorType is 4 or 6 || HasColorKey || HasPaletteAlpha,
|
||||
Exif is null && Icc is null && Xmp is null && Texts is null && ColorChunks is null
|
||||
Exif is null && Icc is null && Xmp is null && Texts is null && ColorChunks is null && Unread is null
|
||||
? ImageMetadata.Empty
|
||||
: new ImageMetadata
|
||||
{
|
||||
@@ -125,9 +127,11 @@ public static class PngDecoder
|
||||
Xmp = Xmp,
|
||||
Texts = Texts ?? [],
|
||||
ColorChunks = ColorChunks ?? [],
|
||||
Unread = Unread ?? [],
|
||||
})
|
||||
{
|
||||
BitsPerSample = ColorType == 3 ? 8 : BitDepth,
|
||||
IsAnimated = Animated,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -248,6 +252,7 @@ public static class PngDecoder
|
||||
break;
|
||||
|
||||
case "acTL":
|
||||
file.Animated |= idatState == 0;
|
||||
if (payload.Length >= 8 && idatState == 0)
|
||||
{
|
||||
var frames = BinaryPrimitives.ReadUInt32BigEndian(payload);
|
||||
@@ -272,12 +277,20 @@ public static class PngDecoder
|
||||
|
||||
break;
|
||||
|
||||
case "fcTL" or "fdAT":
|
||||
break;
|
||||
|
||||
default:
|
||||
if (critical)
|
||||
{
|
||||
throw new ImageFormatNotSupportedException($"PNG con un blocco critico che Febe non conosce ({name}).");
|
||||
}
|
||||
|
||||
if (readMetadata && !(file.Unread ??= []).Contains(name))
|
||||
{
|
||||
file.Unread.Add(name);
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -576,7 +576,7 @@ internal static class Vp8LEncoder
|
||||
private static int ChooseCacheBits(uint[] pixels, ReadOnlySpan<int> lengths)
|
||||
{
|
||||
var bestBits = 0;
|
||||
var bestCost = double.MaxValue;
|
||||
var bestCost = long.MaxValue;
|
||||
var green = new int[256 + NumLengthCodes + (1 << 10)];
|
||||
var red = new int[256];
|
||||
var blue = new int[256];
|
||||
@@ -637,8 +637,10 @@ internal static class Vp8LEncoder
|
||||
return bestBits;
|
||||
}
|
||||
|
||||
// Bits to code the counts with an ideal code, plus a rough price for describing the code.
|
||||
private static double Entropy(ReadOnlySpan<int> counts)
|
||||
// Bits to code the counts with an ideal code, plus a rough price for describing the code, in units of
|
||||
// 2^-LogFractionBits bits: Σ c·log2(total / c) = total·log2(total) − Σ c·log2(c), in integers only, so that the
|
||||
// choice never depends on the floating-point library of the platform (decision D9 of tappa E3).
|
||||
internal static long Entropy(ReadOnlySpan<int> counts)
|
||||
{
|
||||
long total = 0;
|
||||
var used = 0;
|
||||
@@ -650,19 +652,66 @@ internal static class Vp8LEncoder
|
||||
|
||||
if (used <= 1)
|
||||
{
|
||||
return 8;
|
||||
return 8L << LogFractionBits;
|
||||
}
|
||||
|
||||
var bits = 0.0;
|
||||
var bits = total * Log2Fixed((ulong)total);
|
||||
foreach (var c in counts)
|
||||
{
|
||||
if (c > 0)
|
||||
{
|
||||
bits -= c * Math.Log2((double)c / total);
|
||||
bits -= c * Log2Fixed((ulong)c);
|
||||
}
|
||||
}
|
||||
|
||||
return bits + (used * 4.0);
|
||||
return bits + ((long)used * 4 << LogFractionBits);
|
||||
}
|
||||
|
||||
/// <summary>Fractional bits of <see cref="Log2Fixed"/>.</summary>
|
||||
internal const int LogFractionBits = 16;
|
||||
|
||||
/// <summary>Base-2 logarithms of 1-4095 in fixed point, computed once by <see cref="Log2Exact"/>.</summary>
|
||||
private static readonly long[] SmallLog2 = BuildSmallLog2();
|
||||
|
||||
private static long[] BuildSmallLog2()
|
||||
{
|
||||
var table = new long[4096];
|
||||
for (var i = 1; i < table.Length; i++)
|
||||
{
|
||||
table[i] = Log2Exact((ulong)i);
|
||||
}
|
||||
|
||||
return table;
|
||||
}
|
||||
|
||||
/// <summary>log2(<paramref name="value"/>) in fixed point with <see cref="LogFractionBits"/> fractional bits; 0 for 0.</summary>
|
||||
internal static long Log2Fixed(ulong value) => value < (ulong)SmallLog2.Length ? SmallLog2[value] : Log2Exact(value);
|
||||
|
||||
/// <summary>
|
||||
/// log2 by integers only: the integer part from the highest bit, the fraction bit by bit by repeated squaring of
|
||||
/// the mantissa (kept as a 1.31 fixed-point number), rounded down.
|
||||
/// </summary>
|
||||
private static long Log2Exact(ulong value)
|
||||
{
|
||||
if (value == 0)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
var high = 63 - System.Numerics.BitOperations.LeadingZeroCount(value);
|
||||
ulong mantissa = high >= 31 ? value >> (high - 31) : value << (31 - high); // in [2^31, 2^32): 1.0 ≤ m < 2.0
|
||||
long fraction = 0;
|
||||
for (var bit = LogFractionBits - 1; bit >= 0; bit--)
|
||||
{
|
||||
mantissa = (mantissa * mantissa) >> 31;
|
||||
if (mantissa >= 1UL << 32)
|
||||
{
|
||||
mantissa >>= 1;
|
||||
fraction |= 1L << bit;
|
||||
}
|
||||
}
|
||||
|
||||
return ((long)high << LogFractionBits) | fraction;
|
||||
}
|
||||
|
||||
// Writes a prefix code: the simple form for at most two symbols below 256, otherwise the code lengths, run-length
|
||||
|
||||
@@ -96,6 +96,8 @@ public static class WebPDecoder
|
||||
public byte[]? Exif;
|
||||
public byte[]? Icc;
|
||||
public string? Xmp;
|
||||
public bool Animated;
|
||||
public List<string>? Unread;
|
||||
|
||||
public ImageInfo ToInfo() => new(
|
||||
ImageFormat.WebP,
|
||||
@@ -103,9 +105,12 @@ public static class WebPDecoder
|
||||
Height,
|
||||
FrameCount,
|
||||
HasAlpha,
|
||||
Exif is null && Icc is null && Xmp is null
|
||||
Exif is null && Icc is null && Xmp is null && Unread is null
|
||||
? ImageMetadata.Empty
|
||||
: new ImageMetadata { Exif = Exif, Orientation = Exif is null ? 1 : ExifOrientation.Read(Exif), IccProfile = Icc, Xmp = Xmp });
|
||||
: new ImageMetadata { Exif = Exif, Orientation = Exif is null ? 1 : ExifOrientation.Read(Exif), IccProfile = Icc, Xmp = Xmp, Unread = Unread ?? [] })
|
||||
{
|
||||
IsAnimated = Animated,
|
||||
};
|
||||
}
|
||||
|
||||
private static WebPFile Parse(byte[] data, int offset, int length, ImageLimits limits, bool readMetadata)
|
||||
@@ -174,7 +179,11 @@ public static class WebPDecoder
|
||||
var chunk = chunks[i];
|
||||
switch (chunk.Type)
|
||||
{
|
||||
case Anim:
|
||||
file.Animated = true;
|
||||
break;
|
||||
case Anmf:
|
||||
file.Animated = true;
|
||||
if (frames++ == 0)
|
||||
{
|
||||
file.FirstFrame = ReadFrame(data, chunk, file.Width, file.Height);
|
||||
@@ -200,6 +209,25 @@ public static class WebPDecoder
|
||||
case Xmp when readMetadata && file.Xmp is null && chunk.Length <= budget:
|
||||
file.Xmp = Encoding.UTF8.GetString(data, chunk.Start, chunk.Length);
|
||||
budget -= chunk.Length;
|
||||
break;
|
||||
case Iccp or Exif or Xmp:
|
||||
break;
|
||||
default:
|
||||
if (readMetadata)
|
||||
{
|
||||
var name = string.Create(4, chunk.Type, static (c, t) =>
|
||||
{
|
||||
for (var k = 0; k < 4; k++)
|
||||
{
|
||||
c[k] = (char)(byte)(t >> (8 * k));
|
||||
}
|
||||
}).TrimEnd();
|
||||
if (!(file.Unread ??= []).Contains(name))
|
||||
{
|
||||
file.Unread.Add(name);
|
||||
}
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
using System.Security.Cryptography;
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Core.Library;
|
||||
using Febe.Core.Library.Conversion;
|
||||
|
||||
namespace Febe.Core.Export;
|
||||
|
||||
/// <summary>
|
||||
/// The conversion of a library file for a copy (tappa E3, WP1.6b): <see cref="MediaConverter"/> with the files of the
|
||||
/// export environment, and the hash of content that is only known once written (a remux).
|
||||
/// </summary>
|
||||
internal static class ExportConversion
|
||||
{
|
||||
/// <summary>Prepares the library file at <paramref name="source"/> in <paramref name="target"/> (never Original).</summary>
|
||||
/// <exception cref="ContentChangedException">A photo's bytes are not those of <paramref name="sha256"/>.</exception>
|
||||
public static Task<MediaConversionResult> PrepareAsync(ExportEnvironment env, string source, Media media, ExportFormat target, string sha256, CancellationToken ct) =>
|
||||
MediaConverter.PrepareAsync(() => env.FileSystem.OpenRandomAccess(source), media.RelativePath!, media.Kind, target, sha256, env.Throttle, ct);
|
||||
|
||||
/// <summary>The SHA-256 (lowercase hex) and length of what <paramref name="produce"/> writes, written nowhere.</summary>
|
||||
public static async Task<(string Sha256, long Length)> HashAsync(Func<Stream, CancellationToken, Task> produce, CancellationToken ct)
|
||||
{
|
||||
await using var sink = new HashingSink();
|
||||
await produce(sink, ct).ConfigureAwait(false);
|
||||
return (sink.Finish(), sink.Length);
|
||||
}
|
||||
|
||||
/// <summary>A stream that only hashes and counts what is written to it.</summary>
|
||||
private sealed class HashingSink : Stream
|
||||
{
|
||||
private readonly IncrementalHash hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256);
|
||||
private long length;
|
||||
|
||||
public override bool CanRead => false;
|
||||
|
||||
public override bool CanSeek => false;
|
||||
|
||||
public override bool CanWrite => true;
|
||||
|
||||
public override long Length => length;
|
||||
|
||||
public override long Position
|
||||
{
|
||||
get => length;
|
||||
set => throw new NotSupportedException();
|
||||
}
|
||||
|
||||
public string Finish() => Convert.ToHexStringLower(hash.GetHashAndReset());
|
||||
|
||||
public override void Write(byte[] buffer, int offset, int count) => Write(buffer.AsSpan(offset, count));
|
||||
|
||||
public override void Write(ReadOnlySpan<byte> buffer)
|
||||
{
|
||||
hash.AppendData(buffer);
|
||||
length += buffer.Length;
|
||||
}
|
||||
|
||||
public override ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken = default)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
Write(buffer.Span);
|
||||
return ValueTask.CompletedTask;
|
||||
}
|
||||
|
||||
public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) =>
|
||||
WriteAsync(buffer.AsMemory(offset, count), cancellationToken).AsTask();
|
||||
|
||||
public override void Flush()
|
||||
{
|
||||
}
|
||||
|
||||
public override int Read(byte[] buffer, int offset, int count) => throw new NotSupportedException();
|
||||
|
||||
public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException();
|
||||
|
||||
public override void SetLength(long value) => throw new NotSupportedException();
|
||||
|
||||
protected override void Dispose(bool disposing)
|
||||
{
|
||||
if (disposing)
|
||||
{
|
||||
hash.Dispose();
|
||||
}
|
||||
|
||||
base.Dispose(disposing);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Core.Library.Conversion;
|
||||
|
||||
namespace Febe.Core.Export;
|
||||
|
||||
/// <summary>What the plan expects of a file in a format, from its name only (tappa E3: the copy decides on the bytes).</summary>
|
||||
public enum ExportPrediction
|
||||
{
|
||||
/// <summary>Copied byte for byte: Original, or already in the format asked.</summary>
|
||||
Whole,
|
||||
|
||||
/// <summary>Converted into the format asked.</summary>
|
||||
Converted,
|
||||
|
||||
/// <summary>Copied as it is with a note (HEIC, AVIF, raw, GIF, WebM).</summary>
|
||||
AsIs,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The format of a copy (spec §4.10 «Conversione del formato», decisions D1, D2 and D5-D7 of tappa E3): which format a
|
||||
/// file gets in a destination, and what the plan predicts of it from its name.
|
||||
/// </summary>
|
||||
public static class ExportConversions
|
||||
{
|
||||
/// <summary>
|
||||
/// The format of a file of <paramref name="kind"/>: the «Copia in…» override of this request, else the destination's,
|
||||
/// else the general settings' (D1). A value that does not belong to the kind counts as not set.
|
||||
/// </summary>
|
||||
public static ExportFormat Resolve(MediaKind kind, ExportFormatChoice? request, ExportDestination destination, ExportSettings settings)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(destination);
|
||||
ArgumentNullException.ThrowIfNull(settings);
|
||||
Func<ExportFormat, bool> fits = kind == MediaKind.Photo ? ExportFormats.IsPhotoFormat : ExportFormats.IsVideoFormat;
|
||||
var chosen = kind == MediaKind.Photo
|
||||
? new[] { request?.Photo, destination.PhotoFormat, settings.PhotoFormat }
|
||||
: [request?.Video, destination.VideoFormat, settings.VideoFormat];
|
||||
foreach (var format in chosen)
|
||||
{
|
||||
if (format is { } f && fits(f))
|
||||
{
|
||||
return f;
|
||||
}
|
||||
}
|
||||
|
||||
return ExportFormat.Original;
|
||||
}
|
||||
|
||||
/// <summary>The variant a format asks for: Whole for Original, Converted otherwise.</summary>
|
||||
public static ExportVariant VariantOf(ExportFormat format) => format == ExportFormat.Original ? ExportVariant.Whole : ExportVariant.Converted;
|
||||
|
||||
/// <summary>
|
||||
/// What the plan expects, by extension («circa»): Original, or the same format (<c>.jpg/.jpeg</c>, <c>.png</c>,
|
||||
/// <c>.webp</c>, <c>.mp4</c>) → Whole; HEIC, HEIF, AVIF, raw, GIF and WebM → AsIs; anything else → Converted.
|
||||
/// </summary>
|
||||
public static ExportPrediction Predict(string relativePath, MediaKind kind, ExportFormat target)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(relativePath);
|
||||
if (target == ExportFormat.Original)
|
||||
{
|
||||
return ExportPrediction.Whole;
|
||||
}
|
||||
|
||||
var extension = Path.GetExtension(relativePath).ToLowerInvariant();
|
||||
var same = target switch
|
||||
{
|
||||
ExportFormat.Jpg => extension is ".jpg" or ".jpeg",
|
||||
ExportFormat.Png => extension == ".png",
|
||||
ExportFormat.WebpLossless => extension == ".webp",
|
||||
ExportFormat.Mp4 => extension == ".mp4",
|
||||
_ => false,
|
||||
};
|
||||
if (same)
|
||||
{
|
||||
return ExportPrediction.Whole;
|
||||
}
|
||||
|
||||
return AsIsLabel(relativePath) is not null ? ExportPrediction.AsIs : ExportPrediction.Converted;
|
||||
}
|
||||
|
||||
/// <summary>The kind of a file copied as it is, for «3 HEIC copiati come sono»: «HEIC», «AVIF», «raw», «GIF», «WebM»; null otherwise.</summary>
|
||||
public static string? AsIsLabel(string relativePath)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(relativePath);
|
||||
var extension = Path.GetExtension(relativePath).ToLowerInvariant();
|
||||
return extension switch
|
||||
{
|
||||
".heic" or ".heif" => "HEIC",
|
||||
".avif" => "AVIF",
|
||||
".gif" => "GIF",
|
||||
".webm" => "WebM",
|
||||
_ when MediaConverter.IsRawExtension(extension) => "raw",
|
||||
_ => null,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>The effective identity the plan expects (D2): (Converted, format) when predicted converted, else (Whole, Original).</summary>
|
||||
public static (ExportVariant Variant, ExportFormat Format) PredictedIdentity(string relativePath, MediaKind kind, ExportFormat target) =>
|
||||
Predict(relativePath, kind, target) == ExportPrediction.Converted ? (ExportVariant.Converted, target) : (ExportVariant.Whole, ExportFormat.Original);
|
||||
}
|
||||
@@ -15,6 +15,8 @@ namespace Febe.Core.Export;
|
||||
/// <param name="ProfileNamingScheme">Scheme of profile pictures; null: «Come la libreria».</param>
|
||||
/// <param name="Automatic">«Automatica»: stored only in tappa E2 (tappa E5 acts on it).</param>
|
||||
/// <param name="OnlyNew">«Solo i nuovi» when «Automatica» is turned on.</param>
|
||||
/// <param name="PhotoFormat">Format of the copies of photos here; null: «Come le impostazioni generali» (tappa E3, D1).</param>
|
||||
/// <param name="VideoFormat">Format of the copies of videos here (Original or Mp4); null: «Come le impostazioni generali».</param>
|
||||
public sealed record DestinationSpec(
|
||||
ExportScope Scope,
|
||||
long? AccountId,
|
||||
@@ -25,7 +27,9 @@ public sealed record DestinationSpec(
|
||||
string? HighlightNamingScheme,
|
||||
string? ProfileNamingScheme,
|
||||
bool Automatic = false,
|
||||
bool OnlyNew = true);
|
||||
bool OnlyNew = true,
|
||||
ExportFormat? PhotoFormat = null,
|
||||
ExportFormat? VideoFormat = null);
|
||||
|
||||
/// <summary>A saved destination and the warnings of its naming schemes (shown, they do not block).</summary>
|
||||
public sealed record DestinationSaveResult(ExportDestination Destination, IReadOnlyList<string> Warnings);
|
||||
@@ -347,6 +351,17 @@ public sealed class ExportDestinations(ExportEnvironment env)
|
||||
throw new ArgumentException("Scegli almeno un tipo di contenuto.", nameof(spec));
|
||||
}
|
||||
|
||||
// A change of format is not a new folder: the copies already made stay «già copiato» (D3 of tappa E3).
|
||||
if (spec.PhotoFormat is { } photo && !ExportFormats.IsPhotoFormat(photo))
|
||||
{
|
||||
throw new ArgumentException("Per le foto si sceglie Originale, JPG, PNG o WEBP senza perdita.", nameof(spec));
|
||||
}
|
||||
|
||||
if (spec.VideoFormat is { } video && !ExportFormats.IsVideoFormat(video))
|
||||
{
|
||||
throw new ArgumentException("Per i video si sceglie Originale o MP4.", nameof(spec));
|
||||
}
|
||||
|
||||
var errors = new List<string>();
|
||||
var warnings = new List<string>();
|
||||
void Check(string? text, NamingSchemeUse use)
|
||||
@@ -392,6 +407,8 @@ public sealed class ExportDestinations(ExportEnvironment env)
|
||||
NamingScheme = Clean(spec.NamingScheme),
|
||||
HighlightNamingScheme = Clean(spec.HighlightNamingScheme),
|
||||
ProfileNamingScheme = Clean(spec.ProfileNamingScheme),
|
||||
PhotoFormat = spec.PhotoFormat,
|
||||
VideoFormat = spec.VideoFormat,
|
||||
Automatic = spec.Automatic,
|
||||
CreatedAt = createdAt,
|
||||
};
|
||||
|
||||
@@ -2,6 +2,7 @@ using System.Security.Cryptography;
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Core.Library;
|
||||
using Febe.Core.Library.Conversion;
|
||||
using Febe.Core.Storage;
|
||||
|
||||
namespace Febe.Core.Export;
|
||||
@@ -61,6 +62,9 @@ public sealed record ExportEnvironment
|
||||
/// <summary>…or this many planned bytes, whichever comes first.</summary>
|
||||
public long GroupBytes { get; init; } = 1L << 30;
|
||||
|
||||
/// <summary>One conversion at a time in the process (tappa E3, D16): shared with the library conversion.</summary>
|
||||
public ConversionThrottle Throttle { get; init; } = ConversionThrottle.Shared;
|
||||
|
||||
/// <summary>The checker of destination folders of this environment.</summary>
|
||||
public ExportFolderCheck CreateFolderCheck() => new(Root.Mounts, FolderCheckTimeout, WriteProbe);
|
||||
|
||||
@@ -101,6 +105,12 @@ public interface IExportFileSystem
|
||||
/// <summary>Opens a file for reading only.</summary>
|
||||
Stream OpenRead(string path);
|
||||
|
||||
/// <summary>
|
||||
/// Opens a file for reading at any position (a video to remux or to take frames from, tappa E3). By default the
|
||||
/// stream of <see cref="OpenRead"/>, which can seek.
|
||||
/// </summary>
|
||||
Stream OpenRandomAccess(string path) => OpenRead(path);
|
||||
|
||||
/// <summary>SHA-256 (lowercase hex) of a file as it is on disk now.</summary>
|
||||
Task<string> ComputeSha256Async(string path, CancellationToken ct);
|
||||
|
||||
@@ -121,8 +131,13 @@ public sealed class ExportFileSystem : IExportFileSystem
|
||||
|
||||
public static ExportFileSystem Instance { get; } = new();
|
||||
|
||||
// FileShare.Delete: a long read never blocks «Elimina dalla libreria» on Windows (tappa E3).
|
||||
public Stream OpenRead(string path) =>
|
||||
new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, BufferSize, FileOptions.Asynchronous | FileOptions.SequentialScan);
|
||||
new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete, BufferSize, FileOptions.Asynchronous | FileOptions.SequentialScan);
|
||||
|
||||
/// <summary>As <c>ContainerReader.OpenRead</c>: shared for reading, writing and deleting, read at random positions.</summary>
|
||||
public Stream OpenRandomAccess(string path) =>
|
||||
new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete, BufferSize, FileOptions.RandomAccess);
|
||||
|
||||
public async Task<string> ComputeSha256Async(string path, CancellationToken ct)
|
||||
{
|
||||
|
||||
@@ -0,0 +1,170 @@
|
||||
using System.Globalization;
|
||||
|
||||
namespace Febe.Core.Export;
|
||||
|
||||
/// <summary>
|
||||
/// The instants, names and labels of frames (spec §4.10 «Fotogrammi», decisions D12 and D13 of tappa E3): which instants
|
||||
/// a request asks for, the suffix a frame file gets, and how an instant is shown.
|
||||
/// </summary>
|
||||
public static class ExportFrames
|
||||
{
|
||||
/// <summary>The shortest step of «Uno ogni k secondi».</summary>
|
||||
public static readonly TimeSpan MinEvery = TimeSpan.FromMilliseconds(100);
|
||||
|
||||
/// <summary>The most frames of «N in tutto».</summary>
|
||||
public const int MaxCount = 1000;
|
||||
|
||||
/// <summary>The most frames taken from one video.</summary>
|
||||
public const int MaxPerVideo = 1000;
|
||||
|
||||
/// <summary>The most frames of one request.</summary>
|
||||
public const int MaxPerRequest = 20000;
|
||||
|
||||
/// <summary>Why a request over <see cref="MaxPerVideo"/> is refused.</summary>
|
||||
public const string OverCapMessage = "Più di 1.000 fotogrammi per un video: scegli un intervallo più lungo";
|
||||
|
||||
/// <summary>The suffix of the single frame of «Salva il fotogramma» (tappa E4).</summary>
|
||||
public const string SingleSuffix = "_fotogramma";
|
||||
|
||||
/// <summary>How many frames <paramref name="request"/> asks of a video of <paramref name="duration"/>.</summary>
|
||||
public static long FrameCount(TimeSpan duration, ExportFramesRequest request)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(request);
|
||||
return request.Mode switch
|
||||
{
|
||||
FrameMode.At => 1,
|
||||
FrameMode.Every => EveryCount(duration, request.Every ?? throw new ArgumentException("Manca l'intervallo dei fotogrammi.", nameof(request))),
|
||||
FrameMode.Count => request.Count ?? throw new ArgumentException("Manca il numero dei fotogrammi.", nameof(request)),
|
||||
_ => throw new ArgumentOutOfRangeException(nameof(request)),
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The instants <paramref name="request"/> asks of a video of <paramref name="duration"/>, in increasing order.
|
||||
/// Refused (<see cref="ArgumentException"/> with <see cref="OverCapMessage"/>) over <see cref="MaxPerVideo"/>.
|
||||
/// </summary>
|
||||
public static IReadOnlyList<TimeSpan> Instants(TimeSpan duration, ExportFramesRequest request)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(request);
|
||||
return request.Mode switch
|
||||
{
|
||||
FrameMode.At => [request.At is { } at && at > TimeSpan.Zero ? at : TimeSpan.Zero],
|
||||
FrameMode.Every => Every(duration, request.Every ?? throw new ArgumentException("Manca l'intervallo dei fotogrammi.", nameof(request))),
|
||||
FrameMode.Count => Spread(duration, request.Count ?? throw new ArgumentException("Manca il numero dei fotogrammi.", nameof(request))),
|
||||
_ => throw new ArgumentOutOfRangeException(nameof(request)),
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>«Uno ogni k secondi»: 0, k, 2k… before <paramref name="duration"/> (only 0 for a video without length).</summary>
|
||||
public static IReadOnlyList<TimeSpan> Every(TimeSpan duration, TimeSpan step)
|
||||
{
|
||||
if (step < MinEvery)
|
||||
{
|
||||
throw new ArgumentOutOfRangeException(nameof(step), "L'intervallo minimo è 0,1 secondi.");
|
||||
}
|
||||
|
||||
var count = EveryCount(duration, step);
|
||||
if (count > MaxPerVideo)
|
||||
{
|
||||
throw new ArgumentException(OverCapMessage, nameof(step));
|
||||
}
|
||||
|
||||
var instants = new TimeSpan[count];
|
||||
for (var i = 0; i < count; i++)
|
||||
{
|
||||
instants[i] = WholeMs(TimeSpan.FromTicks(step.Ticks * i));
|
||||
}
|
||||
|
||||
return instants;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// «N in tutto»: (i + ½) · duration / N for i = 0…N − 1, rounded up to the millisecond: the item, the preview and
|
||||
/// the download locate the same instant. On a video shorter than N milliseconds neighbours can share one.
|
||||
/// </summary>
|
||||
public static IReadOnlyList<TimeSpan> Spread(TimeSpan duration, int count)
|
||||
{
|
||||
if (count is < 1 or > MaxCount)
|
||||
{
|
||||
throw new ArgumentOutOfRangeException(nameof(count), "Da 1 a 1.000 fotogrammi.");
|
||||
}
|
||||
|
||||
var length = (Int128)Math.Max(0, duration.Ticks);
|
||||
var instants = new TimeSpan[count];
|
||||
for (var i = 0; i < count; i++)
|
||||
{
|
||||
instants[i] = WholeMs(TimeSpan.FromTicks((long)(((2 * i) + 1) * length / (2 * (Int128)count))));
|
||||
}
|
||||
|
||||
return instants;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The suffix of a frame file, appended to the stem: <c>_t0m12s340</c> (the actual instant: minutes, seconds on two
|
||||
/// digits, milliseconds on three) for «Questo istante» and «Uno ogni k secondi»; <c>_f001</c> (the position among
|
||||
/// the <paramref name="count"/> instants, at least three digits) for «N in tutto».
|
||||
/// </summary>
|
||||
/// <param name="index">0-based position of the instant in the request.</param>
|
||||
public static string Suffix(FrameMode mode, TimeSpan actual, int index, int count)
|
||||
{
|
||||
if (mode == FrameMode.Count)
|
||||
{
|
||||
var digits = Math.Max(3, Math.Max(1, count).ToString(CultureInfo.InvariantCulture).Length);
|
||||
return "_f" + (index + 1).ToString("D" + digits.ToString(CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
|
||||
}
|
||||
|
||||
var ms = ActualMs(actual);
|
||||
return string.Create(CultureInfo.InvariantCulture, $"_t{ms / 60000}m{ms / 1000 % 60:D2}s{ms % 1000:D3}");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// An instant as the viewer and the dialog show it: <c>m:ss</c> («0:01»), followed by a comma and the milliseconds
|
||||
/// without trailing zeros only when it is not a whole second («0:01,25»).
|
||||
/// </summary>
|
||||
public static string Label(TimeSpan actual)
|
||||
{
|
||||
var ms = ActualMs(actual);
|
||||
var label = string.Create(CultureInfo.InvariantCulture, $"{ms / 60000}:{ms / 1000 % 60:D2}");
|
||||
var fraction = ms % 1000;
|
||||
return fraction == 0
|
||||
? label
|
||||
: label + "," + fraction.ToString("D3", CultureInfo.InvariantCulture).TrimEnd('0');
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The position of <paramref name="requested"/> among <paramref name="instants"/> (the first of those on the same
|
||||
/// millisecond, as the items keep them), or null when it is not one of them.
|
||||
/// </summary>
|
||||
public static int? IndexOf(IReadOnlyList<TimeSpan> instants, TimeSpan requested)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(instants);
|
||||
var ms = (long)requested.TotalMilliseconds;
|
||||
for (var i = 0; i < instants.Count; i++)
|
||||
{
|
||||
if ((long)instants[i].TotalMilliseconds == ms)
|
||||
{
|
||||
return i;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>An instant rounded up to the whole millisecond (never before the instant computed).</summary>
|
||||
private static TimeSpan WholeMs(TimeSpan at) => TimeSpan.FromMilliseconds(ActualMs(at));
|
||||
|
||||
/// <summary>The identity of a frame's instant: its shown time in milliseconds, rounded up.</summary>
|
||||
public static long ActualMs(TimeSpan shown) =>
|
||||
shown <= TimeSpan.Zero ? 0 : (shown.Ticks + TimeSpan.TicksPerMillisecond - 1) / TimeSpan.TicksPerMillisecond;
|
||||
|
||||
private static long EveryCount(TimeSpan duration, TimeSpan step)
|
||||
{
|
||||
if (step <= TimeSpan.Zero)
|
||||
{
|
||||
throw new ArgumentOutOfRangeException(nameof(step));
|
||||
}
|
||||
|
||||
// 0, k, 2k… strictly before the end: ceil(duration / k), and at least the frame at 0.
|
||||
return duration <= TimeSpan.Zero ? 1 : Math.Max(1, (duration.Ticks + step.Ticks - 1) / step.Ticks);
|
||||
}
|
||||
}
|
||||
@@ -23,8 +23,43 @@ public abstract record ExportSelection
|
||||
public sealed record Account(long AccountId) : ExportSelection;
|
||||
}
|
||||
|
||||
/// <summary>How the instants of «Fotogrammi» are chosen (spec §4.10 «Fotogrammi»).</summary>
|
||||
public enum FrameMode
|
||||
{
|
||||
/// <summary>«Questo istante»: one frame at <see cref="ExportFramesRequest.At"/>.</summary>
|
||||
At,
|
||||
|
||||
/// <summary>«Uno ogni k secondi»: at 0, k, 2k… before the end.</summary>
|
||||
Every,
|
||||
|
||||
/// <summary>«N in tutto»: N frames spread over the video, each in the middle of its share.</summary>
|
||||
Count,
|
||||
}
|
||||
|
||||
/// <summary>A request of frames of videos, in a photo format (Jpg, Png or WebpLossless).</summary>
|
||||
public sealed record ExportFramesRequest(FrameMode Mode, TimeSpan? At, TimeSpan? Every, int? Count, ExportFormat Format);
|
||||
|
||||
/// <summary>
|
||||
/// The formats of «Copia in…» for this request only (tappa E3, D1): null keeps the destination's (or the general
|
||||
/// settings'). A photo format or Original for photos; Mp4 or Original for videos.
|
||||
/// </summary>
|
||||
public sealed record ExportFormatChoice(ExportFormat? Photo, ExportFormat? Video);
|
||||
|
||||
/// <summary>«Copia di nuovo» of one copy row (tappa E3, D11): the form of that row, looked up only by its exact identity.</summary>
|
||||
/// <param name="FrameAt">The instant of a frame row; null otherwise.</param>
|
||||
public sealed record ExportCopyRequest(ExportVariant Variant, ExportFormat Format, TimeSpan? FrameAt);
|
||||
|
||||
/// <summary>A «Copia in…»: what to copy, whether «Tolti» and «Superati» are copied again (D9), who asked.</summary>
|
||||
public sealed record ExportJobRequest(ExportSelection Selection, bool CopyAgain = false, ExportRunOrigin Origin = ExportRunOrigin.Manual);
|
||||
/// <param name="Formats">The formats of this request («Copia in…» → «Cambia»); null: those of the destination.</param>
|
||||
/// <param name="Frames">Not null: a frames job («Fotogrammi…» → «Nella cartella delle copie»), videos only.</param>
|
||||
/// <param name="Exact">«Copia di nuovo» of one copy row, only with a selection of one file.</param>
|
||||
public sealed record ExportJobRequest(
|
||||
ExportSelection Selection,
|
||||
bool CopyAgain = false,
|
||||
ExportRunOrigin Origin = ExportRunOrigin.Manual,
|
||||
ExportFormatChoice? Formats = null,
|
||||
ExportFramesRequest? Frames = null,
|
||||
ExportCopyRequest? Exact = null);
|
||||
|
||||
/// <summary>
|
||||
/// What a «Copia in…» would do (database only, decisions D3 and D9 of tappa E2). Each file goes to the effective
|
||||
@@ -55,8 +90,35 @@ public sealed record ExportPlan(
|
||||
bool HasDestination = true)
|
||||
{
|
||||
public static ExportPlan Empty { get; } = new(0, 0, 0, 0, 0, 0, []);
|
||||
|
||||
/// <summary>
|
||||
/// Files predicted to be copied as they are, by kind («3 HEIC copiati come sono»): a prediction from the names
|
||||
/// («circa»), the copy decides on the bytes (tappa E3).
|
||||
/// </summary>
|
||||
public IReadOnlyList<ExportPlanAsIs> AsIs { get; init; } = [];
|
||||
|
||||
/// <summary>Files predicted to be converted.</summary>
|
||||
public int Converted { get; init; }
|
||||
|
||||
/// <summary>«Con perdita»: at least one file predicted converted to JPG, or JPG frames (D7 of tappa E3).</summary>
|
||||
public bool Lossy { get; init; }
|
||||
|
||||
/// <summary>Frames job: the due videos.</summary>
|
||||
public int Videos { get; init; }
|
||||
|
||||
/// <summary>Frames job: the photos of the selection, skipped («Le 4 foto si saltano»).</summary>
|
||||
public int PhotosSkipped { get; init; }
|
||||
|
||||
/// <summary>Frames job: the frames to write (also in <see cref="Files"/>); «circa» for a video of unknown length.</summary>
|
||||
public int Frames { get; init; }
|
||||
|
||||
/// <summary>Frames job: videos that would give more than <see cref="ExportFrames.MaxPerVideo"/> frames (the job is refused).</summary>
|
||||
public int OverCap { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>Files of a plan copied as they are, of one kind («HEIC», «AVIF», «raw», «GIF», «WebM»).</summary>
|
||||
public sealed record ExportPlanAsIs(string Label, int Files);
|
||||
|
||||
/// <summary>A destination of a plan.</summary>
|
||||
/// <param name="Username">The account of an own folder; null for the general folder.</param>
|
||||
/// <param name="Files">Files to write there.</param>
|
||||
|
||||
@@ -4,6 +4,12 @@ using Febe.Core.Library;
|
||||
|
||||
namespace Febe.Core.Export;
|
||||
|
||||
/// <summary>
|
||||
/// How the file name of a copy differs from the library's (tappa E3): the extension of the effective format
|
||||
/// («.jpg»; null keeps the source's) and the suffix of a frame («_t0m12s340»; null for none), appended to the stem.
|
||||
/// </summary>
|
||||
public sealed record ExportNameOptions(string? Extension, string? Suffix);
|
||||
|
||||
/// <summary>Paths and content types of the export (spec §4.10).</summary>
|
||||
public static class ExportPaths
|
||||
{
|
||||
@@ -63,7 +69,8 @@ public static class ExportPaths
|
||||
Media media,
|
||||
string? highlightTitle,
|
||||
bool inHighlight,
|
||||
TimeZoneInfo zone)
|
||||
TimeZoneInfo zone,
|
||||
ExportNameOptions? name = null)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(d);
|
||||
ArgumentNullException.ThrowIfNull(library);
|
||||
@@ -106,22 +113,42 @@ public static class ExportPaths
|
||||
segments = scheme.Render(values, zone);
|
||||
}
|
||||
|
||||
segments = Renamed(segments, name);
|
||||
return d.Scope == ExportScope.General ? [WindowsFileNames.SanitizeSegment(account.Username), .. segments] : segments;
|
||||
}
|
||||
|
||||
/// <summary>The last segment with the suffix appended to its stem and the extension of <paramref name="name"/>.</summary>
|
||||
private static IReadOnlyList<string> Renamed(IReadOnlyList<string> segments, ExportNameOptions? name)
|
||||
{
|
||||
if (name is null || segments.Count == 0 || (name.Extension is null && string.IsNullOrEmpty(name.Suffix)))
|
||||
{
|
||||
return segments;
|
||||
}
|
||||
|
||||
var (stem, extension) = WindowsFileNames.SplitExtension(segments[^1]);
|
||||
var fileName = WindowsFileNames.SanitizeSegment(stem + (name.Suffix ?? string.Empty) + (name.Extension ?? extension));
|
||||
return [.. segments.Take(segments.Count - 1), fileName];
|
||||
}
|
||||
|
||||
/// <summary>The relative path ('/' separated) of a copy: the segments fitted to the length limit under the root.</summary>
|
||||
/// <param name="d">The destination.</param>
|
||||
/// <param name="segments">The segments of <see cref="Segments"/>.</param>
|
||||
/// <param name="maxPath">The longest full path.</param>
|
||||
/// <param name="keepSuffix">The frame suffix of the file name, never cut by the shortening.</param>
|
||||
/// <exception cref="PathTooLongException">Even shortened, the path does not fit.</exception>
|
||||
public static string RelativePathFor(ExportDestination d, IReadOnlyList<string> segments, int maxPath = WindowsFileNames.MaxPathLength)
|
||||
public static string RelativePathFor(ExportDestination d, IReadOnlyList<string> segments, int maxPath = WindowsFileNames.MaxPathLength, string? keepSuffix = null)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(d);
|
||||
return string.Join('/', WindowsFileNames.FitPath(d.RootPath, segments, maxPath));
|
||||
return string.Join('/', WindowsFileNames.FitPath(d.RootPath, segments, maxPath, keepSuffix));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The name the safe writer gives a file at its <paramref name="attempt"/>-th try when the planned name is taken
|
||||
/// («nome (2).jpg», «nome (3).jpg», …), so a resumed copy finds a file it renamed before a crash.
|
||||
/// («nome (2).jpg», «nome (3).jpg», …), so a resumed copy finds a file it renamed before a crash. With
|
||||
/// <paramref name="keepSuffix"/> (a frame suffix, <see cref="SafeWriteOptions.KeepSuffix"/>) the number comes after
|
||||
/// it and both survive the shortening: «x_f001 (2).png».
|
||||
/// </summary>
|
||||
public static string NumberedName(string root, string relativePath, int attempt, int maxPath = WindowsFileNames.MaxPathLength)
|
||||
public static string NumberedName(string root, string relativePath, int attempt, int maxPath = WindowsFileNames.MaxPathLength, string? keepSuffix = null)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(relativePath);
|
||||
var segments = LibraryLayout.ToStored(relativePath).Split('/', StringSplitOptions.RemoveEmptyEntries);
|
||||
@@ -132,7 +159,8 @@ public static class ExportPaths
|
||||
|
||||
var (stem, extension) = WindowsFileNames.SplitExtension(segments[^1]);
|
||||
var name = WindowsFileNames.SanitizeSegment(string.Create(CultureInfo.InvariantCulture, $"{stem} ({attempt}){extension}"));
|
||||
return string.Join('/', WindowsFileNames.FitPath(root, [.. segments[..^1], name], maxPath));
|
||||
var keep = keepSuffix is null ? null : string.Create(CultureInfo.InvariantCulture, $"{keepSuffix} ({attempt})");
|
||||
return string.Join('/', WindowsFileNames.FitPath(root, [.. segments[..^1], name], maxPath, keep));
|
||||
}
|
||||
|
||||
/// <summary>The scheme that names an entry kind.</summary>
|
||||
|
||||
@@ -6,8 +6,10 @@ namespace Febe.Core.Export;
|
||||
|
||||
/// <summary>
|
||||
/// What a «Copia in…» would do, from the database only (decisions D3, D5 and D9 of tappa E2): each file goes to the
|
||||
/// effective destination of its account; a file already copied there is «già copiato»; «Tolti» and «Superati» are
|
||||
/// skipped unless «Copia di nuovo» was asked. The only look at a destination is whether it answers, for the dialog.
|
||||
/// effective destination of its account; a file already copied there, in any form but a frame, is «già copiato»
|
||||
/// (decision D3 of tappa E3); «Tolti» and «Superati» are skipped unless «Copia di nuovo» was asked. The format of each
|
||||
/// file is resolved and predicted from its name (D1, «circa»); a frames job plans one frame per instant of each due
|
||||
/// video. The only look at a destination is whether it answers, for the dialog.
|
||||
/// </summary>
|
||||
public sealed class ExportPlanner(ExportEnvironment env)
|
||||
{
|
||||
@@ -16,9 +18,11 @@ public sealed class ExportPlanner(ExportEnvironment env)
|
||||
private readonly ExportEnvironment _env = env ?? throw new ArgumentNullException(nameof(env));
|
||||
|
||||
/// <summary>The plan of a request, for the «Copia in…» dialog.</summary>
|
||||
/// <exception cref="ArgumentException">The request is not valid (Italian message).</exception>
|
||||
public async Task<ExportPlan> PlanAsync(ExportJobRequest request, CancellationToken ct)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(request);
|
||||
Validate(request);
|
||||
var destinations = new ExportDestinations(_env);
|
||||
var effective = await destinations.ResolveAllAsync(ct).ConfigureAwait(false);
|
||||
var settings = await ExportSettings.LoadAsync(_env.Storage.Settings, ct).ConfigureAwait(false);
|
||||
@@ -31,17 +35,108 @@ public sealed class ExportPlanner(ExportEnvironment env)
|
||||
return await tally.BuildAsync(_env, destinations, effective, checkDestinations: true, ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>The checks of a request (tappa E3, WP1.1), with Italian messages.</summary>
|
||||
/// <exception cref="ArgumentException">What is wrong.</exception>
|
||||
public static void Validate(ExportJobRequest request)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(request);
|
||||
ArgumentNullException.ThrowIfNull(request.Selection, nameof(request));
|
||||
if (request.Frames is not null && request.Formats is not null)
|
||||
{
|
||||
throw new ArgumentException("I fotogrammi non si chiedono insieme ai formati delle copie.", nameof(request));
|
||||
}
|
||||
|
||||
if (request.Exact is { } exact)
|
||||
{
|
||||
if (request.Selection is not ExportSelection.Media { MediaIds.Count: 1 })
|
||||
{
|
||||
throw new ArgumentException("«Copia di nuovo» di una copia vale per un file solo.", nameof(request));
|
||||
}
|
||||
|
||||
if (request.Frames is not null || request.Formats is not null)
|
||||
{
|
||||
throw new ArgumentException("«Copia di nuovo» di una copia rifà la sua forma: niente altri formati né fotogrammi.", nameof(request));
|
||||
}
|
||||
|
||||
var valid = exact.Variant switch
|
||||
{
|
||||
ExportVariant.Whole => exact.Format == ExportFormat.Original && exact.FrameAt is null,
|
||||
ExportVariant.Converted => exact.Format != ExportFormat.Original && exact.FrameAt is null,
|
||||
ExportVariant.Frame => IsFrameFormat(exact.Format) && exact.FrameAt is { } at && at >= TimeSpan.Zero,
|
||||
_ => false,
|
||||
};
|
||||
if (!valid)
|
||||
{
|
||||
throw new ArgumentException("La forma della copia da rifare non è valida.", nameof(request));
|
||||
}
|
||||
}
|
||||
|
||||
if (request.Formats is { } formats)
|
||||
{
|
||||
if (formats.Photo is { } photo && !ExportFormats.IsPhotoFormat(photo))
|
||||
{
|
||||
throw new ArgumentException("Per le foto si sceglie Originale, JPG, PNG o WEBP senza perdita.", nameof(request));
|
||||
}
|
||||
|
||||
if (formats.Video is { } video && !ExportFormats.IsVideoFormat(video))
|
||||
{
|
||||
throw new ArgumentException("Per i video si sceglie Originale o MP4.", nameof(request));
|
||||
}
|
||||
}
|
||||
|
||||
if (request.Frames is { } frames)
|
||||
{
|
||||
if (!IsFrameFormat(frames.Format))
|
||||
{
|
||||
throw new ArgumentException("I fotogrammi si salvano in JPG, PNG o WEBP senza perdita.", nameof(request));
|
||||
}
|
||||
|
||||
switch (frames.Mode)
|
||||
{
|
||||
case FrameMode.At when frames.At is not { } at || at < TimeSpan.Zero:
|
||||
throw new ArgumentException("Scegli l'istante del fotogramma.", nameof(request));
|
||||
case FrameMode.Every when frames.Every is not { } every || every < ExportFrames.MinEvery:
|
||||
throw new ArgumentException("L'intervallo minimo è 0,1 secondi.", nameof(request));
|
||||
case FrameMode.Count when frames.Count is not ({ } count and >= 1 and <= ExportFrames.MaxCount):
|
||||
throw new ArgumentException("Da 1 a 1.000 fotogrammi.", nameof(request));
|
||||
case FrameMode.At or FrameMode.Every or FrameMode.Count:
|
||||
break;
|
||||
default:
|
||||
throw new ArgumentException("Modo dei fotogrammi sconosciuto.", nameof(request));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>JPG, PNG or WEBP senza perdita: the formats of a frame.</summary>
|
||||
internal static bool IsFrameFormat(ExportFormat format) => format is ExportFormat.Jpg or ExportFormat.Png or ExportFormat.WebpLossless;
|
||||
|
||||
/// <summary>
|
||||
/// Every candidate of the request with what to do with it, in media id order. Within one plan the same file of an
|
||||
/// account in one destination counts once (a story and its highlight entry, two files with the same bytes); with
|
||||
/// «Una copia sola» the same file counts once across accounts.
|
||||
/// Every candidate of the request with what to do with it, in media id order (a frames job: one planned file per
|
||||
/// instant of each video, in instant order). Within one plan the same file of an account in one destination counts
|
||||
/// once (a story and its highlight entry, two files with the same bytes); with «Una copia sola» the same file counts
|
||||
/// once across accounts.
|
||||
/// </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(
|
||||
ExportJobRequest request,
|
||||
IReadOnlyDictionary<long, EffectiveDestination> effective,
|
||||
ExportSettings settings,
|
||||
[EnumeratorCancellation] CancellationToken ct)
|
||||
[EnumeratorCancellation] CancellationToken ct,
|
||||
Func<ExportCandidate, CancellationToken, Task<TimeSpan?>>? lengthOf = null)
|
||||
{
|
||||
if (request.Frames is { } frames)
|
||||
{
|
||||
await foreach (var frame in EnumerateFramesAsync(request, frames, effective, lengthOf, ct).ConfigureAwait(false))
|
||||
{
|
||||
yield return frame;
|
||||
}
|
||||
|
||||
yield break;
|
||||
}
|
||||
|
||||
var exports = _env.Storage.Exports;
|
||||
var oneOnly = settings.SamePost == SamePostCopies.OneOnly;
|
||||
var seen = new HashSet<(long Destination, long Account, string Sha256)>();
|
||||
@@ -70,9 +165,12 @@ public sealed class ExportPlanner(ExportEnvironment env)
|
||||
}
|
||||
|
||||
var states = new Dictionary<long, IReadOnlyDictionary<(long AccountId, string Sha256), ExportCopyState>>();
|
||||
foreach (var (destination, set) in keys)
|
||||
if (request.Exact is null)
|
||||
{
|
||||
states[destination] = await exports.GetCopyStatesAsync(destination, set, ct).ConfigureAwait(false);
|
||||
foreach (var (destination, set) in keys)
|
||||
{
|
||||
states[destination] = await exports.GetCopyStatesAsync(destination, set, ct).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var c in page)
|
||||
@@ -91,25 +189,45 @@ public sealed class ExportPlanner(ExportEnvironment env)
|
||||
|
||||
var sha = c.Sha256!;
|
||||
var key = oneOnly ? (0L, 0L, sha) : (destination, c.AccountId, sha);
|
||||
var state = states[destination].TryGetValue((c.AccountId, sha), out var s) ? s : (ExportCopyState?)null;
|
||||
var form = Form(c, request, effective[c.AccountId].Destination!, settings);
|
||||
ExportCopyState? state;
|
||||
if (request.Exact is { } exact)
|
||||
{
|
||||
// «Copia di nuovo» of one row: only its exact identity counts (D11 of tappa E3).
|
||||
var identity = new ExportCopyIdentity(destination, c.AccountId, sha, exact.Variant, exact.Format, exact.FrameAt);
|
||||
if (await exports.FindCurrentCopyAsync(identity, ct).ConfigureAwait(false) is { } current)
|
||||
{
|
||||
state = current.State;
|
||||
}
|
||||
else
|
||||
{
|
||||
var latest = await exports.FindLatestCopyAsync(identity, ct).ConfigureAwait(false);
|
||||
state = latest is { State: ExportCopyState.Removed or ExportCopyState.Superseded } ? latest.State : null;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
state = states[destination].TryGetValue((c.AccountId, sha), out var s) ? s : null;
|
||||
}
|
||||
|
||||
PlannedFile planned;
|
||||
if (state == ExportCopyState.Copied)
|
||||
{
|
||||
planned = new PlannedFile(c, destination, PlannedCopy.AlreadyCopied);
|
||||
planned = form with { DestinationId = destination, Action = PlannedCopy.AlreadyCopied };
|
||||
}
|
||||
else if (state is ExportCopyState.Removed or ExportCopyState.Superseded)
|
||||
{
|
||||
planned = request.CopyAgain
|
||||
? new PlannedFile(c, destination, PlannedCopy.Write, Again: true)
|
||||
: new PlannedFile(c, destination, PlannedCopy.RemovedOrSuperseded);
|
||||
? form with { DestinationId = destination, Action = PlannedCopy.Write, Again = true }
|
||||
: form with { DestinationId = destination, Action = PlannedCopy.RemovedOrSuperseded };
|
||||
}
|
||||
else if (oneOnly && await exports.FindCopiedElsewhereAsync(sha, ExportVariant.Whole, ExportFormat.Original, c.AccountId, ct).ConfigureAwait(false) is not null)
|
||||
else if (oneOnly && await exports.FindCopiedElsewhereAsync(sha, c.AccountId, ct).ConfigureAwait(false) is not null)
|
||||
{
|
||||
planned = new PlannedFile(c, destination, PlannedCopy.AlreadyCopied);
|
||||
planned = form with { DestinationId = destination, Action = PlannedCopy.AlreadyCopied };
|
||||
}
|
||||
else
|
||||
{
|
||||
planned = new PlannedFile(c, destination, PlannedCopy.Write);
|
||||
planned = form with { DestinationId = destination, Action = PlannedCopy.Write };
|
||||
}
|
||||
|
||||
if (planned.Action is PlannedCopy.Write or PlannedCopy.AlreadyCopied && !seen.Add(key))
|
||||
@@ -122,6 +240,128 @@ public sealed class ExportPlanner(ExportEnvironment env)
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A frames job (D12, D14 of tappa E3): photos are skipped, videos not due are counted as in «Copia in…», each due
|
||||
/// video gives one planned frame per instant of the request. A video of unknown length is measured by
|
||||
/// <paramref name="lengthOf"/> (the job: before anything is recorded, so that its frames count against the caps of
|
||||
/// D12) or, without it, gives one planned file without an instant (<see cref="PlannedFile.UnknownDuration"/>, the
|
||||
/// dialog). One that cannot be read gets one instant, and the copy says «Fotogramma non disponibile per questo
|
||||
/// video». Frames are not checked for «già copiato» here: the copy looks at each one's exact instant.
|
||||
/// </summary>
|
||||
private async IAsyncEnumerable<PlannedFile> EnumerateFramesAsync(
|
||||
ExportJobRequest request,
|
||||
ExportFramesRequest frames,
|
||||
IReadOnlyDictionary<long, EffectiveDestination> effective,
|
||||
Func<ExportCandidate, CancellationToken, Task<TimeSpan?>>? lengthOf,
|
||||
[EnumeratorCancellation] CancellationToken ct)
|
||||
{
|
||||
var exports = _env.Storage.Exports;
|
||||
var seen = new HashSet<(long Destination, long Account, string Sha256, long Ms, ExportFormat Format)>();
|
||||
long after = 0;
|
||||
while (true)
|
||||
{
|
||||
var page = await exports.ListCandidatesAsync(request.Selection, after, PageSize, ct).ConfigureAwait(false);
|
||||
if (page.Count == 0)
|
||||
{
|
||||
yield break;
|
||||
}
|
||||
|
||||
after = page[^1].MediaId;
|
||||
foreach (var c in page)
|
||||
{
|
||||
if (!IsPresent(c))
|
||||
{
|
||||
yield return new PlannedFile(c, null, PlannedCopy.Missing);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (c.MediaKind != MediaKind.Video)
|
||||
{
|
||||
yield return new PlannedFile(c, null, PlannedCopy.PhotoSkipped);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (Due(c, effective) is not { } destination)
|
||||
{
|
||||
yield return new PlannedFile(c, null, PlannedCopy.NotExported);
|
||||
continue;
|
||||
}
|
||||
|
||||
var frame = new PlannedFile(c, destination, PlannedCopy.Write)
|
||||
{
|
||||
Variant = ExportVariant.Frame,
|
||||
Format = frames.Format,
|
||||
Prediction = ExportPrediction.Converted,
|
||||
FirstOfVideo = true,
|
||||
};
|
||||
var duration = c.Duration ?? TimeSpan.Zero;
|
||||
if (frames.Mode != FrameMode.At && c.Duration is null)
|
||||
{
|
||||
if (lengthOf is null)
|
||||
{
|
||||
yield return frame with { UnknownDuration = true };
|
||||
continue;
|
||||
}
|
||||
|
||||
if (await lengthOf(c, ct).ConfigureAwait(false) is not { } measured || measured <= TimeSpan.Zero)
|
||||
{
|
||||
var unreadable = frame with { FrameAt = TimeSpan.Zero };
|
||||
yield return seen.Add((destination, c.AccountId, c.Sha256!, 0, frames.Format))
|
||||
? unreadable
|
||||
: unreadable with { Action = PlannedCopy.AlreadyCopied };
|
||||
continue;
|
||||
}
|
||||
|
||||
duration = measured;
|
||||
}
|
||||
|
||||
if (ExportFrames.FrameCount(duration, frames) > ExportFrames.MaxPerVideo)
|
||||
{
|
||||
yield return frame with { Action = PlannedCopy.OverCap };
|
||||
continue;
|
||||
}
|
||||
|
||||
var first = true;
|
||||
foreach (var at in ExportFrames.Instants(duration, frames))
|
||||
{
|
||||
var planned = frame with { FrameAt = at, FirstOfVideo = first };
|
||||
first = false;
|
||||
// By the millisecond the item keeps (ux_export_item_file): two instants on one are one item.
|
||||
if (!seen.Add((destination, c.AccountId, c.Sha256!, (long)at.TotalMilliseconds, frames.Format)))
|
||||
{
|
||||
planned = planned with { Action = PlannedCopy.AlreadyCopied };
|
||||
}
|
||||
|
||||
yield return planned;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The form a file is asked in (D1, D2): the request's identity, and what its name predicts.</summary>
|
||||
private static PlannedFile Form(ExportCandidate c, ExportJobRequest request, ExportDestination destination, ExportSettings settings)
|
||||
{
|
||||
if (request.Exact is { } exact)
|
||||
{
|
||||
var prediction = exact.Variant == ExportVariant.Whole ? ExportPrediction.Whole : ExportConversions.Predict(c.RelativePath!, c.MediaKind, exact.Format);
|
||||
return new PlannedFile(c, null, PlannedCopy.Write)
|
||||
{
|
||||
Variant = exact.Variant,
|
||||
Format = exact.Format,
|
||||
FrameAt = exact.FrameAt,
|
||||
Prediction = exact.Variant == ExportVariant.Frame ? ExportPrediction.Converted : prediction,
|
||||
};
|
||||
}
|
||||
|
||||
var target = ExportConversions.Resolve(c.MediaKind, request.Formats, destination, settings);
|
||||
return new PlannedFile(c, null, PlannedCopy.Write)
|
||||
{
|
||||
Variant = ExportConversions.VariantOf(target),
|
||||
Format = target,
|
||||
Prediction = ExportConversions.Predict(c.RelativePath!, c.MediaKind, target),
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>A file present in the library, with its SHA-256 and path.</summary>
|
||||
internal static bool IsPresent(ExportCandidate c) => EntryStateRules.IsPresent(c.State) && c.Sha256 is { Length: 64 } && !string.IsNullOrEmpty(c.RelativePath);
|
||||
|
||||
@@ -135,7 +375,26 @@ public sealed class ExportPlanner(ExportEnvironment env)
|
||||
/// <summary>A candidate with what the plan does with it.</summary>
|
||||
/// <param name="DestinationId">Where it goes; null when not exported or missing.</param>
|
||||
/// <param name="Again">Written although «Tolto» or «Superato», because «Copia di nuovo» was asked.</param>
|
||||
internal sealed record PlannedFile(ExportCandidate Candidate, long? DestinationId, PlannedCopy Action, bool Again = false);
|
||||
internal sealed record PlannedFile(ExportCandidate Candidate, long? DestinationId, PlannedCopy Action, bool Again = false)
|
||||
{
|
||||
/// <summary>The variant asked (the request, D2 of tappa E3): Whole, Converted or Frame.</summary>
|
||||
public ExportVariant Variant { get; init; } = ExportVariant.Whole;
|
||||
|
||||
/// <summary>The format asked.</summary>
|
||||
public ExportFormat Format { get; init; } = ExportFormat.Original;
|
||||
|
||||
/// <summary>The instant asked of a frame.</summary>
|
||||
public TimeSpan? FrameAt { get; init; }
|
||||
|
||||
/// <summary>What the name predicts («circa»).</summary>
|
||||
public ExportPrediction Prediction { get; init; } = ExportPrediction.Whole;
|
||||
|
||||
/// <summary>Frames job: the first planned file of its video (the videos are counted on it).</summary>
|
||||
public bool FirstOfVideo { get; init; }
|
||||
|
||||
/// <summary>Frames job: a video of unknown length, without instants yet («circa» one frame).</summary>
|
||||
public bool UnknownDuration { get; init; }
|
||||
}
|
||||
|
||||
internal enum PlannedCopy
|
||||
{
|
||||
@@ -144,12 +403,19 @@ internal enum PlannedCopy
|
||||
RemovedOrSuperseded,
|
||||
NotExported,
|
||||
Missing,
|
||||
|
||||
/// <summary>Frames job: a photo of the selection.</summary>
|
||||
PhotoSkipped,
|
||||
|
||||
/// <summary>Frames job: a video over <see cref="ExportFrames.MaxPerVideo"/> frames.</summary>
|
||||
OverCap,
|
||||
}
|
||||
|
||||
/// <summary>Counts of a plan while its files go by.</summary>
|
||||
internal sealed class PlanTally
|
||||
{
|
||||
private readonly Dictionary<long, (int Files, long Bytes)> _byDestination = [];
|
||||
private readonly Dictionary<string, int> _asIs = new(StringComparer.Ordinal);
|
||||
|
||||
public int Files { get; private set; }
|
||||
|
||||
@@ -163,8 +429,25 @@ internal sealed class PlanTally
|
||||
|
||||
public int Missing { get; private set; }
|
||||
|
||||
public int Converted { get; private set; }
|
||||
|
||||
public bool Lossy { get; private set; }
|
||||
|
||||
public int Videos { get; private set; }
|
||||
|
||||
public int PhotosSkipped { get; private set; }
|
||||
|
||||
public int Frames { get; private set; }
|
||||
|
||||
public int OverCap { get; private set; }
|
||||
|
||||
public void Add(PlannedFile file)
|
||||
{
|
||||
if (file.FirstOfVideo && file.Action is not (PlannedCopy.OverCap or PlannedCopy.NotExported or PlannedCopy.Missing))
|
||||
{
|
||||
Videos++;
|
||||
}
|
||||
|
||||
switch (file.Action)
|
||||
{
|
||||
case PlannedCopy.Missing:
|
||||
@@ -173,6 +456,13 @@ internal sealed class PlanTally
|
||||
case PlannedCopy.NotExported:
|
||||
NotExported++;
|
||||
return;
|
||||
case PlannedCopy.PhotoSkipped:
|
||||
PhotosSkipped++;
|
||||
return;
|
||||
case PlannedCopy.OverCap:
|
||||
OverCap++;
|
||||
Videos++;
|
||||
return;
|
||||
case PlannedCopy.AlreadyCopied:
|
||||
AlreadyCopied++;
|
||||
break;
|
||||
@@ -180,7 +470,8 @@ internal sealed class PlanTally
|
||||
RemovedOrSuperseded++;
|
||||
break;
|
||||
case PlannedCopy.Write:
|
||||
var bytes = file.Candidate.Bytes ?? 0;
|
||||
var frame = file.Variant == ExportVariant.Frame;
|
||||
var bytes = frame ? 0 : file.Candidate.Bytes ?? 0;
|
||||
Files++;
|
||||
Bytes += bytes;
|
||||
if (file.Again)
|
||||
@@ -188,6 +479,21 @@ internal sealed class PlanTally
|
||||
RemovedOrSuperseded++;
|
||||
}
|
||||
|
||||
if (frame)
|
||||
{
|
||||
Frames++;
|
||||
Lossy |= file.Format == ExportFormat.Jpg;
|
||||
}
|
||||
else if (file.Prediction == ExportPrediction.Converted)
|
||||
{
|
||||
Converted++;
|
||||
Lossy |= file.Format == ExportFormat.Jpg;
|
||||
}
|
||||
else if (file.Prediction == ExportPrediction.AsIs && ExportConversions.AsIsLabel(file.Candidate.RelativePath!) is { } label)
|
||||
{
|
||||
_asIs[label] = _asIs.GetValueOrDefault(label) + 1;
|
||||
}
|
||||
|
||||
var (f, b) = _byDestination.GetValueOrDefault(file.DestinationId!.Value);
|
||||
_byDestination[file.DestinationId.Value] = (f + 1, b + bytes);
|
||||
return;
|
||||
@@ -230,7 +536,16 @@ internal sealed class PlanTally
|
||||
}
|
||||
|
||||
var any = rows.Count > 0 || (await env.Storage.Exports.ListDestinationsAsync(false, ct).ConfigureAwait(false)).Count > 0;
|
||||
return new ExportPlan(Files, Bytes, AlreadyCopied, RemovedOrSuperseded, NotExported, Missing, list, any);
|
||||
return new ExportPlan(Files, Bytes, AlreadyCopied, RemovedOrSuperseded, NotExported, Missing, list, any)
|
||||
{
|
||||
AsIs = _asIs.OrderByDescending(p => p.Value).ThenBy(p => p.Key, StringComparer.Ordinal).Select(p => new ExportPlanAsIs(p.Key, p.Value)).ToList(),
|
||||
Converted = Converted,
|
||||
Lossy = Lossy,
|
||||
Videos = Videos,
|
||||
PhotosSkipped = PhotosSkipped,
|
||||
Frames = Frames,
|
||||
OverCap = OverCap,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>Destinations that get a run: those with files to write, already copied, or «tolti o superati».</summary>
|
||||
|
||||
@@ -12,10 +12,24 @@ public sealed record ExportReport(
|
||||
IReadOnlyDictionary<ExportItemState, int> ByState,
|
||||
long BytesCopied,
|
||||
IReadOnlyList<ExportReportAccount> Accounts,
|
||||
IReadOnlyList<ExportReportLine> Problems);
|
||||
IReadOnlyList<ExportReportLine> Problems)
|
||||
{
|
||||
/// <summary>
|
||||
/// Tappa E3: at most <see cref="ExportReports.MaxProblems"/> files copied or adopted with a note (copied as they
|
||||
/// are, what a conversion did not keep, a free name).
|
||||
/// </summary>
|
||||
public IReadOnlyList<ExportReportLine> Notes { get; init; } = [];
|
||||
}
|
||||
|
||||
/// <summary>The files of one account in a job («Copiato» counts written and adopted files).</summary>
|
||||
public sealed record ExportReportAccount(long? AccountId, string Username, int Copied, int AlreadyCopied, int Skipped, int Failed);
|
||||
public sealed record ExportReportAccount(long? AccountId, string Username, int Copied, int AlreadyCopied, int Skipped, int Failed)
|
||||
{
|
||||
/// <summary>
|
||||
/// Tappa E3: the files copied as they are, by kind («HEIC», «AVIF», «raw», «animata», «video», «altro»): the exact
|
||||
/// counts of the job, where the plan's are predictions.
|
||||
/// </summary>
|
||||
public IReadOnlyDictionary<string, int> AsIs { get; init; } = new Dictionary<string, int>();
|
||||
}
|
||||
|
||||
/// <summary>A file of the report, with its reason in Italian.</summary>
|
||||
public sealed record ExportReportLine(long ItemId, string Username, string? RelativePath, ExportItemState State, string Text);
|
||||
@@ -45,6 +59,8 @@ public sealed class ExportReports(ExportEnvironment env)
|
||||
|
||||
var accounts = new Dictionary<long, int[]>();
|
||||
var problems = new List<ExportReportLine>();
|
||||
var notes = new List<ExportReportLine>();
|
||||
var asIs = new Dictionary<long, Dictionary<string, int>>();
|
||||
long bytes = 0;
|
||||
long after = 0;
|
||||
while (true)
|
||||
@@ -68,6 +84,21 @@ public sealed class ExportReports(ExportEnvironment env)
|
||||
{
|
||||
case ExportItemState.Copied or ExportItemState.Adopted:
|
||||
row[0]++;
|
||||
if (AsIsLabel(item.Note) is { } label)
|
||||
{
|
||||
if (!asIs.TryGetValue(key, out var kinds))
|
||||
{
|
||||
asIs[key] = kinds = new Dictionary<string, int>(StringComparer.Ordinal);
|
||||
}
|
||||
|
||||
kinds[label] = kinds.GetValueOrDefault(label) + 1;
|
||||
}
|
||||
|
||||
if (item.Note is not null && notes.Count < MaxProblems && ExportText.Note(item.Note) is { } noted)
|
||||
{
|
||||
notes.Add(new ExportReportLine(item.Id, Name(item.AccountId), item.RelativePath, item.State, noted));
|
||||
}
|
||||
|
||||
if (item.CopyId is { } copyId && await exports.GetCopyAsync(copyId, ct).ConfigureAwait(false) is { Bytes: { } b })
|
||||
{
|
||||
bytes += b;
|
||||
@@ -98,9 +129,42 @@ public sealed class ExportReports(ExportEnvironment env)
|
||||
}
|
||||
|
||||
var perAccount = accounts
|
||||
.Select(a => new ExportReportAccount(a.Key == 0 ? null : a.Key, Name(a.Key == 0 ? null : a.Key), a.Value[0], a.Value[1], a.Value[2], a.Value[3]))
|
||||
.Select(a => new ExportReportAccount(a.Key == 0 ? null : a.Key, Name(a.Key == 0 ? null : a.Key), a.Value[0], a.Value[1], a.Value[2], a.Value[3])
|
||||
{
|
||||
AsIs = asIs.TryGetValue(a.Key, out var kinds) ? kinds : new Dictionary<string, int>(),
|
||||
})
|
||||
.OrderBy(a => a.Username, StringComparer.OrdinalIgnoreCase)
|
||||
.ToList();
|
||||
return new ExportReport(run, destination, summary.Total, summary.ByState, bytes, perAccount, problems);
|
||||
return new ExportReport(run, destination, summary.Total, summary.ByState, bytes, perAccount, problems) { Notes = notes };
|
||||
}
|
||||
|
||||
/// <summary>The kind of a file copied as it is, from the codes of its note; null when it was not.</summary>
|
||||
internal static string? AsIsLabel(string? note)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(note))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
foreach (var code in note.Split(' ', StringSplitOptions.RemoveEmptyEntries))
|
||||
{
|
||||
var name = code.Split(':', 2)[0];
|
||||
var label = name switch
|
||||
{
|
||||
ExportText.Notes.AsIsHeif => "HEIC",
|
||||
ExportText.Notes.AsIsAvif => "AVIF",
|
||||
ExportText.Notes.AsIsRaw => "raw",
|
||||
ExportText.Notes.AsIsAnimated => "animata",
|
||||
ExportText.Notes.AsIsNotRemuxable => "video",
|
||||
_ when name.StartsWith("AsIs", StringComparison.Ordinal) => "altro",
|
||||
_ => null,
|
||||
};
|
||||
if (label is not null)
|
||||
{
|
||||
return label;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -11,6 +11,53 @@ internal static class ExportRunSettings
|
||||
{
|
||||
public static string CopyAgainKey(long runId) => string.Create(CultureInfo.InvariantCulture, $"esportazione.lavoro.{runId}.copia-di-nuovo");
|
||||
|
||||
/// <summary>How the frames of a frames job were asked (tappa E3): <c>Istante</c>, <c>Ogni</c> or <c>Numero:N</c>.</summary>
|
||||
public static string FramesKey(long runId) => string.Create(CultureInfo.InvariantCulture, $"esportazione.lavoro.{runId}.fotogrammi");
|
||||
|
||||
/// <summary>«Copia di nuovo» of one copy row: only its exact identity is looked up (decision D11 of tappa E3).</summary>
|
||||
public static string ExactKey(long runId) => string.Create(CultureInfo.InvariantCulture, $"esportazione.lavoro.{runId}.esatta");
|
||||
|
||||
/// <summary>The frames request of a job, or null for a job of whole or converted files.</summary>
|
||||
public static async Task<(FrameMode Mode, int Count)?> GetFramesAsync(ISettingsStore store, long runId, CancellationToken ct)
|
||||
{
|
||||
var text = (await store.GetAsync(FramesKey(runId), ct).ConfigureAwait(false))?.Trim();
|
||||
if (text is null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
if (string.Equals(text, "Istante", StringComparison.Ordinal))
|
||||
{
|
||||
return (FrameMode.At, 1);
|
||||
}
|
||||
|
||||
if (string.Equals(text, "Ogni", StringComparison.Ordinal))
|
||||
{
|
||||
return (FrameMode.Every, 0);
|
||||
}
|
||||
|
||||
return text.StartsWith("Numero:", StringComparison.Ordinal)
|
||||
&& int.TryParse(text.AsSpan("Numero:".Length), NumberStyles.None, CultureInfo.InvariantCulture, out var count) && count > 0
|
||||
? (FrameMode.Count, count)
|
||||
: null;
|
||||
}
|
||||
|
||||
public static Task SetFramesAsync(ISettingsStore store, long runId, FrameMode mode, int count, CancellationToken ct) =>
|
||||
store.SetAsync(
|
||||
FramesKey(runId),
|
||||
mode switch
|
||||
{
|
||||
FrameMode.At => "Istante",
|
||||
FrameMode.Every => "Ogni",
|
||||
_ => string.Create(CultureInfo.InvariantCulture, $"Numero:{count}"),
|
||||
},
|
||||
ct);
|
||||
|
||||
public static async Task<bool> GetExactAsync(ISettingsStore store, long runId, CancellationToken ct) =>
|
||||
string.Equals((await store.GetAsync(ExactKey(runId), ct).ConfigureAwait(false))?.Trim(), "1", StringComparison.Ordinal);
|
||||
|
||||
public static Task SetExactAsync(ISettingsStore store, long runId, CancellationToken ct) => store.SetAsync(ExactKey(runId), "1", ct);
|
||||
|
||||
/// <summary>«Copia di nuovo anche i tolti o superati» was chosen for this job (decision D9).</summary>
|
||||
public static async Task<bool> GetCopyAgainAsync(ISettingsStore store, long runId, CancellationToken ct)
|
||||
{
|
||||
@@ -21,6 +68,14 @@ internal static class ExportRunSettings
|
||||
public static Task SetCopyAgainAsync(ISettingsStore store, long runId, bool value, CancellationToken ct) =>
|
||||
store.SetAsync(CopyAgainKey(runId), value ? "1" : null, ct);
|
||||
|
||||
/// <summary>Every key of the job, in one transaction (a run id can be used again after <c>DeleteRunAsync</c>).</summary>
|
||||
public static Task ClearAsync(ISettingsStore store, long runId, CancellationToken ct) =>
|
||||
store.SetAsync(CopyAgainKey(runId), null, ct);
|
||||
store.SetManyAsync(
|
||||
new Dictionary<string, string?>
|
||||
{
|
||||
[CopyAgainKey(runId)] = null,
|
||||
[FramesKey(runId)] = null,
|
||||
[ExactKey(runId)] = null,
|
||||
},
|
||||
ct);
|
||||
}
|
||||
@@ -15,6 +15,9 @@ namespace Febe.Core.Export;
|
||||
public sealed class ExportService : IAsyncDisposable
|
||||
{
|
||||
private const string BusyText = "C'è già una copia al lavoro: aspetta che finisca o interrompila.";
|
||||
|
||||
/// <summary>A frames request over <see cref="ExportFrames.MaxPerRequest"/>.</summary>
|
||||
public const string TooManyFramesText = "Più di 20.000 fotogrammi in una richiesta: scegli meno video o un intervallo più lungo";
|
||||
private const int ItemBatch = 2000;
|
||||
private static readonly TimeSpan ProgressInterval = TimeSpan.FromMilliseconds(250);
|
||||
|
||||
@@ -114,9 +117,13 @@ public sealed class ExportService : IAsyncDisposable
|
||||
/// recorded and nothing starts.
|
||||
/// </summary>
|
||||
/// <exception cref="InvalidOperationException">A copy, an import or a rebuild is running.</exception>
|
||||
/// <exception cref="ArgumentException">
|
||||
/// The request is not valid, or a frames request asks more than 1.000 frames of a video or 20.000 in all (Italian message).
|
||||
/// </exception>
|
||||
public async Task<ExportStart> StartAsync(ExportJobRequest request, CancellationToken ct = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(request);
|
||||
ExportPlanner.Validate(request);
|
||||
var held = new LeaseHolder();
|
||||
lock (_gate)
|
||||
{
|
||||
@@ -160,12 +167,48 @@ public sealed class ExportService : IAsyncDisposable
|
||||
var runs = new Dictionary<long, ExportRun>();
|
||||
var pending = new List<ExportItem>();
|
||||
var exports = _env.Storage.Exports;
|
||||
// Frames job: the videos whose length the library does not know are measured once, in the first pass, so that
|
||||
// their frames count against the caps; the recording pass reuses the lengths (they cannot disagree).
|
||||
var lengths = new Dictionary<long, TimeSpan?>();
|
||||
Func<ExportCandidate, CancellationToken, Task<TimeSpan?>>? lengthOf = request.Frames is null
|
||||
? null
|
||||
: async (candidate, token) =>
|
||||
{
|
||||
if (!lengths.TryGetValue(candidate.MediaId, out var length))
|
||||
{
|
||||
length = await ProbeLengthAsync(candidate, token).ConfigureAwait(false);
|
||||
lengths[candidate.MediaId] = length;
|
||||
}
|
||||
|
||||
return length;
|
||||
};
|
||||
if (request.Frames is not null)
|
||||
{
|
||||
// Refused before anything is recorded (D12 of tappa E3): a video over 1.000 frames, more than 20.000 in all.
|
||||
var count = new PlanTally();
|
||||
await foreach (var file in Planner.EnumerateAsync(request, effective, settings, ct, lengthOf).ConfigureAwait(false))
|
||||
{
|
||||
count.Add(file);
|
||||
}
|
||||
|
||||
if (count.OverCap > 0)
|
||||
{
|
||||
throw new ArgumentException(ExportFrames.OverCapMessage, nameof(request));
|
||||
}
|
||||
|
||||
if (count.Frames > ExportFrames.MaxPerRequest)
|
||||
{
|
||||
throw new ArgumentException(TooManyFramesText, nameof(request));
|
||||
}
|
||||
}
|
||||
|
||||
var frameItems = 0;
|
||||
try
|
||||
{
|
||||
await foreach (var file in Planner.EnumerateAsync(request, effective, settings, ct).ConfigureAwait(false))
|
||||
await foreach (var file in Planner.EnumerateAsync(request, effective, settings, ct, lengthOf).ConfigureAwait(false))
|
||||
{
|
||||
tally.Add(file);
|
||||
if (file.DestinationId is not { } destination || file.Action is PlannedCopy.Missing or PlannedCopy.NotExported)
|
||||
if (file.DestinationId is not { } destination || file.Action is PlannedCopy.Missing or PlannedCopy.NotExported or PlannedCopy.PhotoSkipped or PlannedCopy.OverCap)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
@@ -176,10 +219,14 @@ public sealed class ExportService : IAsyncDisposable
|
||||
new ExportRun { DestinationId = destination, Kind = ExportRunKind.Copy, Origin = request.Origin, State = ExportRunState.Running, StartedAt = _env.Clock.Now },
|
||||
CancellationToken.None).ConfigureAwait(false);
|
||||
runs[destination] = run;
|
||||
if (request.CopyAgain)
|
||||
{
|
||||
await ExportRunSettings.SetCopyAgainAsync(_env.Storage.Settings, run.Id, true, CancellationToken.None).ConfigureAwait(false);
|
||||
}
|
||||
await RecordRunSettingsAsync(run.Id, request).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
// Frame items of one video are added together, in instant order (the copy takes them as one batch).
|
||||
// The first pass already refused more than 20.000: this only guards that it saw the same files.
|
||||
if (file.Variant == ExportVariant.Frame && file.Action == PlannedCopy.Write && ++frameItems > ExportFrames.MaxPerRequest)
|
||||
{
|
||||
throw new ArgumentException(TooManyFramesText, nameof(request));
|
||||
}
|
||||
|
||||
pending.Add(new ExportItem
|
||||
@@ -188,10 +235,12 @@ public sealed class ExportService : IAsyncDisposable
|
||||
MediaId = file.Candidate.MediaId,
|
||||
AccountId = file.Candidate.AccountId,
|
||||
SourceSha256 = file.Candidate.Sha256,
|
||||
Variant = ExportVariant.Whole,
|
||||
Format = ExportFormat.Original,
|
||||
Variant = file.Variant,
|
||||
Format = file.Format,
|
||||
FrameAt = file.FrameAt,
|
||||
State = ExportItemState.Pending,
|
||||
});
|
||||
|
||||
if (pending.Count >= ItemBatch)
|
||||
{
|
||||
await exports.AddItemsAsync(pending, CancellationToken.None).ConfigureAwait(false);
|
||||
@@ -235,6 +284,65 @@ public sealed class ExportService : IAsyncDisposable
|
||||
return new ExportStart(ordered, plan);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The keys of a new job: cleared first (a run id can be used again after <c>DeleteRunAsync</c>), then what a resume
|
||||
/// needs to know (WP1.2 of tappa E3): «Copia di nuovo», the frames request, the exact identity of «Copia di nuovo»
|
||||
/// of one copy.
|
||||
/// </summary>
|
||||
private async Task RecordRunSettingsAsync(long runId, ExportJobRequest request)
|
||||
{
|
||||
var store = _env.Storage.Settings;
|
||||
var none = CancellationToken.None;
|
||||
await ExportRunSettings.ClearAsync(store, runId, none).ConfigureAwait(false);
|
||||
if (request.CopyAgain)
|
||||
{
|
||||
await ExportRunSettings.SetCopyAgainAsync(store, runId, true, none).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
if (request.Frames is { } frames)
|
||||
{
|
||||
await ExportRunSettings.SetFramesAsync(store, runId, frames.Mode, frames.Count ?? 0, none).ConfigureAwait(false);
|
||||
}
|
||||
else if (request.Exact is { Variant: ExportVariant.Frame })
|
||||
{
|
||||
await ExportRunSettings.SetFramesAsync(store, runId, FrameMode.At, 1, none).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
if (request.Exact is not null)
|
||||
{
|
||||
await ExportRunSettings.SetExactAsync(store, runId, none).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The length of a video the library does not know, from its headers (only the library file, never the
|
||||
/// destination); null when it cannot be read now (the job then gives it one instant, and the copy tells).
|
||||
/// </summary>
|
||||
private async Task<TimeSpan?> ProbeLengthAsync(ExportCandidate candidate, CancellationToken ct)
|
||||
{
|
||||
var media = await _env.Storage.Media.GetAsync(candidate.MediaId, ct).ConfigureAwait(false);
|
||||
var account = await _env.Storage.Accounts.GetAsync(candidate.AccountId, ct).ConfigureAwait(false);
|
||||
if (media is null || account is null || _env.ResolveSourcePath(account, media) is not { } path)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
return await Task.Run(
|
||||
() =>
|
||||
{
|
||||
using var stream = _env.FileSystem.OpenRandomAccess(path);
|
||||
return VideoFrameReader.ProbeDuration(stream);
|
||||
},
|
||||
ct).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
return null; // not readable now: one instant, the copy tells
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// «Riprendi»: continues unfinished jobs in the background, oldest first. Null: every interrupted or paused one (a
|
||||
/// paused one checks its destination first and pauses again if it still does not answer).
|
||||
|
||||
@@ -68,18 +68,19 @@ public sealed record ExportSettings(
|
||||
public Task SaveAsync(ISettingsStore store, CancellationToken ct = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(store);
|
||||
return store.SetManyAsync(
|
||||
new Dictionary<string, string?>
|
||||
{
|
||||
[ExportSettingKeys.PhotoFormat] = PhotoFormat.ToString(),
|
||||
[ExportSettingKeys.VideoFormat] = VideoFormat.ToString(),
|
||||
[ExportSettingKeys.LibraryPhotoFormat] = LibraryPhotoFormat.ToString(),
|
||||
[ExportSettingKeys.LibraryVideoFormat] = LibraryVideoFormat.ToString(),
|
||||
[ExportSettingKeys.SamePost] = SamePost.ToString(),
|
||||
},
|
||||
ct);
|
||||
return store.SetManyAsync(Values(), ct);
|
||||
}
|
||||
|
||||
/// <summary>The five keys with their stored values (for a write that stores more with them).</summary>
|
||||
public Dictionary<string, string?> Values() => new(StringComparer.Ordinal)
|
||||
{
|
||||
[ExportSettingKeys.PhotoFormat] = PhotoFormat.ToString(),
|
||||
[ExportSettingKeys.VideoFormat] = VideoFormat.ToString(),
|
||||
[ExportSettingKeys.LibraryPhotoFormat] = LibraryPhotoFormat.ToString(),
|
||||
[ExportSettingKeys.LibraryVideoFormat] = LibraryVideoFormat.ToString(),
|
||||
[ExportSettingKeys.SamePost] = SamePost.ToString(),
|
||||
};
|
||||
|
||||
/// <summary>The settings from stored values: exact, case-sensitive names; anything else gives the key's default.</summary>
|
||||
internal static ExportSettings From(IReadOnlyDictionary<string, string> values)
|
||||
{
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Core.Library.Conversion;
|
||||
using Febe.Core.Storage;
|
||||
|
||||
namespace Febe.Core.Export;
|
||||
@@ -25,6 +26,7 @@ public static class ExportSupersession
|
||||
}
|
||||
|
||||
var old = oldSha256.ToLowerInvariant();
|
||||
await LibraryConversionsChangedAsync(storage, accountId, old, newSha256.ToLowerInvariant(), at).ConfigureAwait(false);
|
||||
var users = await storage.Media.FindBySha256Async(old, ct).ConfigureAwait(false);
|
||||
if (users.Any(u => u.Entry.AccountId == accountId && EntryStateRules.IsPresent(u.Media.State)))
|
||||
{
|
||||
@@ -33,4 +35,31 @@ public static class ExportSupersession
|
||||
|
||||
return await storage.Exports.SupersedeCopiesAsync(accountId, old, newSha256.ToLowerInvariant(), at, CancellationToken.None).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The conversions for the library of the account's file that now has <paramref name="newSha256"/> (tappa E3,
|
||||
/// WP2.4): a converted file of the old bytes is «Superato» (it stays), the queue and the failures take the new bytes,
|
||||
/// and the file is queued again in the library formats set now.
|
||||
/// </summary>
|
||||
private static async Task LibraryConversionsChangedAsync(IFebeStorage storage, long accountId, string oldSha256, string newSha256, DateTimeOffset at)
|
||||
{
|
||||
var none = CancellationToken.None;
|
||||
var changed = await storage.Conversions.SupersedeAsync(accountId, oldSha256, newSha256, at, none).ConfigureAwait(false);
|
||||
if (changed.Count == 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var media = new List<Media>();
|
||||
foreach (var id in changed)
|
||||
{
|
||||
if (await storage.Media.GetAsync(id, none).ConfigureAwait(false) is { } m)
|
||||
{
|
||||
media.Add(m);
|
||||
}
|
||||
}
|
||||
|
||||
await LibraryConversionQueue.EnqueueEntryAsync(storage, media, at, none).ConfigureAwait(false);
|
||||
LibraryConversionQueue.Signal();
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,8 @@
|
||||
using Febe.Core.Codecs.Containers;
|
||||
using Febe.Core.Codecs.Images;
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Core.Engine;
|
||||
using Febe.Core.Library.Conversion;
|
||||
using Febe.Core.Storage;
|
||||
|
||||
namespace Febe.Core.Export;
|
||||
@@ -24,6 +27,22 @@ public static class ExportText
|
||||
public const string NameTaken = "NameTaken";
|
||||
public const string PathTaken = "PathTaken";
|
||||
public const string NotExported = "NotExported";
|
||||
|
||||
// Tappa E3 (D19): an item's note is a list of codes separated by spaces, «Code» or «Code:Arg».
|
||||
public const string AsIsHeif = ImageConversionLosses.AsIsHeif;
|
||||
public const string AsIsAvif = ImageConversionLosses.AsIsAvif;
|
||||
public const string AsIsRaw = ImageConversionLosses.AsIsRaw;
|
||||
public const string AsIsAnimated = ImageConversionLosses.AsIsAnimated;
|
||||
public const string AsIsNotDecodable = ImageConversionLosses.AsIsNotDecodable;
|
||||
public const string AsIsDeepColor = ImageConversionLosses.AsIsDeepColor;
|
||||
public const string AsIsCmyk = ImageConversionLosses.AsIsCmyk;
|
||||
public const string AsIsTooLarge = ImageConversionLosses.AsIsTooLarge;
|
||||
public const string AsIsNotRemuxable = MediaConversionResult.AsIsNotRemuxable;
|
||||
public const string FrameNotAvailable = "FrameNotAvailable";
|
||||
public const string TransparencyWhite = ImageConversionLosses.TransparencyWhite;
|
||||
public const string CopiedInAnotherFormat = "CopiedInAnotherFormat";
|
||||
public const string LostTracks = Mp4Remuxer.LostTracks;
|
||||
public const string LostVideoMetadata = Mp4Remuxer.LostVideoMetadata;
|
||||
}
|
||||
|
||||
/// <summary>Name of the state of a file of a job.</summary>
|
||||
@@ -49,21 +68,95 @@ public static class ExportText
|
||||
_ => state.ToString(),
|
||||
};
|
||||
|
||||
/// <summary>The Italian text of a note code; null for none; an unknown code is shown as it is.</summary>
|
||||
public static string? Note(string? code) => code switch
|
||||
/// <summary>
|
||||
/// The Italian text of a note: its codes (separated by spaces, D19 of tappa E3) each in Italian, joined with « · »;
|
||||
/// null for none; an unknown code is shown as it is.
|
||||
/// </summary>
|
||||
public static string? Note(string? note)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(note))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var codes = note.Split(' ', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
|
||||
return string.Join(" · ", codes.Select(One));
|
||||
}
|
||||
|
||||
/// <summary>The codes as one note (D19 of tappa E3): the non-empty ones, without repeats, separated by spaces; null for none.</summary>
|
||||
public static string? JoinNotes(IEnumerable<string?> codes)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(codes);
|
||||
var list = codes.Where(c => !string.IsNullOrWhiteSpace(c)).Select(c => c!.Trim()).Distinct(StringComparer.Ordinal).ToList();
|
||||
return list.Count == 0 ? null : string.Join(' ', list);
|
||||
}
|
||||
|
||||
/// <summary>The reason of «non si porta in MP4», from the code of <see cref="RemuxRefusal"/>.</summary>
|
||||
private static string RemuxReason(string reason) => reason switch
|
||||
{
|
||||
nameof(RemuxRefusal.NotAVideo) => "Febe non lo riconosce come video",
|
||||
nameof(RemuxRefusal.ContainerNotRemuxable) => "contenitore",
|
||||
nameof(RemuxRefusal.VideoCodec) => "codec video",
|
||||
nameof(RemuxRefusal.AudioCodec) => "codec audio",
|
||||
nameof(RemuxRefusal.MissingConfiguration) => "configurazione del codec mancante",
|
||||
nameof(RemuxRefusal.EncodedTrack) => "tracce codificate",
|
||||
nameof(RemuxRefusal.EditList) => "elenco di modifiche",
|
||||
nameof(RemuxRefusal.NoSamples) => "nessun fotogramma",
|
||||
nameof(RemuxRefusal.Unreadable) => "file rovinato",
|
||||
_ => reason,
|
||||
};
|
||||
|
||||
private static string One(string code)
|
||||
{
|
||||
var colon = code.IndexOf(':', StringComparison.Ordinal);
|
||||
var name = colon < 0 ? code : code[..colon];
|
||||
var arg = colon < 0 ? null : code[(colon + 1)..];
|
||||
const string AsIsVideo = "Video copiato com'è: non si porta in MP4 senza ricodificarlo";
|
||||
return name switch
|
||||
{
|
||||
Notes.AsIsNotRemuxable => arg is { Length: > 0 } ? $"{AsIsVideo} ({RemuxReason(arg)})" : AsIsVideo,
|
||||
Notes.LostTracks => arg is { Length: > 0 } ? $"Tracce tolte: {arg}" : "Tracce tolte",
|
||||
_ when arg is null => Note1(code) ?? code,
|
||||
_ => code,
|
||||
};
|
||||
}
|
||||
|
||||
private static string? Note1(string code) => code switch
|
||||
{
|
||||
null or "" => null,
|
||||
Notes.SourceMissing => "File non presente in libreria",
|
||||
Notes.AccountRemoved => "L'account è stato rimosso",
|
||||
Notes.Removed => "Tolto dalla destinazione: non si ricopia da solo («Copia di nuovo»)",
|
||||
Notes.Superseded => "Superato da un file nuovo della libreria: non si ricopia da solo",
|
||||
Notes.CopiedForAnotherAccount => "Già copiato per un altro account («Una copia sola»)",
|
||||
Notes.SourceChanged => "Il file della libreria non corrisponde a quello registrato",
|
||||
Notes.SourceChanged => "Il file della libreria è cambiato durante la copia",
|
||||
Notes.TooLargeForFileSystem => "Più grande di 4 GB: il disco FAT32 non lo accetta",
|
||||
Notes.NameTaken => "Nome già occupato da un altro file: copiato con un nome libero",
|
||||
Notes.PathTaken => "Percorso preso nel frattempo: riprova",
|
||||
Notes.NotExported => "Non si copia qui: «Esporta questo account» è spento, o il file va in un'altra cartella",
|
||||
_ => code,
|
||||
Notes.AsIsHeif => "HEIC copiato com'è",
|
||||
Notes.AsIsAvif => "AVIF copiato com'è",
|
||||
Notes.AsIsRaw => "Raw copiato com'è",
|
||||
Notes.AsIsAnimated => "Immagine animata copiata com'è: convertita perderebbe i fotogrammi dopo il primo",
|
||||
Notes.AsIsNotDecodable => "Copiato com'è: Febe non riesce a leggere l'immagine",
|
||||
Notes.AsIsDeepColor => "Copiato com'è: più di 8 bit per colore",
|
||||
Notes.AsIsCmyk => "Copiato com'è: immagine CMYK",
|
||||
Notes.AsIsTooLarge => "Copiato com'è: troppo grande per il formato scelto",
|
||||
Notes.FrameNotAvailable => "Fotogramma non disponibile per questo video",
|
||||
Notes.TransparencyWhite => "La trasparenza è diventata bianco",
|
||||
Notes.CopiedInAnotherFormat => "Già copiato in un altro formato",
|
||||
ImageConversionLosses.LostTexts => "Non tenuti: testi",
|
||||
ImageConversionLosses.LostColorChunks => "Non tenuti: dati del colore",
|
||||
ImageConversionLosses.LostIcc => "Non tenuto: profilo ICC",
|
||||
ImageConversionLosses.LostIccTooLarge => "Non tenuto: profilo ICC troppo grande",
|
||||
ImageConversionLosses.LostExifTooLarge => "Non tenuto: EXIF troppo grande per JPG",
|
||||
ImageConversionLosses.LostXmpTooLarge => "Non tenuto: XMP troppo grande",
|
||||
ImageConversionLosses.LostExifUnreadable => "Non tenuto: EXIF rovinato",
|
||||
ImageConversionLosses.LostIptc => "Non tenuti: IPTC",
|
||||
ImageConversionLosses.LostOtherSegments => "Non tenuti: altri blocchi",
|
||||
ImageConversionLosses.LostCommentTooLarge => "Non tenuto: commento troppo lungo",
|
||||
ImageConversionLosses.LostExtendedXmp => "Non tenuto: XMP esteso",
|
||||
Notes.LostVideoMetadata => "Non tenuti: metadati del video",
|
||||
_ => null,
|
||||
};
|
||||
|
||||
/// <summary>«1 file copiato», «1.204 file copiati».</summary>
|
||||
|
||||
@@ -7,6 +7,9 @@ namespace Febe.Core.Import;
|
||||
/// <summary>What the comparison decided for one file.</summary>
|
||||
internal sealed record Comparison(ImportOutcome Outcome, long? MatchedMediaId, DuplicatePair? Pair, string? Note);
|
||||
|
||||
/// <summary>A file of the source that is a converted copy of a library file; its original when known.</summary>
|
||||
internal sealed record ConvertedCopyMatch(long? MediaId);
|
||||
|
||||
/// <summary>
|
||||
/// The comparison with the library (spec §9.3), for one analysis session. In this order:
|
||||
/// <list type="number">
|
||||
@@ -39,6 +42,9 @@ internal sealed class ImportComparer
|
||||
private readonly Dictionary<string, long> _sourceIdentity = new(StringComparer.Ordinal);
|
||||
private readonly PerceptualHashIndex _sourceHashes = new();
|
||||
|
||||
// The SHA-256 of the converted copies and frames written in destinations (one read per run, tappa E3, Q37).
|
||||
private IReadOnlySet<string> _copyShas = new HashSet<string>(StringComparer.Ordinal);
|
||||
|
||||
private ImportComparer(IFebeStorage storage, PerceptualHashIndex library, Func<DateTimeOffset> now)
|
||||
{
|
||||
_storage = storage;
|
||||
@@ -69,6 +75,7 @@ internal sealed class ImportComparer
|
||||
}
|
||||
|
||||
var comparer = new ImportComparer(storage, library, now);
|
||||
comparer._copyShas = await storage.Exports.LoadConvertedCopyShasAsync(ct).ConfigureAwait(false);
|
||||
var identifiers = await storage.Imports.LoadLibraryIdentifiersAsync(ct).ConfigureAwait(false);
|
||||
foreach (var entry in identifiers.Entries)
|
||||
{
|
||||
@@ -141,6 +148,13 @@ internal sealed class ImportComparer
|
||||
return new Comparison(ImportOutcome.AlreadyInLibrary, deleted.Media.Id, null, ImportText.NoteDeletedByAlberto);
|
||||
}
|
||||
|
||||
// A converted file of the library, or a converted copy or a frame of a destination: already in the library as
|
||||
// its original, never a probable duplicate of it (tappa E3, Q37).
|
||||
if (await IsConvertedCopyAsync(_storage, _copyShas, file.Sha256, ct).ConfigureAwait(false) is { } converted)
|
||||
{
|
||||
return new Comparison(ImportOutcome.AlreadyInLibrary, converted.MediaId, null, ImportText.NoteConvertedCopy);
|
||||
}
|
||||
|
||||
// 2. Same bytes earlier in the source.
|
||||
if (_sourceSha.TryGetValue(file.Sha256, out var twin) && twin.Id != file.Id)
|
||||
{
|
||||
@@ -177,6 +191,21 @@ internal sealed class ImportComparer
|
||||
return new Comparison(ImportOutcome.New, null, null, null);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Whether <paramref name="sha256"/> is the SHA-256 of a converted file of the library (with its original's media
|
||||
/// id) or of a converted copy or frame written in a destination (media id null); null when it is neither.
|
||||
/// </summary>
|
||||
internal static async Task<ConvertedCopyMatch?> IsConvertedCopyAsync(IFebeStorage storage, IReadOnlySet<string> copyShas, string sha256, CancellationToken ct)
|
||||
{
|
||||
var conversions = await storage.Conversions.FindBySha256Async(sha256, ct).ConfigureAwait(false);
|
||||
if (conversions.Count > 0)
|
||||
{
|
||||
return new ConvertedCopyMatch(conversions[0].MediaId);
|
||||
}
|
||||
|
||||
return copyShas.Contains(sha256) ? new ConvertedCopyMatch(null) : null;
|
||||
}
|
||||
|
||||
private async Task<Comparison?> MatchIdentityAsync(ImportFile file, FileHints hints, long? target, CancellationToken ct)
|
||||
{
|
||||
var candidates = new List<(EntryIdentity Entry, long? MediaId)>();
|
||||
|
||||
@@ -258,6 +258,14 @@ public sealed class ImportCopier(ImportEnvironment env)
|
||||
return await SaveAsync(file with { State = ImportFileState.Skipped, MatchedMediaId = twin.Media.Id, LastError = ImportText.NoteAlreadyInLibrary }).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
// A converted copy of a library file written since the analysis (tappa E3, Q37): never imported as a new file.
|
||||
context.CopyShas ??= await env.Storage.Exports.LoadConvertedCopyShasAsync(ct).ConfigureAwait(false);
|
||||
if (file.EntryId is null && await ImportComparer.IsConvertedCopyAsync(env.Storage, context.CopyShas, file.Sha256!, ct).ConfigureAwait(false) is { } converted)
|
||||
{
|
||||
tally.Skipped++;
|
||||
return await SaveAsync(file with { State = ImportFileState.Skipped, MatchedMediaId = converted.MediaId, LastError = ImportText.NoteConvertedCopy }).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
var account = await env.Storage.Accounts.GetAsync(file.TargetAccountId!.Value, ct).ConfigureAwait(false)
|
||||
?? throw new InvalidOperationException("L'account di destinazione non esiste più: associa di nuovo la cartella.");
|
||||
var hints = context.Recognizers.Recognize(new ImportFileContext(context.Layout, file.RelativePath));
|
||||
@@ -790,7 +798,11 @@ public sealed class ImportCopier(ImportEnvironment env)
|
||||
}
|
||||
}
|
||||
|
||||
private sealed record CopyContext(ImportRun Run, SourceLayout Layout, ImportRecognizers Recognizers, LibraryIngest Ingest);
|
||||
private sealed record CopyContext(ImportRun Run, SourceLayout Layout, ImportRecognizers Recognizers, LibraryIngest Ingest)
|
||||
{
|
||||
/// <summary>The SHA-256 of converted copies and frames in destinations, read once per run when first needed.</summary>
|
||||
public IReadOnlySet<string>? CopyShas { get; set; }
|
||||
}
|
||||
|
||||
private sealed class Tally
|
||||
{
|
||||
|
||||
@@ -139,6 +139,9 @@ public static class ImportText
|
||||
internal const string NoteLargerInSource = "Hai scelto di tenere il più grande: è un altro file della sorgente, che prende il posto di quello in libreria.";
|
||||
internal const string NoteNotRecognized = "Né foto né video: ignorato.";
|
||||
internal const string NoteAlreadyInLibrary = "Identico a un file già in libreria: saltato.";
|
||||
|
||||
/// <summary>A converted file of the library, a converted copy or a frame written in a destination (tappa E3, Q37).</summary>
|
||||
internal const string NoteConvertedCopy = "È una copia convertita (o un fotogramma) di un file già in libreria.";
|
||||
internal const string NoteReplaced = "Ha sostituito il file più piccolo della libreria, come hai scelto.";
|
||||
internal const string NoteChanged = "Il file è cambiato dopo l'analisi: non è stato copiato. Per prenderlo avvia una nuova importazione della cartella.";
|
||||
internal const string NoteNotVerified = "La copia in libreria non corrisponde all'originale: l'originale resta al suo posto. Controlla il disco della libreria.";
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
namespace Febe.Core.Library.Conversion;
|
||||
|
||||
/// <summary>
|
||||
/// One conversion at a time across the process (tappa E3, decision D16): a photo conversion holds a decoded picture
|
||||
/// and its encoder state (up to about a gigabyte for 40 megapixels), so the export and the library conversion take
|
||||
/// turns, each off the calling thread.
|
||||
/// </summary>
|
||||
public sealed class ConversionThrottle
|
||||
{
|
||||
private readonly SemaphoreSlim gate = new(1, 1);
|
||||
|
||||
/// <summary>The throttle every conversion of the process shares.</summary>
|
||||
public static ConversionThrottle Shared { get; } = new();
|
||||
|
||||
/// <summary>Runs <paramref name="work"/> on the thread pool once no other conversion runs.</summary>
|
||||
public async Task<T> RunAsync<T>(Func<CancellationToken, T> work, CancellationToken ct)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(work);
|
||||
await gate.WaitAsync(ct).ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
return await Task.Run(() => work(ct), ct).ConfigureAwait(false);
|
||||
}
|
||||
finally
|
||||
{
|
||||
gate.Release();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,242 @@
|
||||
using System.Globalization;
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Core.Export;
|
||||
using Febe.Core.Storage;
|
||||
|
||||
namespace Febe.Core.Library.Conversion;
|
||||
|
||||
/// <summary>What «Anche i N già in libreria» would queue: files and the bytes of their originals («circa», D17).</summary>
|
||||
public sealed record LibraryConversionPreview(int Files, long Bytes);
|
||||
|
||||
/// <summary>
|
||||
/// The queue of the conversion for the library (tappa E3, D15, WP2.2): what enters it and when. A new file enters after
|
||||
/// its line of <c>_febe.jsonl</c> (<see cref="LibraryIngest.AppendJournalAsync"/>); the files already in the library
|
||||
/// only when Alberto answers «Anche i N già in libreria» to the question asked when the conversion is turned on (Q29);
|
||||
/// a format turned off or changed empties its queue, the converted files stay where they are.
|
||||
/// </summary>
|
||||
public sealed class LibraryConversionQueue(IFebeStorage storage, IClock clock)
|
||||
{
|
||||
/// <summary>«In pausa» (<c>1</c>): the worker converts nothing until it is resumed.</summary>
|
||||
public const string PausedKey = "esportazione.libreria-sospesa";
|
||||
|
||||
/// <summary>
|
||||
/// Since when (Unix milliseconds) the library format of photos is the one set now: «Solo i nuovi» means the files
|
||||
/// stored in the library from then on (<see cref="Media.DownloadedAt"/>), the others only with «Anche i N».
|
||||
/// </summary>
|
||||
public const string PhotoSinceKey = "esportazione.libreria-formato-foto-dal";
|
||||
|
||||
/// <summary>As <see cref="PhotoSinceKey"/>, for videos.</summary>
|
||||
public const string VideoSinceKey = "esportazione.libreria-formato-video-dal";
|
||||
|
||||
private static readonly Lock SignalGate = new();
|
||||
private static TaskCompletionSource _signal = NewSignal();
|
||||
|
||||
/// <summary>The files «Anche i N già in libreria» would queue for the library formats of <paramref name="settings"/>.</summary>
|
||||
public Task<LibraryConversionPreview> PreviewExistingAsync(ExportSettings settings, CancellationToken ct = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(settings);
|
||||
return PreviewExistingAsync(LibraryConversionRules.FormatFor(MediaKind.Photo, settings), LibraryConversionRules.FormatFor(MediaKind.Video, settings), ct);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The files «Anche i N già in libreria» would queue in these formats, one per kind (null: that kind is not asked
|
||||
/// about, as when only the other one is being turned on).
|
||||
/// </summary>
|
||||
public async Task<LibraryConversionPreview> PreviewExistingAsync(ExportFormat? photo, ExportFormat? video, CancellationToken ct = default)
|
||||
{
|
||||
var (files, bytes) = await storage.Conversions.CountExistingAsync(photo, video, ct).ConfigureAwait(false);
|
||||
return new LibraryConversionPreview(files, bytes);
|
||||
}
|
||||
|
||||
/// <summary>«Anche i N già in libreria» for both library formats of <paramref name="settings"/>. Returns how many.</summary>
|
||||
public Task<int> EnqueueExistingAsync(ExportSettings settings, CancellationToken ct = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(settings);
|
||||
return EnqueueExistingAsync(LibraryConversionRules.FormatFor(MediaKind.Photo, settings), LibraryConversionRules.FormatFor(MediaKind.Video, settings), ct);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// «Anche i N già in libreria»: queues the present files that convert, in one statement per kind, only for the kinds
|
||||
/// given (null: that kind keeps what was answered for it, «Solo i nuovi» included). Returns how many.
|
||||
/// </summary>
|
||||
public async Task<int> EnqueueExistingAsync(ExportFormat? photo, ExportFormat? video, CancellationToken ct = default)
|
||||
{
|
||||
var added = await storage.Conversions.EnqueueExistingAsync(photo, video, clock.Now, ct).ConfigureAwait(false);
|
||||
if (added > 0)
|
||||
{
|
||||
Signal();
|
||||
}
|
||||
|
||||
return added;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Saves the settings <paramref name="after"/> (they were <paramref name="before"/>) with what a change of a library
|
||||
/// format brings, in one transaction: the format, since when it is set (<see cref="PhotoSinceKey"/>) and the
|
||||
/// emptied queue of the format it replaces. A request aborted, a crash or a file stored at that moment never sees
|
||||
/// the new format without its «dal» key, nor the old failures left behind (D17, Q29).
|
||||
/// Turning one on queues nothing here: the interface asks, then calls <see cref="EnqueueExistingAsync"/> only for
|
||||
/// «Anche i N già in libreria».
|
||||
/// </summary>
|
||||
public Task SaveSettingsAsync(ExportSettings before, ExportSettings after, CancellationToken ct = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(before);
|
||||
ArgumentNullException.ThrowIfNull(after);
|
||||
var values = after.Values();
|
||||
var (since, formats) = Changes(before, after);
|
||||
foreach (var (key, value) in since)
|
||||
{
|
||||
values[key] = value;
|
||||
}
|
||||
|
||||
return storage.Conversions.SaveSettingsAndDeleteQueuesAsync(values, formats, ct);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The settings were saved by another way: a library format turned off or changed loses its queue and its failures
|
||||
/// that «Riprova» would put back (its converted files and rows stay), and its «dal» key is set, in one transaction.
|
||||
/// <see cref="SaveSettingsAsync"/> stores the settings with them.
|
||||
/// </summary>
|
||||
public Task OnSettingsChangedAsync(ExportSettings before, ExportSettings after, CancellationToken ct = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(before);
|
||||
ArgumentNullException.ThrowIfNull(after);
|
||||
var (since, formats) = Changes(before, after);
|
||||
return since.Count == 0 ? Task.CompletedTask : storage.Conversions.SaveSettingsAndDeleteQueuesAsync(since, formats, ct);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// For each kind whose library format changes: its «dal» key (now, or removed when it goes back to «Originale») and
|
||||
/// the format replaced, whose queue goes.
|
||||
/// </summary>
|
||||
private (Dictionary<string, string?> Since, List<ExportFormat> Formats) Changes(ExportSettings before, ExportSettings after)
|
||||
{
|
||||
var since = new Dictionary<string, string?>(StringComparer.Ordinal);
|
||||
var formats = new List<ExportFormat>();
|
||||
foreach (var kind in new[] { MediaKind.Photo, MediaKind.Video })
|
||||
{
|
||||
var old = LibraryConversionRules.FormatFor(kind, before);
|
||||
var now = LibraryConversionRules.FormatFor(kind, after);
|
||||
if (old == now)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (old is { } format)
|
||||
{
|
||||
formats.Add(format);
|
||||
}
|
||||
|
||||
// The files of the library before now are «già in libreria»: only «Anche i N» queues them.
|
||||
since[SinceKey(kind)] = now is null ? null : clock.Now.ToUnixTimeMilliseconds().ToString(CultureInfo.InvariantCulture);
|
||||
}
|
||||
|
||||
return (since, formats);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// «Riprova»: the failed files of the library formats set now go back to the queue, except those that never convert
|
||||
/// (<c>AsIs*</c>). Returns how many.
|
||||
/// </summary>
|
||||
public async Task<int> RetryFailedAsync(CancellationToken ct = default)
|
||||
{
|
||||
var settings = await ExportSettings.LoadAsync(storage.Settings, ct).ConfigureAwait(false);
|
||||
var formats = new[] { MediaKind.Photo, MediaKind.Video }
|
||||
.Select(kind => LibraryConversionRules.FormatFor(kind, settings))
|
||||
.OfType<ExportFormat>()
|
||||
.ToList();
|
||||
var reset = await storage.Conversions.ResetFailedAsync(formats, clock.Now, ct).ConfigureAwait(false);
|
||||
if (reset > 0)
|
||||
{
|
||||
Signal();
|
||||
}
|
||||
|
||||
return reset;
|
||||
}
|
||||
|
||||
/// <summary>«In pausa» or not.</summary>
|
||||
public static async Task<bool> IsPausedAsync(ISettingsStore settings, CancellationToken ct = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(settings);
|
||||
return await settings.GetAsync(PausedKey, ct).ConfigureAwait(false) == "1";
|
||||
}
|
||||
|
||||
/// <summary>«Sospendi» / «Riprendi» the conversion for the library.</summary>
|
||||
public async Task SetPausedAsync(bool paused, CancellationToken ct = default)
|
||||
{
|
||||
await storage.Settings.SetAsync(PausedKey, paused ? "1" : "0", ct).ConfigureAwait(false);
|
||||
if (!paused)
|
||||
{
|
||||
Signal();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Queues the new files of an entry by the library formats set now, after its journal line (the hook of
|
||||
/// <see cref="LibraryIngest"/>): those stored in the library since the format was set (<see cref="PhotoSinceKey"/>),
|
||||
/// not the files an old entry already had when a late one arrives (they had their answer, «Solo i nuovi» included).
|
||||
/// Nothing when both formats are «Originale». Returns how many rows were added.
|
||||
/// </summary>
|
||||
public static async Task<int> EnqueueEntryAsync(IFebeStorage storage, IReadOnlyList<Media> media, DateTimeOffset at, CancellationToken ct)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(storage);
|
||||
ArgumentNullException.ThrowIfNull(media);
|
||||
// One read: the formats and their «dal» keys as one change stored them, never a format with an older key.
|
||||
var values = await storage.Settings.GetAllAsync(ct).ConfigureAwait(false);
|
||||
var settings = ExportSettings.From(values);
|
||||
if (!settings.ConvertsLibrary)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
var photoSince = Since(values, MediaKind.Photo);
|
||||
var videoSince = Since(values, MediaKind.Video);
|
||||
var requests = LibraryConversionRules.RequestsFor(
|
||||
media.Where(m => (m.Kind == MediaKind.Video ? videoSince : photoSince) is not { } since
|
||||
|| (m.DownloadedAt is { } stored && stored.ToUnixTimeMilliseconds() >= since)),
|
||||
settings);
|
||||
if (requests.Count == 0)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
var added = await storage.Conversions.EnqueueAsync(requests, at, ct).ConfigureAwait(false);
|
||||
if (added > 0)
|
||||
{
|
||||
Signal();
|
||||
}
|
||||
|
||||
return added;
|
||||
}
|
||||
|
||||
private static string SinceKey(MediaKind kind) => kind == MediaKind.Video ? VideoSinceKey : PhotoSinceKey;
|
||||
|
||||
/// <summary>Since when the library format of this kind is set (Unix ms); null: not recorded, every file is new.</summary>
|
||||
private static long? Since(IReadOnlyDictionary<string, string> values, MediaKind kind) =>
|
||||
long.TryParse(values.GetValueOrDefault(SinceKey(kind)), NumberStyles.Integer, CultureInfo.InvariantCulture, out var ms) ? ms : null;
|
||||
|
||||
/// <summary>Wakes the worker: something entered the queue (or the pause ended).</summary>
|
||||
public static void Signal()
|
||||
{
|
||||
TaskCompletionSource fired;
|
||||
lock (SignalGate)
|
||||
{
|
||||
fired = _signal;
|
||||
_signal = NewSignal();
|
||||
}
|
||||
|
||||
fired.TrySetResult();
|
||||
}
|
||||
|
||||
/// <summary>A task that completes at the next <see cref="Signal"/>.</summary>
|
||||
internal static Task NextSignal()
|
||||
{
|
||||
lock (SignalGate)
|
||||
{
|
||||
return _signal.Task;
|
||||
}
|
||||
}
|
||||
|
||||
private static TaskCompletionSource NewSignal() => new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Core.Export;
|
||||
using Febe.Core.Storage;
|
||||
|
||||
namespace Febe.Core.Library.Conversion;
|
||||
|
||||
/// <summary>
|
||||
/// Which library files the conversion for the library queues (tappa E3, D15, WP2.2): a present file whose extension
|
||||
/// says it converts into the format chosen for its kind (<see cref="ExportConversions.Predict"/> is Converted). A file
|
||||
/// already in that format, HEIC, HEIF, AVIF, raw, GIF and WebM are never queued. The same rule is written in SQL by the
|
||||
/// store (<see cref="ExcludedExtensions"/>).
|
||||
/// </summary>
|
||||
public static class LibraryConversionRules
|
||||
{
|
||||
/// <summary>The format of the conversion for the library of a kind; null when it is off («Originale»).</summary>
|
||||
public static ExportFormat? FormatFor(MediaKind kind, ExportSettings settings)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(settings);
|
||||
var format = kind == MediaKind.Photo ? settings.LibraryPhotoFormat : settings.LibraryVideoFormat;
|
||||
var fits = kind == MediaKind.Photo ? ExportFormats.IsPhotoFormat(format) : ExportFormats.IsVideoFormat(format);
|
||||
return format != ExportFormat.Original && fits ? format : null;
|
||||
}
|
||||
|
||||
/// <summary>True when a file at <paramref name="relativePath"/> of <paramref name="kind"/> is queued for <paramref name="format"/>.</summary>
|
||||
public static bool Converts(string relativePath, MediaKind kind, ExportFormat format)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(relativePath);
|
||||
var fits = kind == MediaKind.Photo ? ExportFormats.IsPhotoFormat(format) : ExportFormats.IsVideoFormat(format);
|
||||
return format != ExportFormat.Original && fits && ExportConversions.Predict(relativePath, kind, format) == ExportPrediction.Converted;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The extensions (with their dot, lower case) of the files that are not queued for <paramref name="format"/>: the
|
||||
/// format's own and the ones copied as they are. Equivalent to <see cref="Converts"/> on the extension.
|
||||
/// </summary>
|
||||
public static IReadOnlyList<string> ExcludedExtensions(ExportFormat format)
|
||||
{
|
||||
var own = format switch
|
||||
{
|
||||
ExportFormat.Jpg => new[] { ".jpg", ".jpeg" },
|
||||
ExportFormat.Png => [".png"],
|
||||
ExportFormat.WebpLossless => [".webp"],
|
||||
ExportFormat.Mp4 => [".mp4"],
|
||||
_ => throw new ArgumentOutOfRangeException(nameof(format), "La conversione della libreria ha un formato diverso dall'originale."),
|
||||
};
|
||||
return [.. own, ".heic", ".heif", ".avif", ".gif", ".webm", .. MediaConverter.RawExtensionList.Select(e => e.ToLowerInvariant()).Order(StringComparer.Ordinal)];
|
||||
}
|
||||
|
||||
/// <summary>The conversions to queue for the present files of an entry, by the settings now.</summary>
|
||||
public static IReadOnlyList<MediaConversionRequest> RequestsFor(IEnumerable<Media> media, ExportSettings settings)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(media);
|
||||
ArgumentNullException.ThrowIfNull(settings);
|
||||
var list = new List<MediaConversionRequest>();
|
||||
foreach (var m in media)
|
||||
{
|
||||
if (EntryStateRules.IsPresent(m.State) && m.Sha256 is { Length: 64 } sha && m.RelativePath is { } path
|
||||
&& FormatFor(m.Kind, settings) is { } format && Converts(path, m.Kind, format))
|
||||
{
|
||||
list.Add(new MediaConversionRequest(m.Id, format, sha));
|
||||
}
|
||||
}
|
||||
|
||||
return list;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
using Febe.Core.Codecs.Images;
|
||||
using Febe.Core.Export;
|
||||
|
||||
namespace Febe.Core.Library.Conversion;
|
||||
|
||||
/// <summary>
|
||||
/// The codes of <c>media_conversion.last_error</c> (tappa E3, D19) and their Italian texts. A Failed row carries why it
|
||||
/// failed (an <c>AsIs*</c> code first when the file never converts); a Converted row carries what was not kept.
|
||||
/// </summary>
|
||||
public static class LibraryConversionText
|
||||
{
|
||||
/// <summary>The original is not in the library folder.</summary>
|
||||
public const string SourceMissing = ExportText.Notes.SourceMissing;
|
||||
|
||||
/// <summary>The original's bytes are not the ones recorded.</summary>
|
||||
public const string SourceChanged = ExportText.Notes.SourceChanged;
|
||||
|
||||
/// <summary>The account folder is not there (an unplugged disk): it is never created.</summary>
|
||||
public const string AccountFolderMissing = "AccountFolderMissing";
|
||||
|
||||
/// <summary>The prefix of an unexpected failure; the exception's type name follows the colon.</summary>
|
||||
public const string Error = "Error";
|
||||
|
||||
/// <summary>The prefix of the codes of files that never convert.</summary>
|
||||
public const string AsIsPrefix = "AsIs";
|
||||
|
||||
/// <summary>«In pausa» for low space (D17).</summary>
|
||||
public const string LowSpace = "Spazio libero sotto la soglia: la conversione della libreria è in pausa";
|
||||
|
||||
/// <summary>Waiting for the end of an engine session.</summary>
|
||||
public const string InSession = "Il motore è in sessione: la conversione della libreria riprende dopo";
|
||||
|
||||
/// <summary>Waiting for an import, a copy or a rebuild.</summary>
|
||||
public const string LongWork = "Un'importazione, una copia o una ricostruzione è al lavoro: la conversione della libreria riprende dopo";
|
||||
|
||||
/// <summary>True when the codes of a Failed row say the file never converts.</summary>
|
||||
public static bool IsAsIs(string? codes) => codes is not null && codes.TrimStart().StartsWith(AsIsPrefix, StringComparison.Ordinal);
|
||||
|
||||
/// <summary>The Italian text of a list of codes («·» between them); unknown codes are shown as they are.</summary>
|
||||
public static string? Note(string? codes)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(codes))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return string.Join(" · ", codes.Split(' ', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries).Select(One));
|
||||
}
|
||||
|
||||
private static string One(string code)
|
||||
{
|
||||
var colon = code.IndexOf(':', StringComparison.Ordinal);
|
||||
var name = colon < 0 ? code : code[..colon];
|
||||
return name switch
|
||||
{
|
||||
SourceMissing => "File non presente in libreria",
|
||||
SourceChanged => "Il file della libreria non è quello registrato",
|
||||
AccountFolderMissing => "La cartella dell'account non c'è: ricollega il disco e riprova",
|
||||
Error => "Conversione non riuscita: riprova",
|
||||
ImageConversionLosses.AsIsHeif => "Non si converte: HEIC",
|
||||
ImageConversionLosses.AsIsAvif => "Non si converte: AVIF",
|
||||
ImageConversionLosses.AsIsRaw => "Non si converte: raw",
|
||||
ImageConversionLosses.AsIsAnimated => "Non si converte: immagine animata (perderebbe i fotogrammi dopo il primo)",
|
||||
ImageConversionLosses.AsIsNotDecodable => "Non si converte: Febe non riesce a leggere l'immagine",
|
||||
ImageConversionLosses.AsIsDeepColor => "Non si converte: più di 8 bit per colore",
|
||||
ImageConversionLosses.AsIsCmyk => "Non si converte: immagine CMYK",
|
||||
ImageConversionLosses.AsIsTooLarge => "Non si converte: troppo grande per il formato scelto",
|
||||
MediaConversionResult.AsIsNotRemuxable => "Non si porta in MP4 senza ricodificarlo" + (ExportText.Note(code) is { } t && t.IndexOf('(', StringComparison.Ordinal) is var i and >= 0 ? " " + t[i..] : string.Empty),
|
||||
_ => ExportText.Note(code) ?? code,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,560 @@
|
||||
using System.Security.Cryptography;
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Alerts;
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Core.Export;
|
||||
using Febe.Core.Storage;
|
||||
|
||||
namespace Febe.Core.Library.Conversion;
|
||||
|
||||
/// <summary>What the conversion for the library needs from the rest of Febe (tappa E3, WP2.2).</summary>
|
||||
public sealed record LibraryConversionEnvironment
|
||||
{
|
||||
public required IFebeStorage Storage { get; init; }
|
||||
|
||||
/// <summary>The library folder and account folders now (on Windows it can change while Febe runs).</summary>
|
||||
public required Func<LibraryLayout> Layout { get; init; }
|
||||
|
||||
public required IClock Clock { get; init; }
|
||||
|
||||
/// <summary>Shared with import, export, rebuild and frame download, which pre-empt the conversion. Null: nothing to yield to (tests).</summary>
|
||||
public LongWorkGate? Gate { get; init; }
|
||||
|
||||
/// <summary>The conversion never runs during an engine session.</summary>
|
||||
public IEngineSessionState Session { get; init; } = NoEngineSession.Instance;
|
||||
|
||||
/// <summary>One conversion at a time in the process (D16): shared with the copies to external folders.</summary>
|
||||
public ConversionThrottle Throttle { get; init; } = ConversionThrottle.Shared;
|
||||
|
||||
/// <summary>The free space of the disk of an account folder.</summary>
|
||||
public IFreeSpaceProbe FreeSpace { get; init; } = new DriveFreeSpaceProbe();
|
||||
|
||||
/// <summary>Below this, once the file is written, the conversion pauses (D17): the alerts' «quasi pieno».</summary>
|
||||
public DiskThresholds Thresholds { get; init; } = DiskThresholds.Default;
|
||||
|
||||
/// <summary>How long the worker sleeps when nothing wakes it.</summary>
|
||||
public TimeSpan Idle { get; init; } = TimeSpan.FromSeconds(30);
|
||||
|
||||
/// <summary>How often it looks again while it waits for an engine session or a long work to end.</summary>
|
||||
public TimeSpan Poll { get; init; } = TimeSpan.FromSeconds(5);
|
||||
|
||||
/// <summary>Rows read from the queue at a time.</summary>
|
||||
public int BatchSize { get; init; } = 50;
|
||||
|
||||
/// <summary>One line for the log: only Italian text and exception type names, never paths or messages.</summary>
|
||||
public Action<string>? Log { get; init; }
|
||||
|
||||
/// <summary>Test seam: runs once the converted file is on disk, before its record.</summary>
|
||||
public Func<MediaConversion, CancellationToken, Task>? AfterWrite { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>The conversion for the library as the interface shows it.</summary>
|
||||
/// <param name="Pending">Files in the queue.</param>
|
||||
/// <param name="Converted">Files converted.</param>
|
||||
/// <param name="Failed">Files that failed and can be tried again («Riprova»).</param>
|
||||
/// <param name="AsIs">Files that never convert («non si convertono»).</param>
|
||||
/// <param name="Paused">«In pausa» by Alberto.</param>
|
||||
/// <param name="Waiting">Why it waits now (an engine session, a long work, low space), or null.</param>
|
||||
/// <param name="CurrentMediaId">The library file being converted now, or null.</param>
|
||||
public sealed record LibraryConversionStatus(int Pending, int Converted, int Failed, int AsIs, bool Paused, string? Waiting, long? CurrentMediaId);
|
||||
|
||||
/// <summary>What one pass over the queue did.</summary>
|
||||
/// <param name="Converted">Files converted (or adopted).</param>
|
||||
/// <param name="Done">Rows settled: converted, dropped (already in the format), failed.</param>
|
||||
/// <param name="Again">True when the pass stopped early and should look again soon (session, long work, pre-emption).</param>
|
||||
public sealed record LibraryConversionPass(int Converted, int Done, bool Again);
|
||||
|
||||
/// <summary>
|
||||
/// The conversion for the library (tappa E3, spec §4.10, D15-D18): adds, next to an original, the same file in the
|
||||
/// format chosen for its kind, as a new file with the same stem and a free name. The original, its record, its
|
||||
/// thumbnail, perceptual hash and journal line stay as they are; the converted file is only a <c>media_conversion</c>
|
||||
/// row. It runs in the background through <see cref="RunAsync"/> (started by the composition, never in the demo),
|
||||
/// yields to import, export, rebuild and frame download (<see cref="LongWorkGate.BackgroundLease"/>), never runs during
|
||||
/// an engine session and pauses when the disk is almost full.
|
||||
/// </summary>
|
||||
public sealed class LibraryConversionWorker(LibraryConversionEnvironment env)
|
||||
{
|
||||
private readonly LibraryConversionEnvironment _env = env ?? throw new ArgumentNullException(nameof(env));
|
||||
private volatile string? _waiting;
|
||||
private long _current;
|
||||
|
||||
/// <summary>
|
||||
/// The file that last paused the conversion for space, with the length its converted file needs: until the disk
|
||||
/// has room for that too, the original is not read (hashed, decoded or remuxed) again at every wake-up (D17).
|
||||
/// </summary>
|
||||
private volatile LowSpaceMark? _lowSpace;
|
||||
|
||||
private sealed record LowSpaceMark(long RowId, string SourceSha256, long Needed);
|
||||
|
||||
/// <summary>The counts of the store with what the worker is doing now.</summary>
|
||||
public async Task<LibraryConversionStatus> StatusAsync(CancellationToken ct = default)
|
||||
{
|
||||
var counts = await _env.Storage.Conversions.CountByStateAsync(ct).ConfigureAwait(false);
|
||||
var paused = await LibraryConversionQueue.IsPausedAsync(_env.Storage.Settings, ct).ConfigureAwait(false);
|
||||
var current = Interlocked.Read(ref _current);
|
||||
return new LibraryConversionStatus(counts.Pending, counts.Converted, counts.Failed, counts.AsIs, paused, paused ? null : _waiting, current == 0 ? null : current);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The loop: a pass over the queue, then a wait for <see cref="LibraryConversionQueue.Signal"/> or
|
||||
/// <see cref="LibraryConversionEnvironment.Idle"/>. A failure of a pass is logged by type and the loop goes on; it
|
||||
/// ends with <paramref name="ct"/>.
|
||||
/// </summary>
|
||||
public async Task RunAsync(CancellationToken ct)
|
||||
{
|
||||
while (!ct.IsCancellationRequested)
|
||||
{
|
||||
var wait = _env.Idle;
|
||||
try
|
||||
{
|
||||
var pass = await RunOnceAsync(ct).ConfigureAwait(false);
|
||||
if (pass.Again)
|
||||
{
|
||||
wait = _env.Poll;
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException) when (ct.IsCancellationRequested)
|
||||
{
|
||||
return;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_env.Log?.Invoke($"La conversione della libreria si è fermata per un errore ({ex.GetType().Name}): riprova fra poco.");
|
||||
}
|
||||
|
||||
using var stop = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
||||
var signal = LibraryConversionQueue.NextSignal();
|
||||
var delay = _env.Clock.Delay(wait, stop.Token);
|
||||
await Task.WhenAny(signal, delay).ConfigureAwait(false);
|
||||
await stop.CancelAsync().ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>One pass over the queue, in order, until it is empty or something stops it.</summary>
|
||||
public async Task<LibraryConversionPass> RunOnceAsync(CancellationToken ct = default)
|
||||
{
|
||||
var storage = _env.Storage;
|
||||
if (await LibraryConversionQueue.IsPausedAsync(storage.Settings, ct).ConfigureAwait(false))
|
||||
{
|
||||
_waiting = null;
|
||||
return new LibraryConversionPass(0, 0, false);
|
||||
}
|
||||
|
||||
if (_env.Session.InSession)
|
||||
{
|
||||
_waiting = LibraryConversionText.InSession;
|
||||
return new LibraryConversionPass(0, 0, true);
|
||||
}
|
||||
|
||||
if ((await storage.Conversions.ListPendingAsync(0, 1, ct).ConfigureAwait(false)).Count == 0)
|
||||
{
|
||||
_waiting = null;
|
||||
return new LibraryConversionPass(0, 0, false);
|
||||
}
|
||||
|
||||
LongWorkGate.BackgroundLease? lease = null;
|
||||
if (_env.Gate is { } gate && !gate.TryEnterBackground(out lease))
|
||||
{
|
||||
_waiting = LibraryConversionText.LongWork;
|
||||
return new LibraryConversionPass(0, 0, true);
|
||||
}
|
||||
|
||||
using (lease)
|
||||
{
|
||||
using var linked = CancellationTokenSource.CreateLinkedTokenSource(ct, lease?.Preempted ?? CancellationToken.None);
|
||||
var token = linked.Token;
|
||||
_waiting = null;
|
||||
var converted = 0;
|
||||
var done = 0;
|
||||
var after = 0L;
|
||||
while (true)
|
||||
{
|
||||
var rows = await storage.Conversions.ListPendingAsync(after, _env.BatchSize, ct).ConfigureAwait(false);
|
||||
if (rows.Count == 0)
|
||||
{
|
||||
return new LibraryConversionPass(converted, done, false);
|
||||
}
|
||||
|
||||
foreach (var row in rows)
|
||||
{
|
||||
after = row.Id;
|
||||
if (token.IsCancellationRequested || _env.Session.InSession
|
||||
|| await LibraryConversionQueue.IsPausedAsync(storage.Settings, ct).ConfigureAwait(false))
|
||||
{
|
||||
ct.ThrowIfCancellationRequested();
|
||||
return new LibraryConversionPass(converted, done, true);
|
||||
}
|
||||
|
||||
var outcome = await ConvertOneAsync(row, lease, token, ct).ConfigureAwait(false);
|
||||
switch (outcome)
|
||||
{
|
||||
case Outcome.Converted:
|
||||
converted++;
|
||||
done++;
|
||||
break;
|
||||
case Outcome.Settled:
|
||||
done++;
|
||||
break;
|
||||
case Outcome.LowSpace:
|
||||
_waiting = LibraryConversionText.LowSpace;
|
||||
return new LibraryConversionPass(converted, done, false);
|
||||
case Outcome.Stopped:
|
||||
ct.ThrowIfCancellationRequested();
|
||||
return new LibraryConversionPass(converted, done, true);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private enum Outcome
|
||||
{
|
||||
Converted,
|
||||
Settled,
|
||||
Skipped,
|
||||
LowSpace,
|
||||
Stopped,
|
||||
}
|
||||
|
||||
private async Task<Outcome> ConvertOneAsync(MediaConversion row, LongWorkGate.BackgroundLease? lease, CancellationToken token, CancellationToken ct)
|
||||
{
|
||||
Interlocked.Exchange(ref _current, row.MediaId);
|
||||
try
|
||||
{
|
||||
return await ConvertAsync(row, lease, token).ConfigureAwait(false);
|
||||
}
|
||||
catch (OperationCanceledException) when (token.IsCancellationRequested)
|
||||
{
|
||||
// Pre-empted, or Febe stops: our temporary file is gone, the row stays in the queue.
|
||||
return Outcome.Stopped;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
// One file never stops the queue: the reason goes to the row (codes, D19), the log gets the type only.
|
||||
_env.Log?.Invoke($"Un file non si è convertito per la libreria ({ex.GetType().Name}).");
|
||||
await FailAsync(row, $"{LibraryConversionText.Error}:{ex.GetType().Name}").ConfigureAwait(false);
|
||||
ct.ThrowIfCancellationRequested();
|
||||
return Outcome.Settled;
|
||||
}
|
||||
finally
|
||||
{
|
||||
Interlocked.Exchange(ref _current, 0);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<Outcome> ConvertAsync(MediaConversion row, LongWorkGate.BackgroundLease? lease, CancellationToken token)
|
||||
{
|
||||
var storage = _env.Storage;
|
||||
var media = await storage.Media.GetAsync(row.MediaId, token).ConfigureAwait(false);
|
||||
if (media is null || !EntryStateRules.IsPresent(media.State) || media.RelativePath is null || media.Sha256 is not { Length: 64 })
|
||||
{
|
||||
// Not in the library (deleted meanwhile, or never stored): nothing to convert.
|
||||
await storage.Conversions.DeletePendingRowAsync(row.Id, CancellationToken.None).ConfigureAwait(false);
|
||||
return Outcome.Skipped;
|
||||
}
|
||||
|
||||
// Only in the library format set now (§4.10, Q29): a row left in a format turned off or changed (put back by a
|
||||
// supersession, say) is dropped, never converted.
|
||||
var settings = await ExportSettings.LoadAsync(storage.Settings, token).ConfigureAwait(false);
|
||||
if (LibraryConversionRules.FormatFor(media.Kind, settings) != row.Format)
|
||||
{
|
||||
await storage.Conversions.DeletePendingRowAsync(row.Id, CancellationToken.None).ConfigureAwait(false);
|
||||
return Outcome.Skipped;
|
||||
}
|
||||
|
||||
var entry = await storage.Entries.GetAsync(media.EntryId, token).ConfigureAwait(false);
|
||||
var account = entry is null ? null : await storage.Accounts.GetAsync(entry.AccountId, token).ConfigureAwait(false);
|
||||
if (entry is null || account is null)
|
||||
{
|
||||
await storage.Conversions.DeletePendingRowAsync(row.Id, CancellationToken.None).ConfigureAwait(false);
|
||||
return Outcome.Skipped;
|
||||
}
|
||||
|
||||
var layout = _env.Layout();
|
||||
var folder = layout.AccountFolder(account);
|
||||
if (!Directory.Exists(folder))
|
||||
{
|
||||
// An unplugged disk of an account folder outside the library: never created again here.
|
||||
await FailAsync(row, LibraryConversionText.AccountFolderMissing).ConfigureAwait(false);
|
||||
return Outcome.Settled;
|
||||
}
|
||||
|
||||
var original = LibraryLayout.FullPath(folder, media.RelativePath);
|
||||
if (!File.Exists(original))
|
||||
{
|
||||
await FailAsync(row, LibraryConversionText.SourceMissing).ConfigureAwait(false);
|
||||
return Outcome.Settled;
|
||||
}
|
||||
|
||||
// A disk already below the threshold stays below it with the file, and the file that paused the conversion last
|
||||
// needs as much again: the pause holds before the original is read (hashed, decoded or remuxed) again at every
|
||||
// wake-up (D17). The exact check with the file's length follows.
|
||||
var source = media.Sha256.ToLowerInvariant();
|
||||
var needed = _lowSpace is { } mark && mark.RowId == row.Id && string.Equals(mark.SourceSha256, source, StringComparison.Ordinal) ? mark.Needed : 0;
|
||||
if (_env.FreeSpace.Measure(folder) is { } before && _env.Thresholds.IsLow(before with { AvailableBytes = before.AvailableBytes - needed }))
|
||||
{
|
||||
return Outcome.LowSpace;
|
||||
}
|
||||
|
||||
if (!string.Equals(row.SourceSha256, source, StringComparison.Ordinal))
|
||||
{
|
||||
row = row with { SourceSha256 = source, StateChangedAt = _env.Clock.Now };
|
||||
await storage.Conversions.UpdateAsync(row, CancellationToken.None).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
if (media.Kind == MediaKind.Video && !string.Equals(await HashAsync(original, token).ConfigureAwait(false), source, StringComparison.Ordinal))
|
||||
{
|
||||
// A remux reads the file in pieces: its bytes are checked first (a photo is checked by the converter).
|
||||
await FailAsync(row, LibraryConversionText.SourceChanged).ConfigureAwait(false);
|
||||
return Outcome.Settled;
|
||||
}
|
||||
|
||||
MediaConversionResult result;
|
||||
try
|
||||
{
|
||||
result = await MediaConverter.PrepareAsync(() => OpenRead(original), media.RelativePath, media.Kind, row.Format, source, _env.Throttle, token)
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
catch (ContentChangedException)
|
||||
{
|
||||
await FailAsync(row, LibraryConversionText.SourceChanged).ConfigureAwait(false);
|
||||
return Outcome.Settled;
|
||||
}
|
||||
|
||||
using (result)
|
||||
{
|
||||
if (result.Variant == ExportVariant.Whole)
|
||||
{
|
||||
if (result.Notes.Count == 0)
|
||||
{
|
||||
// Already in the format by its bytes (a «.png» that is a JPEG, to JPG): there is no file to add.
|
||||
await storage.Conversions.DeletePendingRowAsync(row.Id, CancellationToken.None).ConfigureAwait(false);
|
||||
}
|
||||
else
|
||||
{
|
||||
// Animated, not decodable, CMYK, too large, not remuxable…: it never converts (terminal).
|
||||
await FailAsync(row, ExportText.JoinNotes(result.Notes)).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
return Outcome.Settled;
|
||||
}
|
||||
|
||||
if (_env.FreeSpace.Measure(folder) is { } space
|
||||
&& _env.Thresholds.IsLow(space with { AvailableBytes = space.AvailableBytes - result.Length }))
|
||||
{
|
||||
_lowSpace = new LowSpaceMark(row.Id, source, result.Length);
|
||||
return Outcome.LowSpace;
|
||||
}
|
||||
|
||||
_lowSpace = null;
|
||||
return await WriteAsync(row, media, entry, account, folder, layout, result, lease, token).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<Outcome> WriteAsync(MediaConversion row, Media media, Entry entry, Account account, string folder, LibraryLayout layout,
|
||||
MediaConversionResult result, LongWorkGate.BackgroundLease? lease, CancellationToken token)
|
||||
{
|
||||
var storage = _env.Storage;
|
||||
var relative = LibraryLayout.ToStored(media.RelativePath!);
|
||||
var slash = relative.LastIndexOf('/');
|
||||
var directory = slash < 0 ? string.Empty : relative[..slash];
|
||||
var stem = WindowsFileNames.SplitExtension(relative[(slash + 1)..]).Stem;
|
||||
var setTime = await SetFileTimeAsync(token).ConfigureAwait(false);
|
||||
|
||||
FileDigest written = default;
|
||||
string? adopted = null;
|
||||
var preempted = false;
|
||||
IDisposable? commit = null;
|
||||
try
|
||||
{
|
||||
var writer = new SafeFileWriter(layout.MaxPathLength);
|
||||
var saved = await writer.SaveAsync(
|
||||
result.Produce,
|
||||
folder,
|
||||
directory,
|
||||
async (digest, t) =>
|
||||
{
|
||||
written = digest;
|
||||
adopted = await FindAdoptableAsync(account, folder, layout, directory, stem, result.Extension, digest, t).ConfigureAwait(false);
|
||||
if (lease is not null && !lease.TryBeginCommit(out commit))
|
||||
{
|
||||
preempted = true;
|
||||
return null;
|
||||
}
|
||||
|
||||
return adopted is null ? Join(directory, stem + result.Extension) : null;
|
||||
},
|
||||
new SafeWriteOptions
|
||||
{
|
||||
RequireExistingRoot = true,
|
||||
VerifyFromDisk = true,
|
||||
LastWriteTime = setTime ? entry.PublishedAt : null,
|
||||
},
|
||||
token).ConfigureAwait(false);
|
||||
if (preempted)
|
||||
{
|
||||
return Outcome.Stopped;
|
||||
}
|
||||
|
||||
var path = adopted ?? saved!.RelativePath;
|
||||
if (_env.AfterWrite is { } after)
|
||||
{
|
||||
await after(row, CancellationToken.None).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
MediaConversionCommitOutcome outcome;
|
||||
try
|
||||
{
|
||||
outcome = await storage.Conversions.CommitAsync(
|
||||
new MediaConversionCommit(row.Id, media.Id, row.Format, row.SourceSha256, path, written.Bytes, written.Sha256, _env.Clock.Now,
|
||||
ExportText.JoinNotes(result.Notes)),
|
||||
CancellationToken.None).ConfigureAwait(false);
|
||||
}
|
||||
catch when (adopted is null)
|
||||
{
|
||||
DiscardOwn(folder, path, written.Sha256);
|
||||
throw;
|
||||
}
|
||||
|
||||
if (outcome is MediaConversionCommitOutcome.Recorded or MediaConversionCommitOutcome.Upserted)
|
||||
{
|
||||
return Outcome.Converted;
|
||||
}
|
||||
|
||||
if (adopted is null)
|
||||
{
|
||||
// The entry was deleted (or the original replaced) while the file was written: the file just written
|
||||
// belongs to nothing. It is this operation's own file, never one of the library: it goes.
|
||||
DiscardOwn(folder, path, written.Sha256);
|
||||
}
|
||||
|
||||
return Outcome.Settled;
|
||||
}
|
||||
finally
|
||||
{
|
||||
commit?.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A file already at the path (or at one of its free names) with the conversion's SHA-256 that no library file and
|
||||
/// no other conversion records: a conversion of an earlier run (or of a lost database) whose record is missing. Null
|
||||
/// when there is none: the file is written with the next free name. Never by size alone (D10).
|
||||
/// </summary>
|
||||
private async Task<string?> FindAdoptableAsync(Account account, string folder, LibraryLayout layout, string directory, string stem, string extension,
|
||||
FileDigest digest, CancellationToken ct)
|
||||
{
|
||||
for (var attempt = 1; attempt <= 50; attempt++)
|
||||
{
|
||||
var name = attempt == 1 ? stem + extension : string.Create(System.Globalization.CultureInfo.InvariantCulture, $"{stem} ({attempt}){extension}");
|
||||
var segments = Join(directory, WindowsFileNames.SanitizeSegment(name)).Split('/', StringSplitOptions.RemoveEmptyEntries);
|
||||
var relative = string.Join('/', WindowsFileNames.FitPath(folder, segments, layout.MaxPathLength));
|
||||
string full;
|
||||
try
|
||||
{
|
||||
full = LibraryLayout.FullPath(folder, relative);
|
||||
}
|
||||
catch (ArgumentException)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var info = new FileInfo(full);
|
||||
if (!info.Exists)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
if (info.Length == digest.Bytes
|
||||
&& string.Equals(await HashAsync(full, ct).ConfigureAwait(false), digest.Sha256, StringComparison.Ordinal)
|
||||
&& !await IsRecordedAsync(account, relative, digest.Sha256, ct).ConfigureAwait(false))
|
||||
{
|
||||
return relative;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>A library file of the account, or a live conversion of one, records this path (another entry's «x.jpg»).</summary>
|
||||
private async Task<bool> IsRecordedAsync(Account account, string relative, string sha, CancellationToken ct)
|
||||
{
|
||||
var comparison = OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal;
|
||||
var media = await _env.Storage.Media.FindBySha256Async(sha, ct).ConfigureAwait(false);
|
||||
if (media.Any(m => m.Entry.AccountId == account.Id && m.Media.RelativePath is { } p && string.Equals(LibraryLayout.ToStored(p), relative, comparison)))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
foreach (var conversion in await _env.Storage.Conversions.FindBySha256Async(sha, ct).ConfigureAwait(false))
|
||||
{
|
||||
if (conversion.State is MediaConversionState.Converted or MediaConversionState.Superseded
|
||||
&& conversion.RelativePath is { } path && string.Equals(path, relative, comparison))
|
||||
{
|
||||
var owner = await _env.Storage.Media.GetAsync(conversion.MediaId, ct).ConfigureAwait(false);
|
||||
var entry = owner is null ? null : await _env.Storage.Entries.GetAsync(owner.EntryId, ct).ConfigureAwait(false);
|
||||
if (entry?.AccountId == account.Id)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>Deletes the file this conversion just wrote, only if it still has the bytes written (precedent: LibraryIngest).</summary>
|
||||
private void DiscardOwn(string folder, string relative, string sha)
|
||||
{
|
||||
try
|
||||
{
|
||||
var full = LibraryLayout.FullPath(folder, relative);
|
||||
if (File.Exists(full) && string.Equals(HashFile(full), sha, StringComparison.Ordinal))
|
||||
{
|
||||
File.Delete(full);
|
||||
}
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException)
|
||||
{
|
||||
_env.Log?.Invoke($"Un file convertito per un elemento eliminato non si è potuto togliere ({ex.GetType().Name}).");
|
||||
}
|
||||
}
|
||||
|
||||
private async Task FailAsync(MediaConversion row, string? codes)
|
||||
{
|
||||
try
|
||||
{
|
||||
await _env.Storage.Conversions.UpdateAsync(
|
||||
row with { State = MediaConversionState.Failed, LastError = codes, StateChangedAt = _env.Clock.Now, RelativePath = null, Bytes = null, Sha256 = null, ConvertedAt = null },
|
||||
CancellationToken.None).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex) when (ex is KeyNotFoundException or DuplicateRecordException)
|
||||
{
|
||||
// The row went or changed meanwhile (a deletion, the setting turned off): nothing to record.
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<bool> SetFileTimeAsync(CancellationToken ct)
|
||||
{
|
||||
var text = await _env.Storage.Settings.GetAsync(SettingKeys.SetFileTimeToPublication, ct).ConfigureAwait(false);
|
||||
return text is null || !bool.TryParse(text, out var parsed) || parsed;
|
||||
}
|
||||
|
||||
private static string Join(string directory, string name) => directory.Length == 0 ? name : directory + "/" + name;
|
||||
|
||||
private static FileStream OpenRead(string path) =>
|
||||
new(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete, 128 * 1024, FileOptions.RandomAccess);
|
||||
|
||||
private static async Task<string> HashAsync(string path, CancellationToken ct)
|
||||
{
|
||||
await using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete, 128 * 1024,
|
||||
FileOptions.Asynchronous | FileOptions.SequentialScan);
|
||||
return Convert.ToHexStringLower(await SHA256.HashDataAsync(stream, ct).ConfigureAwait(false));
|
||||
}
|
||||
|
||||
private static string HashFile(string path)
|
||||
{
|
||||
using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete, 128 * 1024, FileOptions.SequentialScan);
|
||||
return Convert.ToHexStringLower(SHA256.HashData(stream));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,220 @@
|
||||
using System.Security.Cryptography;
|
||||
using Febe.Core.Codecs.Containers;
|
||||
using Febe.Core.Codecs.Images;
|
||||
using Febe.Core.Domain;
|
||||
|
||||
namespace Febe.Core.Library.Conversion;
|
||||
|
||||
/// <summary>
|
||||
/// A library file ready to be written in a format (tappa E3, spec §4.10 «Conversione del formato»): what will be
|
||||
/// written and how. Dispose it once written or given up.
|
||||
/// </summary>
|
||||
/// <param name="Variant"><see cref="ExportVariant.Whole"/> (the file byte for byte) or <see cref="ExportVariant.Converted"/>.</param>
|
||||
/// <param name="Format">The effective format: <see cref="ExportFormat.Original"/> for a whole file.</param>
|
||||
/// <param name="Extension">The extension of the file written, with its dot («.jpg»; a whole file keeps its own).</param>
|
||||
/// <param name="Length">The bytes <see cref="Produce"/> writes.</param>
|
||||
/// <param name="Sha256">
|
||||
/// The SHA-256 (lowercase hex) of what <see cref="Produce"/> writes; null for a remux, known once written.
|
||||
/// </param>
|
||||
/// <param name="Notes">Note codes: why the file is copied as it is, or what the conversion could not carry.</param>
|
||||
/// <param name="Produce">Writes the file into the stream given.</param>
|
||||
public sealed record MediaConversionResult(ExportVariant Variant, ExportFormat Format, string Extension,
|
||||
long Length, string? Sha256, IReadOnlyList<string> Notes, Func<Stream, CancellationToken, Task> Produce) : IDisposable
|
||||
{
|
||||
/// <summary>The note prefix of a video that cannot be remuxed; the <see cref="RemuxRefusal"/> follows the colon.</summary>
|
||||
public const string AsIsNotRemuxable = "AsIsNotRemuxable";
|
||||
|
||||
/// <summary>Converted bytes or a remux plan, released on <see cref="Dispose"/>.</summary>
|
||||
internal object? Held { get; set; }
|
||||
|
||||
/// <inheritdoc />
|
||||
public void Dispose() => Held = null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Prepares a library file in a target format, independent of where it goes (an export destination, the library):
|
||||
/// photos are converted in memory under the <see cref="ConversionThrottle"/>, videos are remuxed into MP4 while being
|
||||
/// written. The source is never changed.
|
||||
/// </summary>
|
||||
public static class MediaConverter
|
||||
{
|
||||
/// <summary>The raw camera formats, copied as they are (spec §4.10).</summary>
|
||||
private static readonly HashSet<string> RawExtensions = new(StringComparer.OrdinalIgnoreCase)
|
||||
{
|
||||
".dng", ".cr2", ".cr3", ".nef", ".arw", ".raf", ".orf", ".rw2", ".pef", ".srw",
|
||||
};
|
||||
|
||||
/// <summary>A raw camera format by its extension (with its dot), copied as it is.</summary>
|
||||
public static bool IsRawExtension(string extension) => RawExtensions.Contains(extension);
|
||||
|
||||
/// <summary>The raw camera extensions (with their dot, lower case), for rules written in SQL.</summary>
|
||||
public static IReadOnlyCollection<string> RawExtensionList => RawExtensions;
|
||||
|
||||
/// <summary>
|
||||
/// Prepares <paramref name="relativePath"/> (only its name is used) in <paramref name="target"/>.
|
||||
/// <paramref name="openRandomAccess"/> opens the source for reading, seekable; it may be called more than once.
|
||||
/// </summary>
|
||||
/// <exception cref="ContentChangedException">A photo's bytes do not have <paramref name="expectedSourceSha256"/>.</exception>
|
||||
/// <exception cref="ArgumentException">The target does not belong to the kind of file.</exception>
|
||||
public static async Task<MediaConversionResult> PrepareAsync(Func<Stream> openRandomAccess, string relativePath,
|
||||
MediaKind kind, ExportFormat target, string expectedSourceSha256, ConversionThrottle throttle, CancellationToken ct)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(openRandomAccess);
|
||||
ArgumentException.ThrowIfNullOrEmpty(relativePath);
|
||||
ArgumentException.ThrowIfNullOrEmpty(expectedSourceSha256);
|
||||
ArgumentNullException.ThrowIfNull(throttle);
|
||||
var valid = kind == MediaKind.Photo ? ExportFormats.IsPhotoFormat(target) : ExportFormats.IsVideoFormat(target);
|
||||
if (!valid)
|
||||
{
|
||||
throw new ArgumentException("Il formato non è adatto a questo tipo di file.", nameof(target));
|
||||
}
|
||||
|
||||
return kind == MediaKind.Photo
|
||||
? await PreparePhotoAsync(openRandomAccess, relativePath, target, expectedSourceSha256.ToLowerInvariant(), throttle, ct).ConfigureAwait(false)
|
||||
: await PrepareVideoAsync(openRandomAccess, relativePath, target, expectedSourceSha256.ToLowerInvariant(), throttle, ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>The image format written for an export format; null for Original and MP4.</summary>
|
||||
public static ImageFormat? ImageFormatOf(ExportFormat format) => format switch
|
||||
{
|
||||
ExportFormat.Jpg => ImageFormat.Jpeg,
|
||||
ExportFormat.Png => ImageFormat.Png,
|
||||
ExportFormat.WebpLossless => ImageFormat.WebP,
|
||||
_ => null,
|
||||
};
|
||||
|
||||
/// <summary>The extension of a converted file, with its dot.</summary>
|
||||
public static string ExtensionOf(ExportFormat format) => format switch
|
||||
{
|
||||
ExportFormat.Jpg => ".jpg",
|
||||
ExportFormat.Png => ".png",
|
||||
ExportFormat.WebpLossless => ".webp",
|
||||
ExportFormat.Mp4 => ".mp4",
|
||||
_ => throw new ArgumentOutOfRangeException(nameof(format)),
|
||||
};
|
||||
|
||||
private static async Task<MediaConversionResult> PreparePhotoAsync(Func<Stream> open, string relativePath,
|
||||
ExportFormat target, string expected, ConversionThrottle throttle, CancellationToken ct)
|
||||
{
|
||||
var extension = Path.GetExtension(relativePath);
|
||||
long length;
|
||||
byte[]? bytes = null;
|
||||
await using (var source = open())
|
||||
{
|
||||
length = source.Length;
|
||||
if (target != ExportFormat.Original && length <= ImageConverter.MaxSourceBytes)
|
||||
{
|
||||
bytes = new byte[length];
|
||||
await source.ReadExactlyAsync(bytes, ct).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
if (bytes is null)
|
||||
{
|
||||
// Original, or too large to hold: the file byte for byte, checked against its SHA while written.
|
||||
return Whole(open, extension, length, expected, target == ExportFormat.Original ? [] : [ImageConversionLosses.AsIsTooLarge]);
|
||||
}
|
||||
|
||||
var sha = Convert.ToHexStringLower(SHA256.HashData(bytes));
|
||||
if (!string.Equals(sha, expected, StringComparison.Ordinal))
|
||||
{
|
||||
throw new ContentChangedException("Il file della libreria è cambiato durante la copia.");
|
||||
}
|
||||
|
||||
if (RawExtensions.Contains(extension))
|
||||
{
|
||||
return Whole(bytes, extension, sha, [ImageConversionLosses.AsIsRaw]);
|
||||
}
|
||||
|
||||
var format = ImageFormatOf(target)!.Value;
|
||||
var check = ImageConverter.Check(bytes, format);
|
||||
switch (check.Action)
|
||||
{
|
||||
case ImageConversionAction.CopyAsIs:
|
||||
return Whole(bytes, extension, sha, []);
|
||||
case ImageConversionAction.CopyOriginal:
|
||||
return Whole(bytes, extension, sha, check.NoteCode is { } note ? [note] : []);
|
||||
}
|
||||
|
||||
var (converted, refusal) = await throttle.RunAsync((ImageConversionResult? Result, string? Refusal) (CancellationToken token) =>
|
||||
{
|
||||
token.ThrowIfCancellationRequested();
|
||||
try
|
||||
{
|
||||
return (ImageConverter.Convert(bytes, format), null);
|
||||
}
|
||||
catch (ImageLimitException)
|
||||
{
|
||||
// Readable, but over what the decoder or the target allows: «troppo grande», never «non si legge».
|
||||
return (null, ImageConversionLosses.AsIsTooLarge);
|
||||
}
|
||||
catch (ImageDecodeException)
|
||||
{
|
||||
return (null, ImageConversionLosses.AsIsNotDecodable);
|
||||
}
|
||||
}, ct).ConfigureAwait(false);
|
||||
if (converted is null)
|
||||
{
|
||||
return Whole(bytes, extension, sha, [refusal!]);
|
||||
}
|
||||
|
||||
var data = converted.Data;
|
||||
return new MediaConversionResult(ExportVariant.Converted, target, ExtensionOf(target), data.Length,
|
||||
Convert.ToHexStringLower(SHA256.HashData(data)), converted.Losses, Writer(data))
|
||||
{
|
||||
Held = data,
|
||||
};
|
||||
}
|
||||
|
||||
private static async Task<MediaConversionResult> PrepareVideoAsync(Func<Stream> open, string relativePath,
|
||||
ExportFormat target, string expected, ConversionThrottle throttle, CancellationToken ct)
|
||||
{
|
||||
var extension = Path.GetExtension(relativePath);
|
||||
var fileName = Path.GetFileName(relativePath);
|
||||
var (length, refusal, plan) = await throttle.RunAsync(token =>
|
||||
{
|
||||
using var source = open();
|
||||
var size = source.Length;
|
||||
if (target == ExportFormat.Original)
|
||||
{
|
||||
return (size, RemuxRefusal.AlreadyMp4, (RemuxPlan?)null);
|
||||
}
|
||||
|
||||
var outcome = Mp4Remuxer.Check(source, fileName, out var made, token);
|
||||
return (size, outcome, made);
|
||||
}, ct).ConfigureAwait(false);
|
||||
|
||||
if (refusal == RemuxRefusal.None && plan is not null)
|
||||
{
|
||||
return new MediaConversionResult(ExportVariant.Converted, ExportFormat.Mp4, ".mp4", plan.OutputLength, null,
|
||||
plan.Losses, (output, token) => Task.Run(
|
||||
() =>
|
||||
{
|
||||
using var source = open();
|
||||
Mp4Remuxer.Write(plan, source, output, token);
|
||||
},
|
||||
token))
|
||||
{
|
||||
Held = plan,
|
||||
};
|
||||
}
|
||||
|
||||
string[] notes = refusal == RemuxRefusal.AlreadyMp4 ? [] : [$"{MediaConversionResult.AsIsNotRemuxable}:{refusal}"];
|
||||
return Whole(open, extension, length, expected, notes);
|
||||
}
|
||||
|
||||
/// <summary>A whole file streamed from the source (a video, or a photo not read into memory).</summary>
|
||||
private static MediaConversionResult Whole(Func<Stream> open, string extension, long length, string sha, IReadOnlyList<string> notes) =>
|
||||
new(ExportVariant.Whole, ExportFormat.Original, extension, length, sha, notes, async (output, token) =>
|
||||
{
|
||||
await using var source = open();
|
||||
await source.CopyToAsync(output, token).ConfigureAwait(false);
|
||||
});
|
||||
|
||||
/// <summary>A whole photo from the bytes already read and checked.</summary>
|
||||
private static MediaConversionResult Whole(byte[] bytes, string extension, string sha, IReadOnlyList<string> notes) =>
|
||||
new(ExportVariant.Whole, ExportFormat.Original, extension, bytes.Length, sha, notes, Writer(bytes)) { Held = bytes };
|
||||
|
||||
private static Func<Stream, CancellationToken, Task> Writer(byte[] data) =>
|
||||
(output, token) => output.WriteAsync(data, token).AsTask();
|
||||
}
|
||||
@@ -282,7 +282,12 @@ public sealed class DownloadDuplicateReview(
|
||||
}
|
||||
|
||||
var folder = layout.AccountFolder(account);
|
||||
await storage.Media.UpdateAsync(media with { State = MediaState.Deleted }, ct).ConfigureAwait(false);
|
||||
|
||||
// Its converted files of the library (tappa E3) go with it, in the transaction that deletes the file: the queue
|
||||
// and the failures are dropped, the rows with a file become «Tolto» and their files are deleted below (one the
|
||||
// worker records meanwhile is among them). No supersession for the loser.
|
||||
var removed = await storage.Conversions.ForgetDeletedMediaAsync(media.Id, clock.Now, ct).ConfigureAwait(false);
|
||||
var withFiles = removed.Where(LibraryDeletion.HasFile).ToList();
|
||||
await storage.Entries.RecomputeStateAsync(stored.Entry.Id, ct).ConfigureAwait(false);
|
||||
hashIndex?.Remove(media.Id);
|
||||
var remaining = stored.Media.Select(m => m.Id == media.Id ? m with { State = MediaState.Deleted } : m).ToList();
|
||||
@@ -312,6 +317,14 @@ public sealed class DownloadDuplicateReview(
|
||||
}
|
||||
}
|
||||
|
||||
var failedConverted = new List<string>();
|
||||
await LibraryDeletion.DeleteConvertedFilesAsync(storage, account.Id, folder, withFiles, [], [], failedConverted, ct).ConfigureAwait(false);
|
||||
if (failedConverted.Count > 0)
|
||||
{
|
||||
var more = $"@{side.Username}, file convertiti: {string.Join("; ", failedConverted)}.";
|
||||
problem = problem is null ? more : problem + " " + more;
|
||||
}
|
||||
|
||||
if (thumbnails is not null && media.Sha256 is { } sha)
|
||||
{
|
||||
var users = await storage.Media.FindBySha256Async(sha, ct).ConfigureAwait(false);
|
||||
|
||||
@@ -31,6 +31,9 @@ public sealed record DeletionResult(
|
||||
IReadOnlyList<string> FailedFiles)
|
||||
{
|
||||
public bool Complete => Found && FailedFiles.Count == 0;
|
||||
|
||||
/// <summary>Converted files of the library (tappa E3) deleted with the originals; they are in <see cref="DeletedFiles"/> too.</summary>
|
||||
public int ConvertedFiles { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -69,14 +72,12 @@ public sealed class LibraryDeletion(
|
||||
await journal.AppendDeletedAsync(folder, account, stored.Entry, present.Select(m => m.RelativePath!).ToList(), mode == DeletionMode.Remember, none)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
if (mode == DeletionMode.Remember)
|
||||
{
|
||||
await storage.Entries.MarkDeletedAsync(entryId, clock.Now, none).ConfigureAwait(false);
|
||||
}
|
||||
else
|
||||
{
|
||||
await storage.Entries.RemoveAsync(entryId, none).ConfigureAwait(false);
|
||||
}
|
||||
// The converted files of the library (tappa E3) go with their originals; only the explicit choice deletes them.
|
||||
// Their rows are chosen in the transaction that deletes the entry: one the worker records meanwhile is among them.
|
||||
var removed = mode == DeletionMode.Remember
|
||||
? await storage.Entries.MarkDeletedWithConversionsAsync(entryId, clock.Now, none).ConfigureAwait(false)
|
||||
: await storage.Entries.RemoveWithConversionsAsync(entryId, none).ConfigureAwait(false);
|
||||
IReadOnlyList<MediaConversion> withFiles = removed.Where(HasFile).ToList();
|
||||
|
||||
foreach (var media in stored.Media)
|
||||
{
|
||||
@@ -108,6 +109,8 @@ public sealed class LibraryDeletion(
|
||||
}
|
||||
}
|
||||
|
||||
var converted = await DeleteConvertedFilesAsync(storage, account.Id, folder, withFiles, deleted, missing, failed, none).ConfigureAwait(false);
|
||||
|
||||
if (thumbnails is not null)
|
||||
{
|
||||
foreach (var sha in stored.Media.Select(m => m.Sha256).OfType<string>().Distinct(StringComparer.Ordinal))
|
||||
@@ -127,7 +130,89 @@ public sealed class LibraryDeletion(
|
||||
}
|
||||
}
|
||||
|
||||
return new DeletionResult(entryId, true, deleted, missing, failed);
|
||||
return new DeletionResult(entryId, true, deleted, missing, failed) { ConvertedFiles = converted };
|
||||
}
|
||||
|
||||
/// <summary>A conversion whose file is (or was last known to be) on disk.</summary>
|
||||
internal static bool HasFile(MediaConversion c) =>
|
||||
c.State is MediaConversionState.Converted or MediaConversionState.Superseded && c.RelativePath is not null && c.Sha256 is not null;
|
||||
|
||||
/// <summary>
|
||||
/// Deletes the converted files of conversions just removed or marked «Tolto», each only if no library file and no
|
||||
/// live conversion still records its path and it still has the bytes recorded: a file replaced by Alberto stays and
|
||||
/// is listed among the failures with its reason. Returns how many were deleted.
|
||||
/// </summary>
|
||||
internal static async Task<int> DeleteConvertedFilesAsync(IFebeStorage storage, long accountId, string folder, IReadOnlyList<MediaConversion> conversions,
|
||||
List<string> deleted, List<string> missing, List<string> failed, CancellationToken ct)
|
||||
{
|
||||
var count = 0;
|
||||
foreach (var conversion in conversions)
|
||||
{
|
||||
var relative = conversion.RelativePath!;
|
||||
try
|
||||
{
|
||||
var path = LibraryLayout.FullPath(folder, relative);
|
||||
if (!File.Exists(path))
|
||||
{
|
||||
missing.Add(relative);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (await IsStillRecordedAsync(storage, accountId, conversion, ct).ConfigureAwait(false))
|
||||
{
|
||||
continue; // another file of the library has that name now: it is not this conversion's to delete
|
||||
}
|
||||
|
||||
if (!string.Equals(HashFile(path), conversion.Sha256, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
failed.Add($"{relative}: il file convertito è cambiato dopo la conversione, quindi resta dov'è.");
|
||||
continue;
|
||||
}
|
||||
|
||||
File.Delete(path);
|
||||
deleted.Add(relative);
|
||||
count++;
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException)
|
||||
{
|
||||
failed.Add($"{relative}: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
return count;
|
||||
}
|
||||
|
||||
private static async Task<bool> IsStillRecordedAsync(IFebeStorage storage, long accountId, MediaConversion conversion, CancellationToken ct)
|
||||
{
|
||||
var comparison = OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal;
|
||||
var sha = conversion.Sha256!;
|
||||
foreach (var m in await storage.Media.FindBySha256Async(sha, ct).ConfigureAwait(false))
|
||||
{
|
||||
if (m.Entry.AccountId == accountId && EntryStateRules.IsPresent(m.Media.State) && m.Media.RelativePath is { } p
|
||||
&& string.Equals(LibraryLayout.ToStored(p), conversion.RelativePath, comparison))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var other in await storage.Conversions.FindBySha256Async(sha, ct).ConfigureAwait(false))
|
||||
{
|
||||
if (other.Id != conversion.Id && other.State is MediaConversionState.Converted or MediaConversionState.Superseded
|
||||
&& string.Equals(other.RelativePath, conversion.RelativePath, comparison)
|
||||
&& await storage.Media.GetAsync(other.MediaId, ct).ConfigureAwait(false) is { } owner
|
||||
&& (await storage.Entries.GetAsync(owner.EntryId, ct).ConfigureAwait(false))?.AccountId == accountId)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private static string HashFile(string path)
|
||||
{
|
||||
using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, 128 * 1024, FileOptions.SequentialScan);
|
||||
return Convert.ToHexStringLower(System.Security.Cryptography.SHA256.HashData(stream));
|
||||
}
|
||||
|
||||
/// <summary>Multiple selection: deletes each entry in turn.</summary>
|
||||
|
||||
@@ -3,6 +3,7 @@ using System.Globalization;
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Core.Export;
|
||||
using Febe.Core.Library.Conversion;
|
||||
using Febe.Core.Storage;
|
||||
|
||||
namespace Febe.Core.Library;
|
||||
@@ -371,6 +372,10 @@ public sealed class LibraryIngest(
|
||||
stored.Media,
|
||||
highlights.Select(h => new JournalHighlight(h.InstagramId, h.Title, h.Position)).ToList(),
|
||||
ct).ConfigureAwait(false);
|
||||
|
||||
// The conversion for the library (tappa E3, Q29): a new file enters its queue after its journal line; the
|
||||
// files the entry already had before the format was set wait for «Anche i N» (EnqueueEntryAsync).
|
||||
await LibraryConversionQueue.EnqueueEntryAsync(storage, stored.Media, clock.Now, CancellationToken.None).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
using System.Globalization;
|
||||
using System.Security.Cryptography;
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Core.Export;
|
||||
using Febe.Core.Library.Conversion;
|
||||
using Febe.Core.Storage;
|
||||
|
||||
namespace Febe.Core.Library;
|
||||
@@ -61,6 +63,15 @@ public sealed record RebuildReport
|
||||
/// <summary>Files in account folders that no journal line mentions: left untouched, not added.</summary>
|
||||
public int UntrackedFiles { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Converted files of the library without a record (tappa E3): next to a file of the journal, with its name and in a
|
||||
/// target format. Left untouched; queued again when the conversion for their kind is on with that format.
|
||||
/// </summary>
|
||||
public int ConversionsFound { get; init; }
|
||||
|
||||
/// <summary>Converted files of the library still on disk for entries deleted «ricordando la scelta»: left untouched.</summary>
|
||||
public int ConversionsOfDeletedEntries { get; init; }
|
||||
|
||||
public int InvalidLines { get; init; }
|
||||
|
||||
/// <summary>A few examples of what needs attention (Italian), for the report screen.</summary>
|
||||
@@ -152,7 +163,7 @@ public sealed class LibraryRebuilder(
|
||||
var allItems = Fold(journal.Lines, report);
|
||||
|
||||
// Entries already in the database are left as they are (deletions excepted): no hashing, no change.
|
||||
var items = await SplitPresentAsync(account, allItems, report, ct).ConfigureAwait(false);
|
||||
var items = await SplitPresentAsync(account, folder, allItems, report, ct).ConfigureAwait(false);
|
||||
|
||||
// Verify files in parallel: hashing dominates the time.
|
||||
var live = items.Where(i => !i.Deleted).ToList();
|
||||
@@ -198,11 +209,11 @@ public sealed class LibraryRebuilder(
|
||||
batch.Add((item, new NewEntry(entry, media)));
|
||||
if (batch.Count >= BatchSize)
|
||||
{
|
||||
await FlushAsync(account, batch, report, ct).ConfigureAwait(false);
|
||||
await FlushAsync(account, folder, batch, report, ct).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
await FlushAsync(account, batch, report, ct).ConfigureAwait(false);
|
||||
await FlushAsync(account, folder, batch, report, ct).ConfigureAwait(false);
|
||||
|
||||
// Files whose bytes on disk differ from the journal: their copies in external folders are «Superato» (spec §4.10).
|
||||
foreach (var (old, now) in report.Changed)
|
||||
@@ -211,14 +222,14 @@ public sealed class LibraryRebuilder(
|
||||
}
|
||||
|
||||
report.Changed.Clear();
|
||||
CountUntracked(folder, allItems, report);
|
||||
await CountUntrackedAsync(account, folder, allItems, report, ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the items that are not in the database yet. Items already present are counted; a remembered deletion
|
||||
/// is applied to them if the database still shows them.
|
||||
/// </summary>
|
||||
private async Task<List<Item>> SplitPresentAsync(Account account, List<Item> items, Accumulator report, CancellationToken ct)
|
||||
private async Task<List<Item>> SplitPresentAsync(Account account, string folder, List<Item> items, Accumulator report, CancellationToken ct)
|
||||
{
|
||||
var paths = await storage.Media.MapPathsAsync(account.Id, ct).ConfigureAwait(false);
|
||||
var known = new HashSet<(EntryKind, string)>();
|
||||
@@ -253,7 +264,7 @@ public sealed class LibraryRebuilder(
|
||||
: null;
|
||||
if (existing is not null && existing.State != EntryState.Deleted)
|
||||
{
|
||||
await storage.Entries.MarkDeletedAsync(existing.Id, item.DeletedAt ?? clock.Now, ct).ConfigureAwait(false);
|
||||
await MarkDeletedAsync(folder, existing.Id, item.DeletedAt ?? clock.Now, report, ct).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -582,7 +593,7 @@ public sealed class LibraryRebuilder(
|
||||
};
|
||||
}
|
||||
|
||||
private async Task FlushAsync(Account account, List<(Item Item, NewEntry Entry)> batch, Accumulator report, CancellationToken ct)
|
||||
private async Task FlushAsync(Account account, string folder, List<(Item Item, NewEntry Entry)> batch, Accumulator report, CancellationToken ct)
|
||||
{
|
||||
if (batch.Count == 0)
|
||||
{
|
||||
@@ -604,7 +615,7 @@ public sealed class LibraryRebuilder(
|
||||
report.EntriesAlreadyPresent++;
|
||||
if (item.Deleted && stored.Entry.State != EntryState.Deleted)
|
||||
{
|
||||
await storage.Entries.MarkDeletedAsync(stored.Entry.Id, item.DeletedAt ?? clock.Now, ct).ConfigureAwait(false);
|
||||
await MarkDeletedAsync(folder, stored.Entry.Id, item.DeletedAt ?? clock.Now, report, ct).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -661,11 +672,98 @@ public sealed class LibraryRebuilder(
|
||||
State = MediaState.Deleted,
|
||||
};
|
||||
|
||||
private static void CountUntracked(string folder, List<Item> items, Accumulator report)
|
||||
/// <summary>
|
||||
/// A remembered deletion found by the rebuild (tappa E3, WP2.4): the entry's conversions whose converted file is
|
||||
/// missing become «Tolto»; those whose file is still on disk stay as they are (the rebuild never deletes a file) and
|
||||
/// are counted.
|
||||
/// </summary>
|
||||
private async Task MarkDeletedAsync(string folder, long entryId, DateTimeOffset at, Accumulator report, CancellationToken ct)
|
||||
{
|
||||
var missing = new List<long>();
|
||||
foreach (var conversion in await storage.Conversions.ListByEntryAsync(entryId, ct).ConfigureAwait(false))
|
||||
{
|
||||
if (conversion.State is not (MediaConversionState.Converted or MediaConversionState.Superseded) || conversion.RelativePath is not { } relative)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (ExistsIn(folder, relative))
|
||||
{
|
||||
report.ConversionsOfDeletedEntries++;
|
||||
}
|
||||
else
|
||||
{
|
||||
missing.Add(conversion.Id);
|
||||
}
|
||||
}
|
||||
|
||||
await storage.Entries.MarkDeletedAsync(entryId, at, missing, ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private static bool ExistsIn(string folder, string relative)
|
||||
{
|
||||
try
|
||||
{
|
||||
return File.Exists(LibraryLayout.FullPath(folder, relative));
|
||||
}
|
||||
catch (ArgumentException)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The format a converted file of the library has, by its extension; null for any other file.</summary>
|
||||
private static ExportFormat? ConvertedFormatOf(string extension) => extension.ToLowerInvariant() switch
|
||||
{
|
||||
".jpg" or ".jpeg" => ExportFormat.Jpg,
|
||||
".png" => ExportFormat.Png,
|
||||
".webp" => ExportFormat.WebpLossless,
|
||||
".mp4" => ExportFormat.Mp4,
|
||||
_ => null,
|
||||
};
|
||||
|
||||
/// <summary>«nome (2)» → «nome»: the free names the conversion for the library gives.</summary>
|
||||
private static string WithoutNumber(string stem)
|
||||
{
|
||||
var open = stem.LastIndexOf(" (", StringComparison.Ordinal);
|
||||
if (open > 0 && stem.EndsWith(')')
|
||||
&& int.TryParse(stem.AsSpan(open + 2, stem.Length - open - 3), NumberStyles.None, CultureInfo.InvariantCulture, out _))
|
||||
{
|
||||
return stem[..open];
|
||||
}
|
||||
|
||||
return stem;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Counts the files of the account folder that no journal line mentions (left untouched). The converted files of the
|
||||
/// library (tappa E3) are not unknown: those with a row are skipped; one without a row, next to a file of the
|
||||
/// journal with its stem and in a target format, is counted apart and, when the conversion for that kind is on with
|
||||
/// that format, its file is queued again (a Pending row: the worker adopts the file by its SHA-256). Nothing is
|
||||
/// converted during the rebuild.
|
||||
/// </summary>
|
||||
private async Task CountUntrackedAsync(Account account, string folder, List<Item> items, Accumulator report, CancellationToken ct)
|
||||
{
|
||||
var comparer = OperatingSystem.IsWindows() ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal;
|
||||
var known = new HashSet<string>(
|
||||
items.SelectMany(i => i.Files.Values.Concat(i.Removed.Values)).Select(f => LibraryLayout.ToStored(f.Path)),
|
||||
OperatingSystem.IsWindows() ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal);
|
||||
comparer);
|
||||
foreach (var path in await storage.Conversions.ListPathsByAccountAsync(account.Id, ct).ConfigureAwait(false))
|
||||
{
|
||||
known.Add(path);
|
||||
}
|
||||
|
||||
// Files of the journal by folder and stem, for the converted files next to them.
|
||||
var byStem = new Dictionary<string, JournalFile>(comparer);
|
||||
foreach (var file in items.Where(i => !i.Deleted).SelectMany(i => i.Files.Values))
|
||||
{
|
||||
var stored = LibraryLayout.ToStored(file.Path);
|
||||
var slash = stored.LastIndexOf('/');
|
||||
byStem.TryAdd((slash < 0 ? string.Empty : stored[..(slash + 1)]) + WindowsFileNames.SplitExtension(stored[(slash + 1)..]).Stem, file);
|
||||
}
|
||||
|
||||
ExportSettings? settings = null;
|
||||
IReadOnlyDictionary<string, long>? paths = null;
|
||||
foreach (var file in Directory.EnumerateFiles(folder, "*", new EnumerationOptions { RecurseSubdirectories = true, IgnoreInaccessible = true }))
|
||||
{
|
||||
var name = Path.GetFileName(file);
|
||||
@@ -675,11 +773,56 @@ public sealed class LibraryRebuilder(
|
||||
}
|
||||
|
||||
var relative = LibraryLayout.ToStored(Path.GetRelativePath(folder, file));
|
||||
if (!known.Contains(relative))
|
||||
if (known.Contains(relative))
|
||||
{
|
||||
report.UntrackedFiles++;
|
||||
report.Note($"File non registrato in _febe.jsonl (lasciato dov'è): {Path.GetFileName(folder)}/{relative}");
|
||||
continue;
|
||||
}
|
||||
|
||||
var slash = relative.LastIndexOf('/');
|
||||
var (stem, extension) = WindowsFileNames.SplitExtension(relative[(slash + 1)..]);
|
||||
var key = (slash < 0 ? string.Empty : relative[..(slash + 1)]) + WithoutNumber(stem);
|
||||
if (ConvertedFormatOf(extension) is { } format && byStem.TryGetValue(key, out var original))
|
||||
{
|
||||
report.ConversionsFound++;
|
||||
try
|
||||
{
|
||||
settings ??= await ExportSettings.LoadAsync(storage.Settings, ct).ConfigureAwait(false);
|
||||
paths ??= await storage.Media.MapPathsAsync(account.Id, ct).ConfigureAwait(false);
|
||||
await QueueFoundAsync(original, format, settings, paths, ct).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex) when (ex is DuplicateRecordException or KeyNotFoundException or ArgumentException)
|
||||
{
|
||||
// Counted, never thrown: the worker or a later rebuild finds it again.
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
report.UntrackedFiles++;
|
||||
report.Note($"File non registrato in _febe.jsonl (lasciato dov'è): {Path.GetFileName(folder)}/{relative}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Queues the journal file <paramref name="original"/> in <paramref name="format"/> when its conversion is on with that format.</summary>
|
||||
private async Task QueueFoundAsync(JournalFile original, ExportFormat format, ExportSettings settings, IReadOnlyDictionary<string, long> paths, CancellationToken ct)
|
||||
{
|
||||
var stored = LibraryLayout.ToStored(original.Path);
|
||||
if (!paths.TryGetValue(stored, out var entryId))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var media = (await storage.Media.ListByEntryAsync(entryId, ct).ConfigureAwait(false))
|
||||
.FirstOrDefault(m => m.RelativePath is { } p && string.Equals(LibraryLayout.ToStored(p), stored, StringComparison.Ordinal));
|
||||
if (media is null || LibraryConversionRules.FormatFor(media.Kind, settings) != format)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var requests = LibraryConversionRules.RequestsFor([media], settings);
|
||||
if (requests.Count > 0)
|
||||
{
|
||||
await storage.Conversions.EnqueueAsync(requests, clock.Now, ct).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -746,6 +889,10 @@ public sealed class LibraryRebuilder(
|
||||
|
||||
public int UntrackedFiles { get; set; }
|
||||
|
||||
public int ConversionsFound { get; set; }
|
||||
|
||||
public int ConversionsOfDeletedEntries { get; set; }
|
||||
|
||||
public int InvalidLines { get; set; }
|
||||
|
||||
/// <summary>(journal SHA-256, SHA-256 on disk) of the folder being rebuilt, for the copies to mark «Superato».</summary>
|
||||
@@ -773,6 +920,8 @@ public sealed class LibraryRebuilder(
|
||||
FilesUnreadable = FilesUnreadable,
|
||||
HashMismatches = HashMismatches,
|
||||
UntrackedFiles = UntrackedFiles,
|
||||
ConversionsFound = ConversionsFound,
|
||||
ConversionsOfDeletedEntries = ConversionsOfDeletedEntries,
|
||||
InvalidLines = InvalidLines,
|
||||
Notes = _notes,
|
||||
};
|
||||
|
||||
@@ -42,6 +42,12 @@ public sealed record SafeWriteOptions
|
||||
/// is removed and an <see cref="IOException"/> says so.
|
||||
/// </summary>
|
||||
public bool VerifyFromDisk { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// The end of the stem of the file name that a shortening or a free name never cuts (the frame suffix of tappa
|
||||
/// E3, «_t0m12s340»): a free name is «nome_t0m12s340 (2).png», as <c>ExportPaths.NumberedName</c> gives it.
|
||||
/// </summary>
|
||||
public string? KeepSuffix { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>The content exceeded <see cref="SafeWriteOptions.MaxBytes"/>; nothing was kept.</summary>
|
||||
@@ -164,6 +170,38 @@ public sealed class SafeFileWriter(int maxPathLength = WindowsFileNames.MaxPathL
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(source);
|
||||
return await SaveCoreAsync((path, o, token) => WriteTempAsync(source, path, o, token), rootFolder, tempDirectory, decide, options, ct)
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// As <see cref="SaveAsync(Stream, string, string, Func{FileDigest, CancellationToken, ValueTask{string}}, SafeWriteOptions, CancellationToken)"/>,
|
||||
/// for content that is made while it is written (a converted photo, a remuxed video, a frame): <paramref name="produce"/>
|
||||
/// writes it into the temporary file, through a stream that hashes and counts it (and honours
|
||||
/// <see cref="SafeWriteOptions.MaxBytes"/> and <see cref="SafeWriteOptions.Progress"/>); then the same checks,
|
||||
/// <paramref name="decide"/> and the free-name rename. Our own temporary file is removed on any failure.
|
||||
/// </summary>
|
||||
public async Task<SavedFile?> SaveAsync(
|
||||
Func<Stream, CancellationToken, Task> produce,
|
||||
string rootFolder,
|
||||
string tempDirectory,
|
||||
Func<FileDigest, CancellationToken, ValueTask<string?>> decide,
|
||||
SafeWriteOptions? options = null,
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(produce);
|
||||
return await SaveCoreAsync((path, o, token) => ProduceTempAsync(produce, path, o, token), rootFolder, tempDirectory, decide, options, ct)
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private async Task<SavedFile?> SaveCoreAsync(
|
||||
Func<string, SafeWriteOptions, CancellationToken, Task<FileDigest>> write,
|
||||
string rootFolder,
|
||||
string tempDirectory,
|
||||
Func<FileDigest, CancellationToken, ValueTask<string?>> decide,
|
||||
SafeWriteOptions? options,
|
||||
CancellationToken ct)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(rootFolder);
|
||||
ArgumentNullException.ThrowIfNull(decide);
|
||||
options ??= new SafeWriteOptions();
|
||||
@@ -180,7 +218,7 @@ public sealed class SafeFileWriter(int maxPathLength = WindowsFileNames.MaxPathL
|
||||
|
||||
try
|
||||
{
|
||||
var digest = await WriteTempAsync(source, tempPath, options, ct).ConfigureAwait(false);
|
||||
var digest = await write(tempPath, options, ct).ConfigureAwait(false);
|
||||
ct.ThrowIfCancellationRequested();
|
||||
if (options.VerifyFromDisk)
|
||||
{
|
||||
@@ -194,7 +232,7 @@ public sealed class SafeFileWriter(int maxPathLength = WindowsFileNames.MaxPathL
|
||||
}
|
||||
|
||||
ct.ThrowIfCancellationRequested();
|
||||
var finalPath = MoveToFreeName(tempPath, root, desired, out var relative);
|
||||
var finalPath = MoveToFreeName(tempPath, root, desired, options.KeepSuffix, out var relative);
|
||||
var timeSet = true;
|
||||
if (options.LastWriteTime is { } time)
|
||||
{
|
||||
@@ -289,6 +327,93 @@ public sealed class SafeFileWriter(int maxPathLength = WindowsFileNames.MaxPathL
|
||||
return new FileDigest(total, Convert.ToHexStringLower(hash.GetHashAndReset()));
|
||||
}
|
||||
|
||||
private static async Task<FileDigest> ProduceTempAsync(Func<Stream, CancellationToken, Task> produce, string tempPath, SafeWriteOptions options, CancellationToken ct)
|
||||
{
|
||||
await using var target = new FileStream(tempPath, FileMode.CreateNew, FileAccess.Write, FileShare.None, BufferSize, FileOptions.Asynchronous);
|
||||
using var hashing = new HashingStream(target, options);
|
||||
await produce(hashing, ct).ConfigureAwait(false);
|
||||
ct.ThrowIfCancellationRequested();
|
||||
await target.FlushAsync(ct).ConfigureAwait(false);
|
||||
target.Flush(flushToDisk: true);
|
||||
return hashing.Digest();
|
||||
}
|
||||
|
||||
/// <summary>A write-only stream that hashes and counts what goes through it into the temporary file.</summary>
|
||||
private sealed class HashingStream(Stream inner, SafeWriteOptions options) : Stream
|
||||
{
|
||||
private readonly IncrementalHash hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256);
|
||||
private long total;
|
||||
|
||||
public override bool CanRead => false;
|
||||
|
||||
public override bool CanSeek => false;
|
||||
|
||||
public override bool CanWrite => true;
|
||||
|
||||
public override long Length => total;
|
||||
|
||||
public override long Position
|
||||
{
|
||||
get => total;
|
||||
set => throw new NotSupportedException();
|
||||
}
|
||||
|
||||
public FileDigest Digest() => new(total, Convert.ToHexStringLower(hash.GetHashAndReset()));
|
||||
|
||||
public override void Flush() => inner.Flush();
|
||||
|
||||
public override Task FlushAsync(CancellationToken cancellationToken) => inner.FlushAsync(cancellationToken);
|
||||
|
||||
public override int Read(byte[] buffer, int offset, int count) => throw new NotSupportedException();
|
||||
|
||||
public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException();
|
||||
|
||||
public override void SetLength(long value) => throw new NotSupportedException();
|
||||
|
||||
public override void Write(byte[] buffer, int offset, int count) => Write(buffer.AsSpan(offset, count));
|
||||
|
||||
public override void Write(ReadOnlySpan<byte> buffer)
|
||||
{
|
||||
Count(buffer);
|
||||
inner.Write(buffer);
|
||||
options.Progress?.Report(total);
|
||||
}
|
||||
|
||||
public override void WriteByte(byte value) => Write([value]);
|
||||
|
||||
public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) =>
|
||||
WriteAsync(buffer.AsMemory(offset, count), cancellationToken).AsTask();
|
||||
|
||||
public override async ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken = default)
|
||||
{
|
||||
Count(buffer.Span);
|
||||
await inner.WriteAsync(buffer, cancellationToken).ConfigureAwait(false);
|
||||
options.Progress?.Report(total);
|
||||
}
|
||||
|
||||
protected override void Dispose(bool disposing)
|
||||
{
|
||||
if (disposing)
|
||||
{
|
||||
hash.Dispose();
|
||||
}
|
||||
|
||||
base.Dispose(disposing);
|
||||
}
|
||||
|
||||
private void Count(ReadOnlySpan<byte> buffer)
|
||||
{
|
||||
total += buffer.Length;
|
||||
if (options.MaxBytes is { } max && total > max)
|
||||
{
|
||||
throw new FileTooLargeException(
|
||||
string.Create(CultureInfo.InvariantCulture, $"Il file supera il limite di {max} byte: non viene salvato."));
|
||||
}
|
||||
|
||||
hash.AppendData(buffer);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Reads the temporary file back and compares its SHA-256 with the one computed while writing.</summary>
|
||||
private static async Task VerifyFromDiskAsync(string tempPath, FileDigest digest, CancellationToken ct)
|
||||
{
|
||||
@@ -316,7 +441,7 @@ public sealed class SafeFileWriter(int maxPathLength = WindowsFileNames.MaxPathL
|
||||
return segments.Count == 0 ? throw new ArgumentException("Il nome del file è vuoto.", nameof(relativePath)) : segments;
|
||||
}
|
||||
|
||||
private string MoveToFreeName(string tempPath, string root, string desiredRelativePath, out string relative)
|
||||
private string MoveToFreeName(string tempPath, string root, string desiredRelativePath, string? keepSuffix, out string relative)
|
||||
{
|
||||
var segments = Segments(desiredRelativePath);
|
||||
var (stem, extension) = WindowsFileNames.SplitExtension(segments[^1]);
|
||||
@@ -324,7 +449,8 @@ public sealed class SafeFileWriter(int maxPathLength = WindowsFileNames.MaxPathL
|
||||
{
|
||||
var name = attempt == 1 ? segments[^1] : string.Create(CultureInfo.InvariantCulture, $"{stem} ({attempt}){extension}");
|
||||
var candidate = segments.Take(segments.Count - 1).Append(WindowsFileNames.SanitizeSegment(name)).ToList();
|
||||
var fitted = WindowsFileNames.FitPath(root, candidate, maxPathLength);
|
||||
var keep = keepSuffix is null ? null : attempt == 1 ? keepSuffix : string.Create(CultureInfo.InvariantCulture, $"{keepSuffix} ({attempt})");
|
||||
var fitted = WindowsFileNames.FitPath(root, candidate, maxPathLength, keep);
|
||||
relative = string.Join('/', fitted);
|
||||
var finalPath = LibraryLayout.FullPath(root, relative);
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(finalPath)!);
|
||||
|
||||
@@ -58,7 +58,7 @@ public sealed record VideoStillness(bool IsStill, int SampledFrames, double Diff
|
||||
/// (<see cref="H264Decoder"/>, <see cref="H265Decoder"/>). Videos in other codecs (VP9, AV1, ...) give no frame: the
|
||||
/// interface shows the neutral tile.
|
||||
/// </summary>
|
||||
public sealed class VideoFrameDecoder
|
||||
public sealed partial class VideoFrameDecoder
|
||||
{
|
||||
/// <summary>Differences up to this value (0–255) count as compression noise of a still picture.</summary>
|
||||
public const double StillThreshold = 3.0;
|
||||
@@ -77,8 +77,6 @@ public sealed class VideoFrameDecoder
|
||||
/// <summary>How far back from a sample flagged as key the decoder looks for one it can really start from.</summary>
|
||||
private const int MaxRunStartSearch = 2000;
|
||||
|
||||
private static readonly DateTimeOffset AnyDate = new(9000, 1, 1, 0, 0, 0, TimeSpan.Zero);
|
||||
|
||||
private readonly TimeSpan budget;
|
||||
private readonly int maxRun;
|
||||
|
||||
@@ -184,10 +182,10 @@ public sealed class VideoFrameDecoder
|
||||
|
||||
// The frame where the run starts comes along: it stands for a target that gives no picture (a RASL picture
|
||||
// of the HEVC CRA picture decoding starts from, a damaged sample).
|
||||
var frames = decoding.Decode(start < target ? [start, target] : [target], ct);
|
||||
var frames = decoding.DecodeAll(start < target ? [start, target] : [target], ct);
|
||||
if (!frames.TryGetValue(target, out var frame) && !frames.TryGetValue(start, out frame) && target != 0)
|
||||
{
|
||||
frames = new Decoding(stream, video, maxRun).Decode([0], ct);
|
||||
frames = new Decoding(stream, video, maxRun).DecodeAll([0], ct);
|
||||
frames.TryGetValue(0, out frame);
|
||||
}
|
||||
|
||||
@@ -248,7 +246,7 @@ public sealed class VideoFrameDecoder
|
||||
return null;
|
||||
}
|
||||
|
||||
var frames = decoding.Decode([.. targets], ct);
|
||||
var frames = decoding.DecodeAll([.. targets], ct);
|
||||
if (frames.Count < 2)
|
||||
{
|
||||
return null;
|
||||
@@ -295,7 +293,7 @@ public sealed class VideoFrameDecoder
|
||||
private static VideoTrack? Open(Stream stream)
|
||||
{
|
||||
// The creation time does not matter here: any date is accepted (the readers add a day to «now»).
|
||||
var container = ContainerReader.Read(stream, AnyDate, samples: true);
|
||||
var container = ContainerReader.Read(stream, ContainerReader.AnyDate, samples: true);
|
||||
return container?.Video is { Samples.Count: > 0 } video && video.Codec switch
|
||||
{
|
||||
VideoCodec.H264 => video.AnnexB || video.AvcConfiguration is not null,
|
||||
@@ -362,6 +360,13 @@ public sealed class VideoFrameDecoder
|
||||
|
||||
/// <summary>Exact: an H.264 IDR picture, an HEVC IDR or BLA picture.</summary>
|
||||
Idr,
|
||||
|
||||
/// <summary>
|
||||
/// Exact for the pictures shown from it on: an HEVC CRA picture (only its RASL pictures, shown before it, are
|
||||
/// lost), an H.264 I picture with a recovery point SEI whose recovery_frame_cnt is 0. Elsewhere close, as
|
||||
/// <see cref="Intra"/>.
|
||||
/// </summary>
|
||||
Recovery,
|
||||
}
|
||||
|
||||
/// <summary>Size of the NAL length fields of the samples (0: Annex B), from the configuration record.</summary>
|
||||
@@ -436,9 +441,11 @@ public sealed class VideoFrameDecoder
|
||||
/// <summary>
|
||||
/// Decodes chosen samples, each from the random access point before it, reusing a run when the targets share it.
|
||||
/// </summary>
|
||||
private sealed class Decoding(Stream stream, VideoTrack video, int maxRun)
|
||||
private sealed class Decoding(Stream stream, VideoTrack video, int maxRun, bool exact = false)
|
||||
{
|
||||
private readonly Dictionary<int, Frame> found = [];
|
||||
private readonly HashSet<int> produced = [];
|
||||
private readonly List<(int Sample, Frame Frame)> pending = [];
|
||||
private readonly HashSet<int> wanted = [];
|
||||
private readonly int[] keys = KeyIndices(video);
|
||||
private readonly Dictionary<int, StartPoint> accessPoints = [];
|
||||
@@ -458,6 +465,11 @@ public sealed class VideoFrameDecoder
|
||||
/// </summary>
|
||||
internal int RunStart(int index)
|
||||
{
|
||||
if (exact)
|
||||
{
|
||||
return ExactStart(index);
|
||||
}
|
||||
|
||||
var position = Array.BinarySearch(keys, index);
|
||||
position = position >= 0 ? position : Math.Max(0, ~position - 1);
|
||||
var intra = -1;
|
||||
@@ -475,7 +487,7 @@ public sealed class VideoFrameDecoder
|
||||
return index - candidate <= maxRun || intra < 0 ? candidate : intra;
|
||||
}
|
||||
|
||||
if (point == StartPoint.Intra && intra < 0)
|
||||
if (point is StartPoint.Intra or StartPoint.Recovery && intra < 0)
|
||||
{
|
||||
intra = candidate;
|
||||
}
|
||||
@@ -490,6 +502,34 @@ public sealed class VideoFrameDecoder
|
||||
return index <= maxRun || intra < 0 ? 0 : intra;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The nearest start from which <paramref name="index"/> comes out exact, however far: an IDR picture, or a
|
||||
/// recovery point shown no later than it; otherwise the first sample.
|
||||
/// </summary>
|
||||
private int ExactStart(int index)
|
||||
{
|
||||
var position = Array.BinarySearch(keys, index);
|
||||
position = position >= 0 ? position : Math.Max(0, ~position - 1);
|
||||
var shown = video.Samples[index].PresentationTime;
|
||||
for (var tried = 0; position > 0 && tried < MaxRunStartSearch; position--, tried++)
|
||||
{
|
||||
var candidate = keys[position];
|
||||
if (!accessPoints.TryGetValue(candidate, out var point))
|
||||
{
|
||||
point = AccessPointOf(candidate);
|
||||
accessPoints[candidate] = point;
|
||||
}
|
||||
|
||||
if (point == StartPoint.Idr
|
||||
|| (point == StartPoint.Recovery && shown >= video.Samples[candidate].PresentationTime))
|
||||
{
|
||||
return candidate;
|
||||
}
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
private StartPoint AccessPointOf(int index)
|
||||
{
|
||||
try
|
||||
@@ -500,7 +540,7 @@ public sealed class VideoFrameDecoder
|
||||
return H265Decoder.AccessPoint(sample, lengthSize) switch
|
||||
{
|
||||
H265AccessPoint.Idr => StartPoint.Idr,
|
||||
H265AccessPoint.Cra => StartPoint.Intra,
|
||||
H265AccessPoint.Cra => StartPoint.Recovery,
|
||||
_ => StartPoint.None,
|
||||
};
|
||||
}
|
||||
@@ -508,6 +548,7 @@ public sealed class VideoFrameDecoder
|
||||
return H264Decoder.AccessPoint(sample, lengthSize) switch
|
||||
{
|
||||
H264AccessPoint.Idr => StartPoint.Idr,
|
||||
H264AccessPoint.IntraPicture when H264Decoder.HasExactRecoveryPoint(sample, lengthSize) => StartPoint.Recovery,
|
||||
H264AccessPoint.IntraPicture => StartPoint.Intra,
|
||||
_ => StartPoint.None,
|
||||
};
|
||||
@@ -518,7 +559,25 @@ public sealed class VideoFrameDecoder
|
||||
}
|
||||
}
|
||||
|
||||
internal Dictionary<int, Frame> Decode(int[] targets, CancellationToken ct)
|
||||
/// <summary>
|
||||
/// Decodes the targets (sample indices in ascending order) and keeps every frame: the few a thumbnail or a
|
||||
/// stillness check asks for.
|
||||
/// </summary>
|
||||
internal Dictionary<int, Frame> DecodeAll(int[] targets, CancellationToken ct)
|
||||
{
|
||||
foreach (var (sample, frame) in Decode(targets, ct))
|
||||
{
|
||||
found.TryAdd(sample, frame);
|
||||
}
|
||||
|
||||
return found;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Decodes the targets (sample indices in ascending order) and hands out each frame as soon as the sample that
|
||||
/// finishes it is decoded, in decoding order, once per sample; a target that gives no picture is left out.
|
||||
/// </summary>
|
||||
internal IEnumerable<(int Sample, Frame Frame)> Decode(int[] targets, CancellationToken ct)
|
||||
{
|
||||
foreach (var t in targets)
|
||||
{
|
||||
@@ -536,29 +595,56 @@ public sealed class VideoFrameDecoder
|
||||
next = key;
|
||||
}
|
||||
|
||||
try
|
||||
for (; next <= target; next++)
|
||||
{
|
||||
// Frames are matched to samples by the sample being decoded, not by the decoder's own count: a
|
||||
// sample without a picture (only parameter sets, a skipped RASL picture, or damaged) must not shift
|
||||
// the frames after it.
|
||||
runner ??= new Runner(video, () => wanted.Contains(current), frame => found.TryAdd(current, frame));
|
||||
for (; next <= target; next++)
|
||||
ct.ThrowIfCancellationRequested();
|
||||
if (!Step(ref runner, next))
|
||||
{
|
||||
ct.ThrowIfCancellationRequested();
|
||||
current = next;
|
||||
runner.Decode(ContainerReader.ReadSample(stream, video.Samples[next], ref buffer));
|
||||
// This run is damaged (or its samples lie past the end of a truncated file): the next target
|
||||
// starts again from its own key frame, and what was decoded so far stands.
|
||||
runner = null;
|
||||
}
|
||||
|
||||
foreach (var item in pending)
|
||||
{
|
||||
yield return item;
|
||||
}
|
||||
|
||||
pending.Clear();
|
||||
if (runner is null)
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
catch (Exception ex) when (ex is H264Exception or H265Exception or ContainerException or EndOfStreamException
|
||||
or IndexOutOfRangeException or ArgumentException or InvalidOperationException)
|
||||
{
|
||||
// This run is damaged (or its samples lie past the end of a truncated file): the next target starts
|
||||
// again from its own key frame, and what was decoded so far stands.
|
||||
runner = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return found;
|
||||
/// <summary>Decodes one sample; false when the stream is damaged there.</summary>
|
||||
private bool Step(ref Runner? runner, int sample)
|
||||
{
|
||||
try
|
||||
{
|
||||
// Frames are matched to samples by the sample being decoded, not by the decoder's own count: a sample
|
||||
// without a picture (only parameter sets, a skipped RASL picture, or damaged) must not shift the frames
|
||||
// after it.
|
||||
runner ??= new Runner(video, () => wanted.Contains(current), Found);
|
||||
current = sample;
|
||||
runner.Decode(ContainerReader.ReadSample(stream, video.Samples[sample], ref buffer));
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex) when (ex is H264Exception or H265Exception or ContainerException or EndOfStreamException
|
||||
or IndexOutOfRangeException or ArgumentException or InvalidOperationException)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private void Found(Frame frame)
|
||||
{
|
||||
if (produced.Add(current))
|
||||
{
|
||||
pending.Add((current, frame));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,348 @@
|
||||
using Febe.Core.Codecs;
|
||||
using Febe.Core.Codecs.Containers;
|
||||
using Febe.Core.Codecs.Images;
|
||||
using YuvToRgb = Febe.Core.Codecs.YuvToRgb;
|
||||
|
||||
namespace Febe.Core.Library;
|
||||
|
||||
/// <summary>What <see cref="VideoFrameReader.Open"/> found about a video.</summary>
|
||||
/// <param name="Available">False when no frame can be taken from it: <paramref name="Unavailable"/> says why.</param>
|
||||
/// <param name="Unavailable">The Italian message shown when frames are not available; null otherwise.</param>
|
||||
/// <param name="Duration">The presentation length (zero when unknown).</param>
|
||||
/// <param name="Width">Width of a frame as shown (rotation applied).</param>
|
||||
/// <param name="Height">Height of a frame as shown (rotation applied).</param>
|
||||
/// <param name="Rotation">Clockwise rotation of the track: 0, 90, 180 or 270.</param>
|
||||
/// <param name="Codec">The video codec («H264», «Hevc»), or the container's codec tag of one Febe does not decode.</param>
|
||||
/// <param name="FrameDuration">The mean time between two frames (zero when unknown).</param>
|
||||
/// <param name="HasAudio">Whether the container has an audio track.</param>
|
||||
/// <param name="SampleCount">Samples of the video track.</param>
|
||||
public sealed record VideoFrameInfo(bool Available, string? Unavailable, TimeSpan Duration, int Width, int Height,
|
||||
int Rotation, string Codec, TimeSpan FrameDuration, bool HasAudio, int SampleCount);
|
||||
|
||||
/// <summary>A frame to take: the instant asked for and the sample really shown then (spec §4.10 «Fotogrammi»).</summary>
|
||||
/// <param name="Index">Position of the instant in the request (0-based), which names the file.</param>
|
||||
/// <param name="Requested">The instant asked for.</param>
|
||||
/// <param name="Actual">
|
||||
/// When the sample is shown, rounded up to the next 100 ns tick: what the frame's identity and name carry.
|
||||
/// </param>
|
||||
/// <param name="Sample">The sample index in decoding order.</param>
|
||||
public sealed record VideoFrameTarget(int Index, TimeSpan Requested, TimeSpan Actual, int Sample);
|
||||
|
||||
/// <summary>A decoded frame, upright, in 8-bit RGBA (alpha 255). Dispose it to give the pixels back.</summary>
|
||||
public sealed class VideoFrame(int index, TimeSpan requested, TimeSpan actual, RgbaImage image) : IDisposable
|
||||
{
|
||||
/// <summary>Position of the instant in the request.</summary>
|
||||
public int Index { get; } = index;
|
||||
|
||||
/// <summary>The instant asked for.</summary>
|
||||
public TimeSpan Requested { get; } = requested;
|
||||
|
||||
/// <summary>When the frame is shown.</summary>
|
||||
public TimeSpan Actual { get; } = actual;
|
||||
|
||||
/// <summary>The pixels, rotated as the video is shown.</summary>
|
||||
public RgbaImage Image { get; } = image;
|
||||
|
||||
/// <inheritdoc />
|
||||
public void Dispose() => Image.Dispose();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Frames of a video at chosen instants, at full resolution and exact (spec §4.10 «Fotogrammi»): instants are the
|
||||
/// presentation times as a player shows them (ISO edit lists included), each frame decoded from a point the decoder can
|
||||
/// start from exactly, and turned upright. One frame lives in memory at a time; the stream must stay open and seekable
|
||||
/// while the reader is used.
|
||||
/// </summary>
|
||||
public sealed class VideoFrameReader : IDisposable
|
||||
{
|
||||
/// <summary>The message for a video whose frames Febe cannot take.</summary>
|
||||
public const string NotAvailableMessage = "Fotogramma non disponibile per questo video";
|
||||
|
||||
private readonly Stream? stream;
|
||||
private readonly VideoTrack? video;
|
||||
|
||||
/// <summary>Shown time of each sample in track units (presentation time plus the empty edits).</summary>
|
||||
private readonly long[] shown = [];
|
||||
|
||||
/// <summary>The samples that can be chosen, by shown time then decoding order.</summary>
|
||||
private readonly int[] order = [];
|
||||
|
||||
private VideoFrameReader(Stream? stream, VideoTrack? video)
|
||||
{
|
||||
this.stream = stream;
|
||||
this.video = video;
|
||||
if (video is null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var samples = video.Samples;
|
||||
shown = new long[samples.Count];
|
||||
for (var i = 0; i < samples.Count; i++)
|
||||
{
|
||||
shown[i] = samples[i].PresentationTime + video.EmptyEditDuration;
|
||||
}
|
||||
|
||||
// Samples shown before the start or from the end of the edit on (cut by the edit list) are not chosen, unless
|
||||
// nothing else is.
|
||||
var end = video.EditSegmentDuration is { } segment && segment > 0 ? video.EmptyEditDuration + segment : long.MaxValue;
|
||||
var visible = Enumerable.Range(0, samples.Count).Where(i => shown[i] >= 0 && shown[i] < end).ToArray();
|
||||
order = visible.Length > 0 ? visible : [.. Enumerable.Range(0, samples.Count)];
|
||||
Array.Sort(order, (a, b) => shown[a] != shown[b] ? shown[a].CompareTo(shown[b]) : a.CompareTo(b));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Opens the video in <paramref name="seekable"/> (left open: the caller disposes it after the reader). Never
|
||||
/// throws for a video it cannot read: <paramref name="info"/> is then not available, and the reader gives no frame.
|
||||
/// </summary>
|
||||
public static VideoFrameReader Open(Stream seekable, out VideoFrameInfo info)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(seekable);
|
||||
MediaContainer? container;
|
||||
VideoTrack? video;
|
||||
try
|
||||
{
|
||||
seekable.Position = 0;
|
||||
container = ContainerReader.Read(seekable, ContainerReader.AnyDate, samples: true);
|
||||
video = container is null ? null : VideoFrameDecoder.FrameTrack(container);
|
||||
}
|
||||
catch (Exception ex) when (VideoFrameDecoder.IsUnreadableFile(ex))
|
||||
{
|
||||
container = null;
|
||||
video = null;
|
||||
}
|
||||
|
||||
if (container?.Video is not { } track || video is null)
|
||||
{
|
||||
var v = container?.Video;
|
||||
info = new VideoFrameInfo(false, NotAvailableMessage, container?.Duration ?? TimeSpan.Zero,
|
||||
v?.DisplayWidth ?? 0, v?.DisplayHeight ?? 0, v?.Rotation ?? 0, v is null ? string.Empty : Codec(v),
|
||||
TimeSpan.Zero, container?.Audio is not null, v?.Samples.Count ?? 0);
|
||||
return new VideoFrameReader(null, null);
|
||||
}
|
||||
|
||||
var reader = new VideoFrameReader(seekable, video);
|
||||
info = new VideoFrameInfo(true, null, reader.Duration(container), track.DisplayWidth, track.DisplayHeight,
|
||||
Rotation(track.Rotation), Codec(track), reader.FrameDuration(), container.Audio is not null, track.Samples.Count);
|
||||
return reader;
|
||||
}
|
||||
|
||||
/// <summary>The length of the video from its headers only (no sample table walked through); null when unreadable.</summary>
|
||||
public static TimeSpan? ProbeDuration(Stream seekable)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(seekable);
|
||||
try
|
||||
{
|
||||
seekable.Position = 0;
|
||||
return ContainerReader.Read(seekable, ContainerReader.AnyDate, samples: false)?.Duration;
|
||||
}
|
||||
catch (Exception ex) when (VideoFrameDecoder.IsUnreadableFile(ex))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The sample shown at each instant: the one with the greatest shown time not after it; the first one for an
|
||||
/// instant before it, the last one for an instant past the end. Empty when the video is not available.
|
||||
/// </summary>
|
||||
public IReadOnlyList<VideoFrameTarget> Locate(IReadOnlyList<TimeSpan> instants)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(instants);
|
||||
if (video is null || order.Length == 0)
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
var targets = new VideoFrameTarget[instants.Count];
|
||||
for (var i = 0; i < instants.Count; i++)
|
||||
{
|
||||
var sample = SampleAt(instants[i]);
|
||||
targets[i] = new VideoFrameTarget(i, instants[i], ShownAt(sample), sample);
|
||||
}
|
||||
|
||||
return targets;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Decodes the targets lazily, in decoding order (not the order of the instants): each frame comes out as soon as it
|
||||
/// is decoded and must be disposed by the caller. A target whose sample gives no picture (a damaged stream) is left
|
||||
/// out; targets on the same sample each get their own copy.
|
||||
/// </summary>
|
||||
public IEnumerable<VideoFrame> Decode(IReadOnlyList<VideoFrameTarget> targets, CancellationToken ct)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(targets);
|
||||
return video is null || stream is null || targets.Count == 0 ? [] : DecodeCore(targets, ct);
|
||||
}
|
||||
|
||||
private IEnumerable<VideoFrame> DecodeCore(IReadOnlyList<VideoFrameTarget> targets, CancellationToken ct)
|
||||
{
|
||||
var bySample = targets.Where(t => t.Sample >= 0 && t.Sample < shown.Length)
|
||||
.GroupBy(t => t.Sample)
|
||||
.ToDictionary(g => g.Key, g => g.OrderBy(t => t.Index).ToArray());
|
||||
int[] samples = [.. bySample.Keys.Order()];
|
||||
foreach (var (sample, image) in VideoFrameDecoder.DecodeExact(stream!, video!, samples, ct))
|
||||
{
|
||||
var wanted = bySample[sample];
|
||||
for (var i = 0; i < wanted.Length; i++)
|
||||
{
|
||||
var copy = i == wanted.Length - 1 ? image : new RgbaImage(image.Width, image.Height, image.ToArray());
|
||||
yield return new VideoFrame(wanted[i].Index, wanted[i].Requested, wanted[i].Actual, copy);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public void Dispose()
|
||||
{
|
||||
// The stream belongs to the caller; nothing else is held.
|
||||
}
|
||||
|
||||
private int SampleAt(TimeSpan at)
|
||||
{
|
||||
// Exact comparison of at (100 ns ticks) with a shown time (track units): at·timescale against shown·10⁷.
|
||||
var timescale = (Int128)video!.Timescale;
|
||||
var wanted = (Int128)at.Ticks * timescale;
|
||||
int low = 0, high = order.Length - 1, best = -1;
|
||||
while (low <= high)
|
||||
{
|
||||
var middle = (low + high) / 2;
|
||||
if ((Int128)shown[order[middle]] * TimeSpan.TicksPerSecond <= wanted)
|
||||
{
|
||||
best = middle;
|
||||
low = middle + 1;
|
||||
}
|
||||
else
|
||||
{
|
||||
high = middle - 1;
|
||||
}
|
||||
}
|
||||
|
||||
if (best < 0)
|
||||
{
|
||||
return order[0];
|
||||
}
|
||||
|
||||
// Among samples shown at the same time, the first in decoding order.
|
||||
while (best > 0 && shown[order[best - 1]] == shown[order[best]])
|
||||
{
|
||||
best--;
|
||||
}
|
||||
|
||||
return order[best];
|
||||
}
|
||||
|
||||
/// <summary>The shown time of a sample as a TimeSpan, rounded up to the tick (never before it is shown).</summary>
|
||||
private TimeSpan ShownAt(int sample)
|
||||
{
|
||||
var timescale = (Int128)Math.Max(1, video!.Timescale);
|
||||
var units = (Int128)Math.Max(0, shown[sample]);
|
||||
var ticks = ((units * TimeSpan.TicksPerSecond) + timescale - 1) / timescale;
|
||||
return TimeSpan.FromTicks((long)Int128.Min(ticks, TimeSpan.MaxValue.Ticks));
|
||||
}
|
||||
|
||||
private TimeSpan Duration(MediaContainer container)
|
||||
{
|
||||
if (container.Duration is { } d && d > TimeSpan.Zero)
|
||||
{
|
||||
return d;
|
||||
}
|
||||
|
||||
if (video!.Duration > 0 && video.Timescale > 0)
|
||||
{
|
||||
return TimeSpan.FromTicks((long)((Int128)video.Duration * TimeSpan.TicksPerSecond / video.Timescale));
|
||||
}
|
||||
|
||||
return order.Length == 0 ? TimeSpan.Zero : ShownAt(order[^1]) + FrameDuration();
|
||||
}
|
||||
|
||||
private TimeSpan FrameDuration()
|
||||
{
|
||||
if (order.Length < 2 || video!.Timescale <= 0)
|
||||
{
|
||||
return TimeSpan.Zero;
|
||||
}
|
||||
|
||||
var span = (Int128)(shown[order[^1]] - shown[order[0]]) * TimeSpan.TicksPerSecond;
|
||||
return TimeSpan.FromTicks((long)(span / video.Timescale / (order.Length - 1)));
|
||||
}
|
||||
|
||||
private static int Rotation(int rotation) => ((rotation % 360) + 360) % 360 is var r && r is 90 or 180 or 270 ? r : 0;
|
||||
|
||||
private static string Codec(VideoTrack video) =>
|
||||
video.Codec is VideoCodec.H264 or VideoCodec.Hevc ? video.Codec.ToString() : video.CodecTag;
|
||||
}
|
||||
|
||||
/// <summary>The frames part of the decoder: what <see cref="VideoFrameReader"/> needs of its private machinery.</summary>
|
||||
public sealed partial class VideoFrameDecoder
|
||||
{
|
||||
/// <summary>The track frames can be taken from: H.264 or HEVC with its samples and configuration; else null.</summary>
|
||||
internal static VideoTrack? FrameTrack(MediaContainer container) =>
|
||||
container.Video is { Samples.Count: > 0, Encoded: false } video && video.Codec switch
|
||||
{
|
||||
VideoCodec.H264 => video.AnnexB || video.AvcConfiguration is not null,
|
||||
VideoCodec.Hevc => video.AnnexB || video.HevcConfiguration is not null,
|
||||
_ => false,
|
||||
}
|
||||
? video
|
||||
: null;
|
||||
|
||||
/// <summary>Whether an exception while reading a video means a file that cannot be read (not a bug).</summary>
|
||||
internal static bool IsUnreadableFile(Exception ex) => IsUnreadable(ex);
|
||||
|
||||
/// <summary>
|
||||
/// Decodes the samples (ascending indices) exactly, each from an IDR picture or a recovery point shown no later than
|
||||
/// it (else from the first sample), and gives each frame in RGBA, rotated upright, in decoding order.
|
||||
/// </summary>
|
||||
internal static IEnumerable<(int Sample, RgbaImage Image)> DecodeExact(Stream stream, VideoTrack video, int[] samples,
|
||||
CancellationToken ct)
|
||||
{
|
||||
var decoding = new Decoding(stream, video, int.MaxValue, exact: true);
|
||||
foreach (var (sample, frame) in decoding.Decode(samples, ct))
|
||||
{
|
||||
yield return (sample, ToRgba(frame, video.Rotation));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A frame at full size in RGBA (alpha 255), brought to 8 bits, then turned as the video is shown.</summary>
|
||||
private static RgbaImage ToRgba(Frame frame, int rotation)
|
||||
{
|
||||
RgbaImage image;
|
||||
if (frame.Hevc is { } h)
|
||||
{
|
||||
image = ToRgba(Planes(h), h.MatrixCoefficients, h.FullRange);
|
||||
}
|
||||
else
|
||||
{
|
||||
var a = frame.Avc!;
|
||||
image = a.BytesPerSample == 2
|
||||
? ToRgba(WidePlanes(a), a.MatrixCoefficients, a.FullRange)
|
||||
: ToRgba(Planes(a), a.MatrixCoefficients, a.FullRange);
|
||||
}
|
||||
|
||||
var orientation = (((rotation % 360) + 360) % 360) switch
|
||||
{
|
||||
90 => 6,
|
||||
180 => 3,
|
||||
270 => 8,
|
||||
_ => 1,
|
||||
};
|
||||
var upright = ImageOrientation.Apply(image, orientation);
|
||||
if (!ReferenceEquals(upright, image))
|
||||
{
|
||||
image.Dispose();
|
||||
}
|
||||
|
||||
return upright;
|
||||
}
|
||||
|
||||
private static RgbaImage ToRgba<T>(in YuvPlanes<T> planes, int matrix, bool fullRange)
|
||||
where T : unmanaged, System.Numerics.IBinaryInteger<T>
|
||||
{
|
||||
var image = new RgbaImage(planes.Width, planes.Height);
|
||||
var k = YuvToRgb.For(matrix, fullRange, planes.BitDepthY, planes.BitDepthC, planes.Height);
|
||||
YuvToRgb.Convert(planes, k, 1, image.Pixels, planes.Width * RgbaImage.BytesPerPixel, RgbaImage.BytesPerPixel,
|
||||
planes.Width, planes.Height);
|
||||
return image;
|
||||
}
|
||||
}
|
||||
@@ -89,8 +89,15 @@ public static class WindowsFileNames
|
||||
/// keeping its extension; then the longest folder segments. A shortened part ends with <c>~</c> and eight hex digits
|
||||
/// of the SHA-256 of the original, so different names stay different (for example <c>_1</c> and <c>_2</c>).
|
||||
/// </summary>
|
||||
/// <param name="baseFolder">The folder the path is below.</param>
|
||||
/// <param name="segments">The segments.</param>
|
||||
/// <param name="maxLength">The longest full path.</param>
|
||||
/// <param name="keepSuffix">
|
||||
/// When the stem of the file name ends with it (a frame suffix, «_t0m12s340»), the part before it is shortened and the
|
||||
/// hash goes before it: «nome~1a2b3c4d_t0m12s340.png». Null: the whole stem may be cut, as before tappa E3.
|
||||
/// </param>
|
||||
/// <exception cref="PathTooLongException">Even shortened, the path does not fit (the base folder is too long).</exception>
|
||||
public static IReadOnlyList<string> FitPath(string baseFolder, IReadOnlyList<string> segments, int maxLength = MaxPathLength)
|
||||
public static IReadOnlyList<string> FitPath(string baseFolder, IReadOnlyList<string> segments, int maxLength = MaxPathLength, string? keepSuffix = null)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(baseFolder);
|
||||
ArgumentNullException.ThrowIfNull(segments);
|
||||
@@ -111,11 +118,11 @@ public static class WindowsFileNames
|
||||
|
||||
// 1. The file name, keeping its extension.
|
||||
var last = parts.Length - 1;
|
||||
var (stem, extension) = SplitExtension(parts[last]);
|
||||
var (stem, extension) = SplitKept(parts[last], keepSuffix);
|
||||
var stemTarget = Math.Max(stem.Length - excess, Math.Min(stem.Length, MinimumStem + HashSuffixLength));
|
||||
if (stemTarget < stem.Length)
|
||||
{
|
||||
parts[last] = Shorten(parts[last], stemTarget + extension.Length, keepExtension: true);
|
||||
parts[last] = Shorten(parts[last], stemTarget + extension.Length, keepExtension: true, keepSuffix);
|
||||
excess = Total() - maxLength;
|
||||
}
|
||||
|
||||
@@ -156,10 +163,22 @@ public static class WindowsFileNames
|
||||
: (fileName[..dot], fileName[dot..]);
|
||||
}
|
||||
|
||||
/// <summary>Shortens a name to at most <paramref name="maxLength"/> characters with a hash suffix of the original.</summary>
|
||||
private static string Shorten(string name, int maxLength, bool keepExtension)
|
||||
/// <summary>
|
||||
/// The stem and the end that is kept of a file name: the extension, preceded by <paramref name="keepSuffix"/> when
|
||||
/// the stem ends with it.
|
||||
/// </summary>
|
||||
private static (string Stem, string Kept) SplitKept(string fileName, string? keepSuffix)
|
||||
{
|
||||
var (stem, extension) = keepExtension ? SplitExtension(name) : (name, string.Empty);
|
||||
var (stem, extension) = SplitExtension(fileName);
|
||||
return keepSuffix is { Length: > 0 } && stem.Length > keepSuffix.Length && stem.EndsWith(keepSuffix, StringComparison.Ordinal)
|
||||
? (stem[..^keepSuffix.Length], keepSuffix + extension)
|
||||
: (stem, extension);
|
||||
}
|
||||
|
||||
/// <summary>Shortens a name to at most <paramref name="maxLength"/> characters with a hash suffix of the original.</summary>
|
||||
private static string Shorten(string name, int maxLength, bool keepExtension, string? keepSuffix = null)
|
||||
{
|
||||
var (stem, extension) = keepExtension ? SplitKept(name, keepSuffix) : (name, string.Empty);
|
||||
var room = maxLength - extension.Length - HashSuffixLength;
|
||||
if (room < 1)
|
||||
{
|
||||
|
||||
@@ -58,11 +58,36 @@ public interface IEntryStore
|
||||
/// «Eliminato»: the entry stays without files so it is not downloaded again (spec §4.6). Its files become
|
||||
/// <see cref="MediaState.Deleted"/> and lose their path and perceptual hash; SHA-256 and size are kept. Deleting files on disk is the caller's job.
|
||||
/// </summary>
|
||||
Task MarkDeletedAsync(long entryId, DateTimeOffset at, CancellationToken ct = default);
|
||||
Task MarkDeletedAsync(long entryId, DateTimeOffset at, CancellationToken ct = default) => MarkDeletedAsync(entryId, at, [], ct);
|
||||
|
||||
/// <summary>«Eliminalo e lascia che torni»: removes the record (files records and highlight links by cascade).</summary>
|
||||
/// <summary>
|
||||
/// As <see cref="MarkDeletedAsync(long, DateTimeOffset, CancellationToken)"/>, and in the same transaction the
|
||||
/// conversions for the library of its files: the queue and the failures (Pending, Failed) go, and the rows of
|
||||
/// <paramref name="removedConversionIds"/> (whose converted file goes or is gone) become «Tolto». Other converted rows stay.
|
||||
/// </summary>
|
||||
Task MarkDeletedAsync(long entryId, DateTimeOffset at, IReadOnlyCollection<long> removedConversionIds, CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// «Elimina dalla libreria» with memory: as <see cref="MarkDeletedAsync(long, DateTimeOffset, CancellationToken)"/>,
|
||||
/// and in the same transaction every conversion of its files with a file (Converted, Superseded) becomes «Tolto»
|
||||
/// and is returned as it was: chosen inside the transaction, so a conversion recorded just before is among them
|
||||
/// (its file is the caller's to delete) and none can be recorded after. The queue and the failures go.
|
||||
/// </summary>
|
||||
Task<IReadOnlyList<MediaConversion>> MarkDeletedWithConversionsAsync(long entryId, DateTimeOffset at, CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// «Eliminalo e lascia che torni»: removes the record (files records and highlight links by cascade). Conversions
|
||||
/// without a file left (Pending, Failed, Removed) go with it; a Converted or Superseded one makes it fail with
|
||||
/// <see cref="InvalidOperationException"/> (its file would be forgotten): use <see cref="RemoveWithConversionsAsync"/>.
|
||||
/// </summary>
|
||||
Task RemoveAsync(long entryId, CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// «Eliminalo e lascia che torni» from «Elimina dalla libreria»: removes the record and every conversion of its files
|
||||
/// in one transaction, and returns the conversions removed (their converted files are the caller's to delete).
|
||||
/// </summary>
|
||||
Task<IReadOnlyList<MediaConversion>> RemoveWithConversionsAsync(long entryId, CancellationToken ct = default);
|
||||
|
||||
/// <summary>Entries of an account ordered by publication time, newest first (account tabs, collection pipeline).</summary>
|
||||
Task<IReadOnlyList<Entry>> ListByAccountAsync(long accountId, EntryListOptions? options = null, CancellationToken ct = default);
|
||||
|
||||
|
||||
@@ -162,6 +162,12 @@ public interface IExportStore
|
||||
|
||||
Task<ExportItem?> GetItemAsync(long itemId, CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// The first item of a library file in a job with this variant and format, any state; null when none. The frames of
|
||||
/// a video are added together in instant order, so an item's position among them is its id minus this one.
|
||||
/// </summary>
|
||||
Task<long?> FirstItemIdAsync(long runId, long mediaId, ExportVariant variant, ExportFormat format, CancellationToken ct = default);
|
||||
|
||||
/// <summary>Items of a job, by key, with an optional state.</summary>
|
||||
Task<IReadOnlyList<ExportItem>> ListItemsAsync(ExportItemQuery query, CancellationToken ct = default);
|
||||
|
||||
@@ -177,22 +183,47 @@ public interface IExportStore
|
||||
Task<IReadOnlyDictionary<long, bool>> ListAccountExportSwitchesAsync(CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// The newest Superseded or Removed row of (destination, account) whose <see cref="ExportCopy.SupersededBySha256"/> is
|
||||
/// this SHA-256: the library file that took the place of a copied one, never copied again by itself.
|
||||
/// The newest Superseded or Removed row, not a frame, of (destination, account) whose
|
||||
/// <see cref="ExportCopy.SupersededBySha256"/> is this SHA-256: the library file that took the place of a copied one,
|
||||
/// never copied again by itself (a superseded frame never makes the file «Superato»).
|
||||
/// </summary>
|
||||
Task<ExportCopy?> FindReplacedCopyAsync(long destinationId, long accountId, string sha256, CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// «Una copia sola»: the newest Copied row of this original, variant and format in a destination in use (the general
|
||||
/// folder or the own folder of an account still in Febe), of an account still in Febe; with
|
||||
/// <paramref name="exceptAccountId"/>, of an account other than that one, so a newer row of the account itself never
|
||||
/// hides the copy of another account (decision of 2026-11-27: «una copia altrove conta solo se è di un altro account»).
|
||||
/// «Una copia sola»: the newest Copied row of this original, in any form but a frame (whole or converted, decision D3
|
||||
/// of tappa E3), in a destination in use (the general folder or the own folder of an account still in Febe), of an
|
||||
/// account still in Febe; with <paramref name="exceptAccountId"/>, of an account other than that one, so a newer row
|
||||
/// of the account itself never hides the copy of another account (decision of 2026-11-27: «una copia altrove conta
|
||||
/// solo se è di un altro account»).
|
||||
/// </summary>
|
||||
Task<ExportCopy?> FindCopiedElsewhereAsync(string sha256, ExportVariant variant, ExportFormat format, long? exceptAccountId = null, CancellationToken ct = default);
|
||||
Task<ExportCopy?> FindCopiedElsewhereAsync(string sha256, long? exceptAccountId = null, CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// The state of whole copies (<see cref="ExportVariant.Whole"/>, <see cref="ExportFormat.Original"/>) of (account,
|
||||
/// SHA-256) pairs in one destination, for the plan: the current row (Copied or Failed) first, else the newest row
|
||||
/// The SHA-256 of every file written converted or as a frame in a destination (any state, any destination): an
|
||||
/// import recognises them as copies of library files (tappa E3, Q37). No index on <c>copy_sha256</c>: one read per
|
||||
/// import run, bounded by the converted copies.
|
||||
/// </summary>
|
||||
Task<IReadOnlySet<string>> LoadConvertedCopyShasAsync(CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// The current (Copied or Failed) rows of an original for an account in a destination, in any form but a frame,
|
||||
/// newest first: «già copiato» looks at the file, not at its format (decision D3 of tappa E3).
|
||||
/// </summary>
|
||||
Task<IReadOnlyList<ExportCopy>> ListCurrentCopiesAnyFormAsync(long destinationId, long accountId, string sha256, CancellationToken ct = default);
|
||||
|
||||
/// <summary>The newest row, in any state and any form but a frame, of an original for an account in a destination (D3 of tappa E3).</summary>
|
||||
Task<ExportCopy?> FindLatestCopyAnyFormAsync(long destinationId, long accountId, string sha256, CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// After a copy of an original succeeded: its other current «Non riuscito» rows in any form but a frame, for the
|
||||
/// account in the destination, are deleted (they have no file; the identity <paramref name="except"/> is kept).
|
||||
/// Returns the rows deleted.
|
||||
/// </summary>
|
||||
Task<int> ClearFailedAsync(long destinationId, long accountId, string sha256, ExportCopyIdentity except, CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// The state of the copies of (account, SHA-256) pairs in one destination, in any form but a frame (decision D3 of
|
||||
/// tappa E3), for the plan: Copied when a current row is Copied, else Failed when one is Failed, else the newest row
|
||||
/// when Removed or Superseded, else Removed or Superseded when a row was replaced by this SHA-256
|
||||
/// (<see cref="FindReplacedCopyAsync"/>). Pairs without any are absent.
|
||||
/// </summary>
|
||||
@@ -227,7 +258,7 @@ public interface IExportStore
|
||||
/// </summary>
|
||||
Task<IReadOnlyDictionary<long, ExportEntryCopies>> GetEntryCopyCountsAsync(IReadOnlyList<long> entryIds, CancellationToken ct = default);
|
||||
|
||||
/// <summary>The mark of single files («Tutte le foto»): Copied or None; files that are not due are absent.</summary>
|
||||
/// <summary>The mark of single files («Tutte le foto»): Copied, FrameOnly or None; files that are not due are absent.</summary>
|
||||
Task<IReadOnlyDictionary<long, ExportMark>> GetFileMarksAsync(IReadOnlyList<long> mediaIds, CancellationToken ct = default);
|
||||
|
||||
/// <summary>The counts of the account card: «312 su 1.204 non ancora copiati» (decision D3 of tappa E2).</summary>
|
||||
@@ -246,7 +277,8 @@ public sealed record ExportCandidate(
|
||||
long? Bytes,
|
||||
string? RelativePath,
|
||||
int Position,
|
||||
bool InHighlight);
|
||||
bool InHighlight,
|
||||
TimeSpan? Duration = null);
|
||||
|
||||
/// <summary>The copy mark of a tile (spec §4.10): «Non ancora copiato», «Copiato in parte», «Copiato».</summary>
|
||||
public enum ExportMark
|
||||
@@ -254,13 +286,21 @@ public enum ExportMark
|
||||
None,
|
||||
Partly,
|
||||
Copied,
|
||||
|
||||
/// <summary>«Solo fotogrammi»: no due file is copied, at least one has a frame copied (decision D4 of tappa E3).</summary>
|
||||
FrameOnly,
|
||||
}
|
||||
|
||||
/// <summary>The due files of an entry and how many are copied (decision D3 of tappa E2).</summary>
|
||||
public sealed record ExportEntryCopies(int Due, int Copied)
|
||||
/// <summary>
|
||||
/// The due files of an entry and how many are copied (decision D3 of tappa E2): a frame never makes a file copied; a
|
||||
/// file with only frames copied counts in <paramref name="FrameOnly"/> (decision D4 of tappa E3).
|
||||
/// </summary>
|
||||
public sealed record ExportEntryCopies(int Due, int Copied, int FrameOnly = 0)
|
||||
{
|
||||
/// <summary>«Non ancora copiato» (none), «Copiato in parte», «Copiato».</summary>
|
||||
public ExportMark Mark => Copied <= 0 ? ExportMark.None : Copied >= Due ? ExportMark.Copied : ExportMark.Partly;
|
||||
/// <summary>«Non ancora copiato» (none), «Solo fotogrammi», «Copiato in parte», «Copiato».</summary>
|
||||
public ExportMark Mark => Copied <= 0
|
||||
? FrameOnly > 0 ? ExportMark.FrameOnly : ExportMark.None
|
||||
: Copied >= Due ? ExportMark.Copied : ExportMark.Partly;
|
||||
}
|
||||
|
||||
/// <summary>Counts of the due files of an account (decision D3 of tappa E2).</summary>
|
||||
|
||||
@@ -25,9 +25,134 @@ public interface IMediaConversionStore
|
||||
/// <summary>The conversions of one library file, in creation order.</summary>
|
||||
Task<IReadOnlyList<MediaConversion>> ListByMediaAsync(long mediaId, CancellationToken ct = default);
|
||||
|
||||
/// <summary>The conversions of the files of one entry, by file and creation order.</summary>
|
||||
Task<IReadOnlyList<MediaConversion>> ListByEntryAsync(long entryId, CancellationToken ct = default);
|
||||
|
||||
/// <summary>The conversions of these library files, by file and creation order.</summary>
|
||||
Task<IReadOnlyList<MediaConversion>> ListByMediaIdsAsync(IReadOnlyCollection<long> mediaIds, CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// The paths (relative to the account folder) that conversions of the account's files record: Converted,
|
||||
/// Superseded and Removed rows (a rebuild does not count them as unknown files).
|
||||
/// </summary>
|
||||
Task<IReadOnlyList<string>> ListPathsByAccountAsync(long accountId, CancellationToken ct = default);
|
||||
|
||||
/// <summary>The conversions of the account's files that record this path (any state with a path), by key.</summary>
|
||||
Task<IReadOnlyList<MediaConversion>> FindByPathAsync(long accountId, string relativePath, CancellationToken ct = default);
|
||||
|
||||
/// <summary>Conversions whose converted file has this SHA-256 (a converted file found again is never a duplicate).</summary>
|
||||
Task<IReadOnlyList<MediaConversion>> FindBySha256Async(string sha256, CancellationToken ct = default);
|
||||
|
||||
/// <summary>The queue of the conversion, in order, by key.</summary>
|
||||
Task<IReadOnlyList<MediaConversion>> ListPendingAsync(long afterId = 0, int limit = 500, CancellationToken ct = default);
|
||||
|
||||
/// <summary>«Tolto»: these Converted or Superseded rows lost their file with their entry. Returns the rows changed.</summary>
|
||||
Task<int> MarkRemovedAsync(IReadOnlyCollection<long> ids, DateTimeOffset at, CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// A library file leaves its entry («Tieni il più grande» on a file of a series), in one transaction: the file
|
||||
/// becomes <see cref="MediaState.Deleted"/>, its queue and failures go, its rows with a file become «Tolto». Returns
|
||||
/// those rows as they were (chosen inside the transaction: their files are the caller's to delete). The state of
|
||||
/// the entry is the caller's to recompute.
|
||||
/// </summary>
|
||||
Task<IReadOnlyList<MediaConversion>> ForgetDeletedMediaAsync(long mediaId, DateTimeOffset at, CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// The account's file changed from <paramref name="oldSha256"/> to <paramref name="newSha256"/> (spec §4.10
|
||||
/// «Superato»): the conversions made from the old bytes of the account's files that now have the new ones become
|
||||
/// Superseded (their files stay); Pending and retryable Failed rows take the new SHA-256. Returns the media ids of the
|
||||
/// files concerned (to queue them again).
|
||||
/// </summary>
|
||||
Task<IReadOnlyList<long>> SupersedeAsync(long accountId, string oldSha256, string newSha256, DateTimeOffset at, CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// The setting of a format went off or changed: its queue is emptied, with its failures that «Riprova» would put
|
||||
/// back (Converted rows and their files stay, and so do the <c>AsIs*</c> verdicts). Returns how many rows went.
|
||||
/// </summary>
|
||||
Task<int> DeleteQueueAsync(ExportFormat format, CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// A change of the library formats: stores <paramref name="settings"/> (null values remove their key) and empties
|
||||
/// the queues of <paramref name="formats"/> as <see cref="DeleteQueueAsync"/> does, in one transaction, so that the
|
||||
/// formats, the keys that go with them and the queues are stored whole or not at all. Returns how many rows went.
|
||||
/// </summary>
|
||||
Task<int> SaveSettingsAndDeleteQueuesAsync(IReadOnlyDictionary<string, string?> settings, IReadOnlyCollection<ExportFormat> formats, CancellationToken ct = default);
|
||||
|
||||
/// <summary>Drops one Pending row (a file already in the format by its bytes: nothing to record). False when it is not Pending.</summary>
|
||||
Task<bool> DeletePendingRowAsync(long id, CancellationToken ct = default);
|
||||
|
||||
/// <summary>How many rows are in each state; Failed rows with an <c>AsIs*</c> code are counted apart.</summary>
|
||||
Task<MediaConversionCounts> CountByStateAsync(CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// Queues these files in these formats (Pending, <c>source_sha256</c> = the given SHA-256). A file that already has a
|
||||
/// current conversion in the format (Pending, Converted, or Failed, which holds the slot) is left as it is. Returns
|
||||
/// how many rows were added.
|
||||
/// </summary>
|
||||
Task<int> EnqueueAsync(IReadOnlyList<MediaConversionRequest> requests, DateTimeOffset at, CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// «Anche i N già in libreria»: queues, in one statement, every present library file of each kind whose extension
|
||||
/// says it converts into the format given for its kind (null: that kind is not queued). Returns how many were added.
|
||||
/// </summary>
|
||||
Task<int> EnqueueExistingAsync(ExportFormat? photo, ExportFormat? video, DateTimeOffset at, CancellationToken ct = default);
|
||||
|
||||
/// <summary>What <see cref="EnqueueExistingAsync"/> would queue: files and their bytes.</summary>
|
||||
Task<(int Files, long Bytes)> CountExistingAsync(ExportFormat? photo, ExportFormat? video, CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// Records a converted file just written (or adopted) for a Pending row, in one transaction (WP2.2 step 4): the row
|
||||
/// becomes Converted only if it is still Pending with <paramref name="sourceSha256"/> and its library file is still
|
||||
/// present with that SHA-256. Otherwise, with the file still present and unchanged, the current conversion of that
|
||||
/// file and format becomes Converted with this file, or a new row is added; with the file gone or changed nothing is
|
||||
/// recorded.
|
||||
/// </summary>
|
||||
Task<MediaConversionCommitOutcome> CommitAsync(MediaConversionCommit commit, CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// «Riprova»: Failed rows in <paramref name="formats"/> (the library formats set now) go back to Pending, except those
|
||||
/// with an <c>AsIs*</c> code (they never convert). Returns how many.
|
||||
/// </summary>
|
||||
Task<int> ResetFailedAsync(IReadOnlyCollection<ExportFormat> formats, DateTimeOffset at, CancellationToken ct = default);
|
||||
}
|
||||
|
||||
/// <summary>One file to queue in one format, made from these bytes.</summary>
|
||||
public sealed record MediaConversionRequest(long MediaId, ExportFormat Format, string SourceSha256);
|
||||
|
||||
/// <summary>The rows of the conversion for the library, by state.</summary>
|
||||
/// <param name="Pending">In the queue.</param>
|
||||
/// <param name="Converted">Converted files.</param>
|
||||
/// <param name="Failed">Failed, to try again («Riprova»).</param>
|
||||
/// <param name="AsIs">Failed for good: animated, not decodable, CMYK… («non si convertono»).</param>
|
||||
/// <param name="Superseded">Converted from bytes the library no longer has.</param>
|
||||
/// <param name="Removed">Their file went with the entry.</param>
|
||||
public sealed record MediaConversionCounts(int Pending, int Converted, int Failed, int AsIs, int Superseded, int Removed);
|
||||
|
||||
/// <summary>A converted file written for <paramref name="ConversionId"/>.</summary>
|
||||
/// <param name="ConversionId">The Pending row it was written for.</param>
|
||||
/// <param name="MediaId">Its library file.</param>
|
||||
/// <param name="Format">The format.</param>
|
||||
/// <param name="SourceSha256">The SHA-256 of the original it was made from.</param>
|
||||
/// <param name="RelativePath">Path relative to the account folder.</param>
|
||||
/// <param name="Bytes">Its size.</param>
|
||||
/// <param name="Sha256">Its SHA-256.</param>
|
||||
/// <param name="At">When it was converted.</param>
|
||||
/// <param name="Notes">What the conversion could not keep (loss codes, D19), or null.</param>
|
||||
public sealed record MediaConversionCommit(long ConversionId, long MediaId, ExportFormat Format, string SourceSha256,
|
||||
string RelativePath, long Bytes, string Sha256, DateTimeOffset At, string? Notes);
|
||||
|
||||
/// <summary>What <see cref="IMediaConversionStore.CommitAsync"/> did.</summary>
|
||||
public enum MediaConversionCommitOutcome
|
||||
{
|
||||
/// <summary>The Pending row is now Converted.</summary>
|
||||
Recorded,
|
||||
|
||||
/// <summary>The row had changed meanwhile; the file is recorded in the current row of its format, or a new one.</summary>
|
||||
Upserted,
|
||||
|
||||
/// <summary>Nothing recorded: the library file was deleted or changed meanwhile.</summary>
|
||||
SourceGone,
|
||||
|
||||
/// <summary>Nothing recorded: another converted file already holds the format of this library file.</summary>
|
||||
SlotTaken,
|
||||
}
|
||||
@@ -623,7 +623,8 @@ internal sealed class SettingsStore(FebeDatabase db) : ISettingsStore
|
||||
},
|
||||
ct);
|
||||
|
||||
private static void Set(WriteContext w, string key, string? value)
|
||||
/// <summary>Stores one value inside a write (null removes the key): also for stores that save settings with their rows.</summary>
|
||||
internal static void Set(WriteContext w, string key, string? value)
|
||||
{
|
||||
if (value is null)
|
||||
{
|
||||
|
||||