Unione di funzione/decoder-h264 in funzione/decoder-hevc (catena della 0.3.0)

Il ramo HEVC era partito da b23632f; la catena porta qui documenti e regole,
S4b, i codec di casa (C1) e il resto dell'H.264 (campi, Extended, alta
profondità, MVC, SVC, lettori ASF/FLV/MPEG). Le due serie restano intere:
- VideoFrameDecoder sceglie H.264 o HEVC come nel ramo HEVC; dell'H.264 prende
  la sola vista di base dell'MVC e i piani a 16 bit, passati al convertitore
  comune YuvToRgb (anche 4:2:2, 4:4:4 e 4:0:0) al posto del suo.
- Le foto HEIC passano dalla facciata dei codec di C1: HeifImageDecoder
  trasforma l'HeifImage in RgbaImage senza copia e irot/imir nell'orientamento,
  così ImageDecoding, miniature e impronte le trattano come le altre foto; la
  dimensione di un HEIC grande si legge dai soli box.
- decisioni.md tiene tutte le righe dei due lati (prima quelle della catena).
- Prove: entrambe le copie dei flussi di conformità H.264 e H.265 e delle
  immagini di riferimento; nei file rovinati entrano sia HEVC sia WMV/FLV/MPEG.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-25 11:34:18 +01:00
commit 14920afebf
420 files changed
+39437 -2446

No files matched your search

+33 -10
View File
@@ -18,7 +18,8 @@ internal sealed record ContentFacts(
/// <summary>
/// Reads one source file, read-only (spec §9.2): type from the content, size, SHA-256, dimensions, perceptual hash for
/// photos, date from the metadata (EXIF for photos, <c>mvhd</c> for MP4/MOV, the in-house container readers for WebM, Matroska and AVI).
/// photos, date from the metadata (EXIF for photos, <c>mvhd</c> for MP4/MOV, the in-house container readers for WebM, Matroska, AVI,
/// WMV/ASF, FLV and MPEG program streams).
/// </summary>
internal static class ContentAnalysis
{
@@ -67,7 +68,7 @@ internal static class ContentAnalysis
sha = Convert.ToHexStringLower(SHA256.HashData(bytes));
ct.ThrowIfCancellationRequested();
(width, height, hash) = Decode(() => new MemoryStream(bytes, writable: false));
(width, height, hash) = Decode(bytes);
}
else
{
@@ -80,23 +81,45 @@ internal static class ContentAnalysis
return new ContentFacts(type, length, sha, width, height, null, hash, date, null);
}
/// <summary>Size as shown and perceptual hash of a photo in memory; nulls for what Febe cannot decode (e.g. AVIF).</summary>
private static (int? Width, int? Height, ulong? Hash) Decode(byte[] bytes)
{
try
{
// The bytes are already in memory: one decode of them gives hash and size, with no copy.
var (hash, size) = PerceptualHash.ComputeWithSize(bytes);
return (size?.Width, size?.Height, hash);
}
catch (Exception ex) when (ex is OutOfMemoryException or ArgumentException or InvalidOperationException or IndexOutOfRangeException)
{
return (null, null, null);
}
}
/// <summary>
/// The same for a photo over <see cref="InMemoryLimit"/>, which the analysis does not keep for the copy: it is read once
/// more, whole (up to <see cref="ImageDecoding.MaxFileBytes"/>; the codecs need the bytes in memory), and decoded
/// once for both hash and size.
/// </summary>
private static (int? Width, int? Height, ulong? Hash) Decode(Func<Stream> open)
{
try
{
int? width = null, height = null;
byte[]? data;
using (var stream = open())
{
if (ImageDecoding.ReadSize(stream) is { } size)
{
(width, height) = size;
}
data = ImageDecoding.ReadAll(stream);
}
using var again = open();
return (width, height, PerceptualHash.Compute(again));
if (data is null)
{
return (null, null, null);
}
var (hash, size) = PerceptualHash.ComputeWithSize(data);
return (size?.Width, size?.Height, hash);
}
catch (Exception ex) when (ex is ArgumentException or InvalidOperationException or OutOfMemoryException)
catch (Exception ex) when (ex is OutOfMemoryException or ArgumentException or InvalidOperationException or IndexOutOfRangeException)
{
return (null, null, null); // a format no decoder reads (e.g. AVIF): no size, no hash
}
+4 -4
View File
@@ -517,11 +517,11 @@ public sealed class ImportCopier(ImportEnvironment env)
{
try
{
hash = PerceptualHash.ComputeFromFile(saved.FullPath);
await using var stream = File.OpenRead(saved.FullPath);
if (ImageDecoding.ReadSize(stream) is { } size)
// One read of the file gives both the perceptual hash and the size as shown.
(hash, var size) = PerceptualHash.ComputeWithSizeFromFile(saved.FullPath);
if (size is { } shown)
{
(width, height) = size;
(width, height) = shown;
}
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
+3 -2
View File
@@ -37,8 +37,9 @@ public sealed record ImportEnvironment
public VideoFrameDecoder? Frames { get; init; }
/// <summary>
/// Reader of the metadata of videos the MP4 header reader does not cover (WebM, Matroska, AVI). Null: the in-house
/// <see cref="ContainerVideoMetadataProbe"/> on the clock of this environment.
/// Reader of the metadata of videos the MP4 header reader does not cover (WebM/Matroska, AVI, WMV/ASF, FLV and MPEG
/// program streams: see <see cref="IVideoMetadataProbe"/>). Null: the in-house <see cref="ContainerVideoMetadataProbe"/>
/// on the clock of this environment.
/// </summary>
public IVideoMetadataProbe? VideoProbe { get; init; }
+4 -18
View File
@@ -1,34 +1,20 @@
using Febe.Core.Library;
using SkiaSharp;
namespace Febe.Core.Import;
/// <summary>In-memory previews of source photos for the comparison panel (nothing is written to disk).</summary>
internal static class ImportPreview
{
private const int JpegQuality = 82;
/// <summary>A JPEG of the image, upright, at most <paramref name="longSide"/> pixels; null when it cannot be decoded.</summary>
public static byte[]? RenderJpeg(Stream encodedImage, int longSide)
{
using var bitmap = ImageDecoding.DecodeUpright(encodedImage, longSide);
if (bitmap is null)
using var image = ThumbnailStore.DecodeFor(encodedImage, longSide);
if (image is null)
{
return null;
}
var scale = Math.Min(1.0, (double)longSide / Math.Max(bitmap.Width, bitmap.Height));
var width = Math.Max(1, (int)Math.Round(bitmap.Width * scale));
var height = Math.Max(1, (int)Math.Round(bitmap.Height * scale));
using var surface = SKSurface.Create(new SKImageInfo(width, height, SKColorType.Rgba8888, SKAlphaType.Premul));
surface.Canvas.Clear(SKColors.White);
using (var image = SKImage.FromBitmap(bitmap))
{
surface.Canvas.DrawImage(image, new SKRect(0, 0, width, height), new SKSamplingOptions(SKCubicResampler.Mitchell), null);
}
using var snapshot = surface.Snapshot();
using var data = snapshot.Encode(SKEncodedImageFormat.Jpeg, JpegQuality);
return data?.ToArray();
using var small = ThumbnailStore.Render(image, longSide);
return ThumbnailStore.Jpeg(small);
}
}
+12 -3
View File
@@ -22,7 +22,7 @@ var import = new ImportService(new ImportEnvironment
Thumbnails = new ThumbnailStore(data.Thumbnails),
HashIndex = sharedHashIndex, // lo stesso PerceptualHashIndex della raccolta
Frames = VideoFrameDecoder.Instance, // miniature dei video H.264 e HEVC importati, decodificate in casa
VideoProbe = new ContainerVideoMetadataProbe(clock), // metadati di WebM, Matroska e AVI (null: la stessa, predefinita)
VideoProbe = new ContainerVideoMetadataProbe(clock), // metadati di WebM, Matroska, AVI, WMV, FLV e MPEG (null: la stessa, predefinita)
SetFileTimeToPublication = settings.SetFileTimeToPublication,
Sources = isDocker ? ImportSourceOptions.Docker("/importa") : ImportSourceOptions.AnyFolder,
DataFolder = data.Root,
@@ -64,12 +64,12 @@ partenza (`DuplicateDecision.Pending`); «Fai lo stesso per gli altri» è `Deci
Per ogni file, senza scrivere nulla nella sorgente: tipo dal contenuto (`MediaSniffer`: JPEG, PNG, GIF, WebP, HEIC/HEIF,
AVIF, BMP, TIFF e raw, MP4, MOV anche senza `ftyp`, 3GP, WebM/Matroska, AVI, WMV, FLV, MPEG; l'audio M4A non è un
video), byte, SHA-256, dimensioni, impronta visiva a 64 bit per le foto, data, identificativo o codice, account
video, e nemmeno un WMA o un FLV di solo audio quando i primi 512 kB lo dimostrano: per l'FLV almeno un tag audio intero, nessun tag video e cinque secondi di audio o la fine del file), byte, SHA-256, dimensioni, impronta visiva a 64 bit per le foto, data, identificativo o codice, account
probabile, tipo probabile e titolo della raccolta.
- **Data**, nell'ordine: nome del file (o `_febe.jsonl` di una libreria di Febe, data esatta), metadati (EXIF
`DateTimeOriginal` poi `CreateDate` letti a mano in JPEG, TIFF, PNG e WebP; `mvhd` di MP4/MOV letto a mano; i lettori di
contenitori scritti in casa per WebM, Matroska e AVI), data di modifica. Se il nome dà solo il giorno e i metadati hanno un'ora
contenitori scritti in casa per WebM, Matroska, AVI, WMV/ASF, FLV e MPEG), data di modifica. Se il nome dà solo il giorno e i metadati hanno un'ora
dello stesso giorno, vince l'ora dei metadati. Le ore senza fuso sono quelle di Alberto (`IClock.LocalZone`).
- **Cartelle** (`SourceLayout`): se la cartella scelta contiene solo cartelle di tipo (post, storie, evidenza,
taggati, anni...) o solo file, è un account; altrimenti ogni sottocartella di primo livello è un'unità da associare a
@@ -159,6 +159,15 @@ virgolette quando serve, apostrofo davanti a un testo che Excel prenderebbe per
## Limiti noti
- WMV/ASF, FLV e MPEG (lettori `AsfReader`, `FlvReader`, `MpegPsReader` in `Codecs/Containers`, scritti dalle
specifiche): di un WMV si leggono le proprietà del file (data, durata senza il preroll; niente durata se è una
trasmissione), dei flussi (codec, dimensioni, audio, anche dentro l'estensione dell'intestazione), il titolo e
`WM/EncodingTime` quando manca la data; di un FLV `onMetaData` (durata, dimensioni, `creationdate`), le dimensioni
dall'SPS dell'H.264 o dall'intestazione dell'H.263 di Sorenson, e senza durata nei metadati quella fino alla fine dell'ultimo fotogramma (l'ultimo tag video più l'intervallo dal precedente; l'audio solo se non c'è video); di un MPEG
(MPEG-1 e MPEG-2, anche VOB) codec e dimensioni dall'intestazione di sequenza o dall'SPS dell'H.264 e la durata dal
primo all'ultimo tempo di presentazione, leggendo solo i primi 2 MB e l'ultimo MB. Un MPEG non ha data. La
miniatura viene solo dagli FLV H.264: WMV (VC-1) e MPEG-2 non si decodificano, e i campioni di un MPEG, spezzati nei
pacchetti PES, non si elencano, nemmeno se H.264.
- HEIC/HEIF: dimensioni, impronta e miniatura vengono dal decodificatore scritto in casa (`Febe.Core.Codecs.Heif`, sul
decodificatore HEVC): immagine singola o griglia di riquadri, `clap`, `irot`/`imir`, trasparenza. La data di scatto
si legge dall'oggetto `Exif` del box `meta` solo se sta nei primi 512 KB del file. Restano senza miniatura gli HEIF
+5 -3
View File
@@ -1,5 +1,6 @@
using System.Buffers.Binary;
using System.Text;
using Febe.Core.Codecs.Containers;
using Febe.Core.Domain;
namespace Febe.Core.Import;
@@ -17,7 +18,7 @@ public sealed record DetectedType(MediaKind Kind, string ContentType, string Ext
/// <summary>
/// Recognizes photos and videos from their first bytes, not from the extension (spec §9.2). Anything else is «Non
/// riconosciuto». Audio-only containers (M4A) are not videos.
/// riconosciuto». Audio-only containers (M4A, WMA, an FLV of audio alone) are not videos.
/// </summary>
public static class MediaSniffer
{
@@ -133,12 +134,13 @@ public static class MediaSniffer
if (head.Length >= 16 && head.StartsWith(AsfSignature))
{
return new DetectedType(MediaKind.Video, "video/x-ms-asf", ".wmv", "WMV");
// A WMA file is ASF too: only a whole header that lists audio and no video says so.
return AsfReader.IsAudioOnly(head) ? null : new DetectedType(MediaKind.Video, "video/x-ms-asf", ".wmv", "WMV");
}
if (head.StartsWith("FLV"u8) && head[3] == 0x01)
{
return new DetectedType(MediaKind.Video, "video/x-flv", ".flv", "FLV");
return FlvReader.IsAudioOnly(head) ? null : new DetectedType(MediaKind.Video, "video/x-flv", ".flv", "FLV");
}
if (head[0] == 0x00 && head[1] == 0x00 && head[2] == 0x01 && head[3] == 0xBA)
+1 -1
View File
@@ -6,7 +6,7 @@ namespace Febe.Core.Import;
/// <summary>Metadata of a video read from its container.</summary>
public sealed record VideoMetadata(DateTimeOffset? CreatedAt, TimeSpan? Duration, int? Width, int? Height);
/// <summary>Reads creation time, duration and size of a video (MP4/MOV, WebM/Matroska, AVI).</summary>
/// <summary>Reads creation time, duration and size of a video (MP4/MOV, WebM/Matroska, AVI, WMV/ASF, FLV, MPEG program stream).</summary>
public interface IVideoMetadataProbe
{
/// <summary>Metadata of a video file, read-only; null when it cannot be read.</summary>