From 704c1ed9cfad1348d0eb5f49cddfb3d4cd0e8df4 Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Fri, 27 Nov 2026 22:30:23 +0100 Subject: [PATCH] E3: conversione delle foto, rimux in MP4 e fotogrammi esatti nel nucleo MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Prima parte della tappa E3 (formati e fotogrammi), solo nel nucleo: il pianificatore, il copiatore e l'archivio delle esportazioni restano alla parte successiva. - Foto: ImageConverter.Check dice prima che cosa succede (copia identica, conversione, copia così com'è con il motivo: HEIC, AVIF, raw, animazioni, file danneggiati, CMYK e oltre 8 bit verso PNG/WEBP, oltre il limite di pixel); la conversione riporta come note ciò che non può portare invece di fermarsi, e la trasparenza verso JPG diventa bianco. I lettori segnalano animazioni, CMYK e segmenti non letti. VP8L usa un logaritmo in virgola fissa, così lo stesso file dà gli stessi byte su ogni sistema. - Video: i lettori ISO e Matroska leggono elenco dei montaggi, lingue, tipo di AAC, MP3 e i vecchi codici AAC di Matroska; Mp4Writer prepara la disposizione e ne conosce la lunghezza prima di scrivere; il nuovo Mp4Remuxer porta in MP4 senza ricodificare, sempre con gli stessi byte. - Fotogrammi: VideoFrameReader trova il campione mostrato a un istante come lo mostra il lettore, lo decodifica esatto a piena risoluzione e lo raddrizza; ExportFrames calcola istanti, suffissi e etichette. - Nomi: il suffisso del fotogramma non si accorcia mai e la numerazione dei nomi liberi viene dopo di lui; SafeFileWriter scrive anche contenuti prodotti mentre li scrive. - MediaConverter e ConversionThrottle preparano una conversione senza sapere dove andrà, una alla volta in tutto il processo. Nuove prove per determinismo, istanti, rotazione, rimux e nomi; tutte le prove di Febe.Tests passano. Co-Authored-By: Claude Opus 5.5 --- .../Codecs/Containers/ContainerReader.cs | 6 + .../Codecs/Containers/IsoBmffReader.cs | 176 ++++++++- .../Codecs/Containers/MatroskaReader.cs | 101 ++++- .../Codecs/Containers/MediaContainer.cs | 60 +++ src/Febe.Core/Codecs/Containers/Mp4Remuxer.cs | 335 +++++++++++++++++ src/Febe.Core/Codecs/Containers/Mp4Writer.cs | 256 ++++++++++--- src/Febe.Core/Codecs/H264/H264Decoder.cs | 78 ++++ .../Codecs/Images/ExifOrientation.cs | 15 + src/Febe.Core/Codecs/Images/GifDecoder.cs | 5 +- src/Febe.Core/Codecs/Images/ImageConverter.cs | 287 ++++++++++++++- src/Febe.Core/Codecs/Images/ImageMetadata.cs | 16 + src/Febe.Core/Codecs/Images/JpegFile.cs | 38 +- src/Febe.Core/Codecs/Images/PngDecoder.cs | 15 +- src/Febe.Core/Codecs/Images/Vp8LWriter.cs | 63 +++- src/Febe.Core/Codecs/Images/WebPDecoder.cs | 32 +- src/Febe.Core/Export/ExportFrames.cs | 145 ++++++++ src/Febe.Core/Export/ExportModels.cs | 16 + src/Febe.Core/Export/ExportPaths.cs | 40 +- .../Library/Conversion/ConversionThrottle.cs | 29 ++ .../Library/Conversion/MediaConverter.cs | 213 +++++++++++ src/Febe.Core/Library/SafeFileWriter.cs | 134 ++++++- src/Febe.Core/Library/VideoFrameDecoder.cs | 142 +++++-- src/Febe.Core/Library/VideoFrames.cs | 346 ++++++++++++++++++ src/Febe.Core/Library/WindowsFileNames.cs | 31 +- .../Export/ExportFrameNamesTests.cs | 122 ++++++ .../Imaging/ImageConversionTests.cs | 90 +++++ .../Febe.Tests/Library/SafeFileWriterTests.cs | 30 ++ .../Media/Containers/VideoFramesTests.cs | 153 ++++++++ 28 files changed, 2830 insertions(+), 144 deletions(-) create mode 100644 src/Febe.Core/Codecs/Containers/Mp4Remuxer.cs create mode 100644 src/Febe.Core/Export/ExportFrames.cs create mode 100644 src/Febe.Core/Library/Conversion/ConversionThrottle.cs create mode 100644 src/Febe.Core/Library/Conversion/MediaConverter.cs create mode 100644 src/Febe.Core/Library/VideoFrames.cs create mode 100644 tests/Febe.Tests/Export/ExportFrameNamesTests.cs create mode 100644 tests/Febe.Tests/Imaging/ImageConversionTests.cs create mode 100644 tests/Febe.Tests/Media/Containers/VideoFramesTests.cs diff --git a/src/Febe.Core/Codecs/Containers/ContainerReader.cs b/src/Febe.Core/Codecs/Containers/ContainerReader.cs index 6aa585d..d9607f7 100644 --- a/src/Febe.Core/Codecs/Containers/ContainerReader.cs +++ b/src/Febe.Core/Codecs/Containers/ContainerReader.cs @@ -6,6 +6,12 @@ namespace Febe.Core.Codecs.Containers; /// public static class ContainerReader { + /// + /// 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. + /// + internal static readonly DateTimeOffset AnyDate = new(9000, 1, 1, 0, 0, 0, TimeSpan.Zero); + /// The largest sample read into memory: an 8K frame of H.264 at its highest level stays far below. public const int MaxSampleSize = 64 * 1024 * 1024; diff --git a/src/Febe.Core/Codecs/Containers/IsoBmffReader.cs b/src/Febe.Core/Codecs/Containers/IsoBmffReader.cs index 822574a..ae2923b 100644 --- a/src/Febe.Core/Codecs/Containers/IsoBmffReader.cs +++ b/src/Febe.Core/Codecs/Containers/IsoBmffReader.cs @@ -39,6 +39,7 @@ public static class IsoBmffReader long position = 0; Span 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,11 @@ public static class IsoBmffReader internal byte[]? Hvcc; internal byte[]? Asc; internal long EditOffset; + internal bool HasEdits; + internal long EmptyEditMovie; + internal int EditCount; + internal string? Language; + internal int ObjectType; internal List Samples = []; internal long FragmentTime = -1; } @@ -279,6 +295,7 @@ public static class IsoBmffReader internal readonly Dictionary TrackDefaults = []; private readonly List tracks = []; private DateTimeOffset? created; + private DateTimeOffset? modified; private long timescale; private long duration; @@ -288,6 +305,12 @@ public static class IsoBmffReader /// fragment_duration of the mehd box, in movie units; 0 when absent. internal long FragmentDuration; + /// The trak boxes of the movie, of every kind. + internal int TrackCount; + + /// True when the movie has a udta or meta box. + internal bool HasUserData; + /// A fragmented movie whose headers give no duration: only its fragments tell it. internal bool NeedsFragmentsForDuration => Fragmented && duration <= 0 && FragmentDuration <= 0 && !tracks.Exists(t => t.Handler == "vide" && t.Duration > 0); @@ -295,15 +318,18 @@ public static class IsoBmffReader internal void ParseMvhd(ReadOnlySpan 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 +338,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 +399,33 @@ 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 + } + + // 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 +449,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 +531,39 @@ public static class IsoBmffReader } } + /// + /// The ISO 639-2/T code packed in an mdhd (three letters of five bits each); null for «und», for a + /// QuickTime Macintosh language code (below 0x400) or for a damaged value. + /// + private static string? Language(ReadOnlySpan field) + { + if (field.Length < 2) + { + return null; + } + + var packed = BinaryPrimitives.ReadUInt16BigEndian(field) & 0x7FFF; + if (packed < 0x400) + { + return null; + } + + Span 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 +610,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)); + } + } } } } } } - /// The DecoderSpecificInfo of an esds box (ISO/IEC 14496-1 descriptors). - private static byte[]? EsdsConfig(ReadOnlySpan body) + /// + /// The objectTypeIndication (0 when absent) and the DecoderSpecificInfo of an esds box (ISO/IEC 14496-1 + /// descriptors). + /// + private static (int ObjectType, byte[]? Config) EsdsConfig(ReadOnlySpan body) { + var objectType = 0; var p = 4; // version and flags while (p + 2 <= body.Length) { @@ -555,7 +656,7 @@ public static class IsoBmffReader { if (p + 3 > body.Length) { - return null; + return (objectType, null); } var flags = body[p + 2]; @@ -569,7 +670,7 @@ public static class IsoBmffReader { if (p >= body.Length) { - return null; + return (objectType, null); } p += 1 + body[p]; @@ -583,18 +684,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 +1009,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 +1038,10 @@ public static class IsoBmffReader AvcConfiguration = video.Avcc, HevcConfiguration = video.Hvcc, Samples = video.Samples, + EditMediaTime = video.HasEdits ? video.EditOffset : null, + EmptyEditDuration = EmptyEdit(video), + EditCount = video.EditCount, + Language = video.Language, }; } @@ -942,6 +1052,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 +1063,15 @@ 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), + EditCount = audio.EditCount, + Language = audio.Language, }; } @@ -965,7 +1082,30 @@ 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, + }; + } + + /// The leading empty edits of a track (movie units) in track units, rounded to the nearest. + 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; } /// A duration in seconds; null when it is beyond what a video can last (a damaged header). diff --git a/src/Febe.Core/Codecs/Containers/MatroskaReader.cs b/src/Febe.Core/Codecs/Containers/MatroskaReader.cs index 2493752..38af403 100644 --- a/src/Febe.Core/Codecs/Containers/MatroskaReader.cs +++ b/src/Febe.Core/Codecs/Containers/MatroskaReader.cs @@ -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 Samples = []; } @@ -509,6 +522,12 @@ public static class MatroskaReader internal TrackEntry? Video; internal TrackEntry? Audio; + /// Every TrackEntry of the file. + internal int TrackCount; + + /// True when the segment has a Tags element. + internal bool HasTags; + /// Nanoseconds of one unit of the sample times; fixed by the first block, 0 before. 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, + }; + } + + /// A three-letter ISO 639-2 language; null for «und», absent or malformed. + private static string? Language(string? code) => + code is { Length: 3 } && code != "und" && code.All(char.IsAsciiLetterLower) ? code : null; + + /// + /// 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). + /// + 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; } } diff --git a/src/Febe.Core/Codecs/Containers/MediaContainer.cs b/src/Febe.Core/Codecs/Containers/MediaContainer.cs index b1b7337..46ddcf1 100644 --- a/src/Febe.Core/Codecs/Containers/MediaContainer.cs +++ b/src/Febe.Core/Codecs/Containers/MediaContainer.cs @@ -94,6 +94,31 @@ public abstract class MediaTrack /// The four-character code or codec identifier of the container, for messages. public string CodecTag { get; init; } = string.Empty; + /// + /// 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. + /// + public long? EditMediaTime { get; init; } + + /// + /// The empty edits before the first non-empty one (a delayed start), in track units; 0 when none. A sample is shown + /// at its plus this. + /// + public long EmptyEditDuration { get; init; } + + /// The edits of the edit list after the leading empty ones (1 for an ordinary one, 0 without edit list). + public int EditCount { get; init; } + + /// The language of the track as an ISO 639-2 code («ita», «eng»); null when unknown or undetermined. + public string? Language { get; init; } + + /// + /// True when the frames of the track are stored transformed (Matroska ContentEncodings: compression, header + /// stripping, encryption): their bytes are not the codec's. + /// + public bool Encoded { get; init; } + /// Time in seconds of a value in track units. public double Seconds(long ticks) => Timescale > 0 ? (double)ticks / Timescale : 0; } @@ -143,6 +168,26 @@ public sealed class AudioTrack : MediaTrack /// The AudioSpecificConfig of an AAC track. public byte[]? AacConfiguration { get; init; } + + /// The audio object type of an AAC track (ISO/IEC 14496-3: 2 is AAC LC, 5 SBR, 29 PS); null when unknown. + public int? AudioObjectType { get; init; } + + /// The audio object type of an AudioSpecificConfig (5 bits, 31 escaping to 32 + 6 more). + 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; + } } /// What a container says: its creation time, duration and first video and audio tracks. @@ -153,6 +198,21 @@ public sealed class MediaContainer /// Creation time written in the container, when plausible. public DateTimeOffset? CreatedAt { get; init; } + /// Modification time written in the container (ISO mvhd), when plausible. + public DateTimeOffset? ModifiedAt { get; init; } + + /// The major brand of an ISO file («isom», «qt », «M4V », «3gp4»...), null for other containers or without ftyp. + public string? MajorBrand { get; init; } + + /// Tracks of every kind in the file (video, audio, timecode, subtitles...), of which only the first video and audio are read. + public int TrackCount { get; init; } + + /// + /// True when the file has metadata of its own that the readers do not interpret (ISO udta or meta + /// boxes, Matroska tags): a remux does not carry it. + /// + public bool HasUserData { get; init; } + /// Duration of the whole presentation. public TimeSpan? Duration { get; init; } diff --git a/src/Febe.Core/Codecs/Containers/Mp4Remuxer.cs b/src/Febe.Core/Codecs/Containers/Mp4Remuxer.cs new file mode 100644 index 0000000..2d00c36 --- /dev/null +++ b/src/Febe.Core/Codecs/Containers/Mp4Remuxer.cs @@ -0,0 +1,335 @@ +namespace Febe.Core.Codecs.Containers; + +/// Why a video cannot be brought into MP4 without re-encoding it (tappa E3: then it is copied as it is). +public enum RemuxRefusal +{ + /// It can. + None, + + /// Not a video Febe recognises, or a file without a video track. + NotAVideo, + + /// Already an MP4 (an ISO file with an .mp4 name and a brand other than QuickTime's): copied byte for byte. + AlreadyMp4, + + /// A container whose frames MP4 cannot take as they are (AVI, ASF, FLV, MPEG-PS, Annex B streams). + ContainerNotRemuxable, + + /// A video codec other than H.264 and HEVC. + VideoCodec, + + /// An audio codec other than AAC and MP3. + AudioCodec, + + /// A track without the configuration record of its codec. + MissingConfiguration, + + /// A Matroska track whose frames are stored transformed (ContentEncodings). + EncodedTrack, + + /// A track with more than one edit (a cut or a still segment), which the writer does not reproduce. + EditList, + + /// A video track without samples. + NoSamples, + + /// A damaged or truncated file. + Unreadable, +} + +/// +/// A remux planned by : the source as +/// read, the MP4 to write (its exact length is ) and the note codes of what it does not keep. +/// +public sealed record RemuxPlan(MediaContainer Source, Mp4Layout Layout, IReadOnlyList Losses) +{ + /// Bytes of the MP4 that writes. + public long OutputLength => Layout.Length; + + /// The stream the sample writers of read from, set by . + internal RemuxSource Reading { get; init; } = new(); +} + +/// Where the samples of a planned remux are read from while it is written. +internal sealed class RemuxSource +{ + internal Stream? Stream { get; set; } +} + +/// +/// 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 +/// moov 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). +/// +public static class Mp4Remuxer +{ + /// Note code (with «:n») of the tracks left behind: timecode, subtitles, a second audio track... + public const string LostTracks = "LostTracks"; + + /// Note code of the metadata of the source the MP4 does not carry (ISO udta/meta, Matroska tags). + public const string LostVideoMetadata = "LostVideoMetadata"; + + /// Plans the remux of a seekable without knowing its name: never . + public static RemuxRefusal Check(Stream source, out RemuxPlan? plan, CancellationToken ct) => Check(source, null, out plan, ct); + + /// + /// Plans the remux of a seekable ; (or a path) tells an MP4 + /// already (). Never throws for a bad file. + /// + 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 { 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(); + 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; + } + + /// + /// Writes the MP4 of into , reading the samples from + /// (the same file the plan was made from, seekable). is checked + /// between samples. + /// + /// A sample lies outside the file (it changed since the plan). + 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, + 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, + LastSampleDuration = LastDuration(audio), + }; + } + + /// + /// 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. + /// + 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); + } + + /// The duration of the last sample from the track's duration, when it is plausible (else the writer's default). + 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 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)); + }; + } +} diff --git a/src/Febe.Core/Codecs/Containers/Mp4Writer.cs b/src/Febe.Core/Codecs/Containers/Mp4Writer.cs index 4c3838f..4d6d9e2 100644 --- a/src/Febe.Core/Codecs/Containers/Mp4Writer.cs +++ b/src/Febe.Core/Codecs/Containers/Mp4Writer.cs @@ -41,6 +41,129 @@ public sealed class Mp4OutputTrack /// Duration of the last sample, when the times cannot tell it (0: as the one before it). public long LastSampleDuration { get; init; } + + /// The ISO 639-2/T language of the mdhd («ita»); null writes «und». + public string? Language { get; init; } + + /// + /// 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». + /// + public string? SampleEntryType { get; init; } + + /// + /// MPEG-1/2 audio layer III in an mp4a entry (objectTypeIndication 0x6B, ISO/IEC 14496-1): it has no + /// AudioSpecificConfig, so stays null. + /// + public bool IsMp3 { get; init; } + + /// + /// The media time, on the scale of , 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. + /// + public long? EditMediaTime { get; init; } + + /// A delayed start in track units: an empty edit before the media (0: none). + public long EmptyEditDuration { get; init; } +} + +/// The dates of the movie header; the modification date falls back to the creation date. +public sealed record Mp4MovieInfo(DateTimeOffset? Created, DateTimeOffset? Modified); + +/// +/// An MP4 file planned by : its exact is known before a byte is +/// written, and streams it, one sample at a time. +/// +public sealed class Mp4Layout +{ + private readonly IReadOnlyList tracks; + private readonly List<(int Track, int First, int Count)> chunks; + private readonly byte[] head; + + internal Mp4Layout(IReadOnlyList 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; + } + + /// Bytes of the whole file. + public long Length { get; } + + /// Writes the file into (from its current position). + /// A sample writer wrote another number of bytes than its size. + 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."); + } + } + + /// Counts the bytes written through it, whatever the stream below can tell. + 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 buffer) + { + inner.Write(buffer); + Count += buffer.Length; + } + + public override void WriteByte(byte value) + { + inner.WriteByte(value); + Count++; + } + } } /// @@ -57,6 +180,16 @@ public static class Mp4Writer public static void Write(Stream output, IReadOnlyList tracks, DateTimeOffset? created = null) { ArgumentNullException.ThrowIfNull(output); + Prepare(tracks, created is null ? null : new Mp4MovieInfo(created, created)).WriteTo(output); + } + + /// + /// Plans the file of : every box but the media data is built, so the length is known; + /// writes it. + /// + /// A track has no samples, no timescale or no codec configuration. + public static Mp4Layout Prepare(IReadOnlyList tracks, Mp4MovieInfo? info) + { ArgumentNullException.ThrowIfNull(tracks); if (tracks.Count == 0 || tracks.Any(t => t.Samples.Count == 0 || t.Timescale <= 0)) { @@ -65,7 +198,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 +217,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,39 +245,27 @@ public static class Mp4Writer } moov = Moov(tracks, timing, chunks, offsets, co64, time); - output.Write(ftyp); - output.Write(moov); - Span 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); } - /// Times of a track as the boxes need them. - private sealed record Timing(long[] Durations, int[] CompositionOffsets, long MediaDuration, long EditMediaTime, bool AllKey) + /// Times of a track as the boxes need them; is in track units. + private sealed record Timing(long[] Durations, int[] CompositionOffsets, long MediaDuration, long EditMediaTime, bool AllKey, long EmptyEdit) { internal static Timing Of(Mp4OutputTrack track) { @@ -180,9 +303,17 @@ 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 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; + } + + return new Timing(durations, offsets, total, editTime, allKey, empty); } } @@ -222,17 +353,17 @@ public static class Mp4Writer return box.ToArray(); } - private static byte[] Moov(IReadOnlyList tracks, Timing[] timing, List<(int Track, int First, int Count)> chunks, long[] offsets, bool co64, ulong time) + private static byte[] Moov(IReadOnlyList 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].MediaDuration - timing[t].EditMediaTime, 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 +384,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) + /// The empty edit of a track in movie units, rounded to the nearest. + 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 +430,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.MediaDuration - timing.EditMediaTime, 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 +466,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) { 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 +490,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 +536,17 @@ public static class Mp4Writer return trak; } + /// An ISO 639-2/T code packed in 15 bits (ISO/IEC 14496-12 §8.4.2.3); «und» for anything else. + 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 +698,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 +732,9 @@ 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 + config[0] = track.IsMp3 ? (byte)0x6B : (byte)0x40; // MPEG-1 audio (layer III) or MPEG-4 audio config[1] = 0x15; // audio stream decoderSpecific.CopyTo(config, 13); byte[] es = [0, 0, 0, .. Descriptor(0x04, config), .. Descriptor(0x06, [0x02])]; diff --git a/src/Febe.Core/Codecs/H264/H264Decoder.cs b/src/Febe.Core/Codecs/H264/H264Decoder.cs index f11cf98..a2687bd 100644 --- a/src/Febe.Core/Codecs/H264/H264Decoder.cs +++ b/src/Febe.Core/Codecs/H264/H264Decoder.cs @@ -216,6 +216,84 @@ public sealed partial class H264Decoder } } + /// + /// Whether the access unit carries a recovery point SEI (H.264 §D.1.8) with recovery_frame_cnt 0: 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. + /// + internal static bool HasExactRecoveryPoint(ReadOnlySpan 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) + { + return payloadSize > 0 && new RbspReader(data, Math.Min(length, p + payloadSize), p).ReadUe() == 0; + } + + p += payloadSize; + } + } + catch (H264Exception) + { + // A damaged SEI says nothing. + } + } + } + private void DecodeUnitsAnnexB(ReadOnlySpan stream) { var position = 0; diff --git a/src/Febe.Core/Codecs/Images/ExifOrientation.cs b/src/Febe.Core/Codecs/Images/ExifOrientation.cs index 762d145..ddf8d91 100644 --- a/src/Febe.Core/Codecs/Images/ExifOrientation.cs +++ b/src/Febe.Core/Codecs/Images/ExifOrientation.cs @@ -71,6 +71,21 @@ internal static class ExifOrientation return 1; } + /// + /// Whether 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. + /// + public static bool IsTiff(ReadOnlySpan 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); + } + private static ushort U16(ReadOnlySpan b, bool little) => little ? BinaryPrimitives.ReadUInt16LittleEndian(b) : BinaryPrimitives.ReadUInt16BigEndian(b); diff --git a/src/Febe.Core/Codecs/Images/GifDecoder.cs b/src/Febe.Core/Codecs/Images/GifDecoder.cs index f383eec..63c25cd 100644 --- a/src/Febe.Core/Codecs/Images/GifDecoder.cs +++ b/src/Febe.Core/Codecs/Images/GifDecoder.cs @@ -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 data, ImageLimits limits, bool countFrames) diff --git a/src/Febe.Core/Codecs/Images/ImageConverter.cs b/src/Febe.Core/Codecs/Images/ImageConverter.cs index a0c7f6a..fe15316 100644 --- a/src/Febe.Core/Codecs/Images/ImageConverter.cs +++ b/src/Febe.Core/Codecs/Images/ImageConverter.cs @@ -33,6 +33,10 @@ public sealed record ImageConversionOptions /// /// The metadata written. /// What of the source's metadata the target could not take, in Italian, for the interface. +/// +/// The same as note codes (tappa E3, ), once each, in a fixed order: what the export +/// and the library conversion record. +/// public sealed record ImageConversionResult( byte[] Data, ImageFormat Source, @@ -41,7 +45,60 @@ public sealed record ImageConversionResult( int Height, bool Lossy, ImageMetadata Metadata, - IReadOnlyList NotCarried); + IReadOnlyList NotCarried, + IReadOnlyList Losses); + +/// What a conversion does with a source (tappa E3, decisions D5 and D6). +public enum ImageConversionAction +{ + /// The source is already in the target format: it is copied byte for byte, without a note. + CopyAsIs, + + /// The source is decoded and written in the target format. + Convert, + + /// The source cannot be converted without losing what matters: it is copied as it is, with a note. + CopyOriginal, +} + +/// The outcome of . +/// What to do. +/// The format of the source by its bytes; null when it is not recognised. +/// For , why (AsIsHeif, AsIsAnimated...). +public sealed record ImageConversionCheck(ImageConversionAction Action, ImageFormat? Source, string? NoteCode); + +/// The note codes of what a conversion copies as it is or does not keep (decision D19 of tappa E3). +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"; + + /// The order in which the codes are listed, so that the same source always gives the same note. + internal static readonly string[] Order = + [ + TransparencyWhite, LostExifUnreadable, LostExifTooLarge, LostIcc, LostIccTooLarge, LostXmpTooLarge, LostExtendedXmp, + LostIptc, LostTexts, LostCommentTooLarge, LostColorChunks, LostOtherSegments, + ]; +} /// /// Turns a picture into another format with the same pixels and the same metadata, so that the converted file is @@ -57,9 +114,97 @@ public sealed record ImageConversionResult( /// public static class ImageConverter { + /// The largest source a conversion reads into memory (decision D6 of tappa E3: 512 MiB). + public const long MaxSourceBytes = 512L * 1024 * 1024; + + /// The largest picture written as WebP (decision D6 of tappa E3: about 1.1 GB of working memory). + public const long MaxWebPPixels = 40_000_000; + /// The formats a conversion can write. public static bool CanWrite(ImageFormat format) => format is ImageFormat.Jpeg or ImageFormat.Png or ImageFormat.WebP; + /// + /// What a conversion of to 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. + /// + /// The target is not JPEG, PNG or WebP. + public static ImageConversionCheck Check(ReadOnlyMemory 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 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; + return tooLarge ? ImageConversionLosses.AsIsTooLarge : null; + } + /// Converts (any format reads) to . /// The target is not JPEG, PNG or WebP. /// The source is damaged, too large or in a format Febe does not read. @@ -85,8 +230,58 @@ public static class ImageConverter lossy = true; } - var metadata = info.Metadata; + var losses = new HashSet(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)); + } + + /// + /// Writes (straight RGBA) as with what of + /// 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: is never + /// changed. + /// + /// The target is not JPEG, PNG or WebP, or a WebP side is over 16384. + 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(StringComparer.Ordinal), out _); + } + + return EncodeCore(image, target, metadata ?? ImageMetadata.Empty, options, [], new HashSet(StringComparer.Ordinal), out _); + } + + /// The codes of in the order of . + private static string[] Ordered(HashSet losses) => + [.. ImageConversionLosses.Order.Where(losses.Contains)]; + + /// Encodes; flattens in place for a JPEG target that is not opaque. + private static byte[] EncodeCore( + RgbaImage image, + ImageFormat target, + ImageMetadata metadata, + ImageConversionOptions options, + List notCarried, + HashSet 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 = null; + } + var icc = metadata.IccProfile; var iccName = metadata.IccProfileName; if (icc is not null && IccColorSpace(icc) != "RGB ") @@ -97,6 +292,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 +300,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 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 +352,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 +363,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)"); + losses.Add(ImageConversionLosses.LostExifTooLarge); exif = null; } 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(); - 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(); + var kept = new List(); + 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,16 +419,16 @@ 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; } /// The data colour space of an ICC profile (bytes 16-19 of its header: «RGB », «GRAY», «CMYK»...), or null. @@ -211,6 +457,9 @@ public static class ImageConverter /// Bytes of payload in one JPEG marker segment (65535 less the two of the length). private const int JpegMaxSegmentPayload = 65533; + /// Bytes of an ICC profile in one APP2 segment (the payload less «ICC_PROFILE\0» and the two counters). + private const int JpegIccChunk = 65519; + private static string? ValidIccName(string? name) { if (string.IsNullOrEmpty(name) || name.Length > 79) @@ -229,7 +478,7 @@ public static class ImageConverter return name.Trim().Length == name.Length ? name : null; } - private static List PngTexts(IReadOnlyList texts, List notCarried) + private static List PngTexts(IReadOnlyList texts, List notCarried, HashSet losses) { var result = new List(texts.Count); foreach (var text in texts) @@ -238,6 +487,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 +498,7 @@ public static class ImageConverter } } + /// Composites an image over a plain colour. public static class ImageBackground { diff --git a/src/Febe.Core/Codecs/Images/ImageMetadata.cs b/src/Febe.Core/Codecs/Images/ImageMetadata.cs index 571c1a0..60819a8 100644 --- a/src/Febe.Core/Codecs/Images/ImageMetadata.cs +++ b/src/Febe.Core/Codecs/Images/ImageMetadata.cs @@ -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. /// public IReadOnlyList ColorChunks { get; init; } = []; + + /// + /// 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. + /// + public IReadOnlyList Unread { get; init; } = []; } /// What a file says about its image, read without decoding the pixels. @@ -55,4 +62,13 @@ 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. /// public int BitsPerSample { get; init; } = 8; + + /// + /// Whether the file is an animation, by the presence of its marks (spec §4.10): a PNG with an acTL chunk + /// before its image data, a WebP with an ANIM or ANMF chunk, a GIF with more than one image. + /// + public bool IsAnimated { get; init; } + + /// Whether the pixels are stored as CMYK or YCCK (a JPEG with four components). + public bool IsCmyk { get; init; } } diff --git a/src/Febe.Core/Codecs/Images/JpegFile.cs b/src/Febe.Core/Codecs/Images/JpegFile.cs index a9d5698..3743233 100644 --- a/src/Febe.Core/Codecs/Images/JpegFile.cs +++ b/src/Febe.Core/Codecs/Images/JpegFile.cs @@ -76,6 +76,7 @@ internal sealed partial class JpegFile : IDisposable private string? _xmp; private List<(int Sequence, int Count, byte[] Data)>? _iccChunks; private List? _texts; + private List? _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,9 @@ 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 }; } public JpegCoefficients ToCoefficients() @@ -625,6 +627,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 +652,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 +671,22 @@ internal sealed partial class JpegFile : IDisposable (_iccChunks ??= []).Add((sequence, count, chunk.ToArray())); } } + else + { + NotRead("APP2"); // MPF and the like + } + } + + /// The namespace that starts an extended XMP APP1 segment (XMP part 3), with its terminating zero. + private static ReadOnlySpan ExtendedXmpNamespace => "http://ns.adobe.com/xmp/extension/\0"u8; + + private void NotRead(string name) + { + _unread ??= []; + if (!_unread.Contains(name)) + { + _unread.Add(name); + } } /// The namespace that starts an XMP APP1 segment, with its terminating zero. diff --git a/src/Febe.Core/Codecs/Images/PngDecoder.cs b/src/Febe.Core/Codecs/Images/PngDecoder.cs index 2fe7f0d..f69df1f 100644 --- a/src/Febe.Core/Codecs/Images/PngDecoder.cs +++ b/src/Febe.Core/Codecs/Images/PngDecoder.cs @@ -103,6 +103,8 @@ public static class PngDecoder public string? Xmp; public List? Texts; public List? ColorChunks; + public List? 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; } } diff --git a/src/Febe.Core/Codecs/Images/Vp8LWriter.cs b/src/Febe.Core/Codecs/Images/Vp8LWriter.cs index 7e67ca8..6d48ae2 100644 --- a/src/Febe.Core/Codecs/Images/Vp8LWriter.cs +++ b/src/Febe.Core/Codecs/Images/Vp8LWriter.cs @@ -576,7 +576,7 @@ internal static class Vp8LEncoder private static int ChooseCacheBits(uint[] pixels, ReadOnlySpan 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 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 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); + } + + /// Fractional bits of . + internal const int LogFractionBits = 16; + + /// Base-2 logarithms of 1-4095 in fixed point, computed once by . + 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; + } + + /// log2() in fixed point with fractional bits; 0 for 0. + internal static long Log2Fixed(ulong value) => value < (ulong)SmallLog2.Length ? SmallLog2[value] : Log2Exact(value); + + /// + /// 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. + /// + 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 diff --git a/src/Febe.Core/Codecs/Images/WebPDecoder.cs b/src/Febe.Core/Codecs/Images/WebPDecoder.cs index b96bdc6..fcf8ef1 100644 --- a/src/Febe.Core/Codecs/Images/WebPDecoder.cs +++ b/src/Febe.Core/Codecs/Images/WebPDecoder.cs @@ -96,6 +96,8 @@ public static class WebPDecoder public byte[]? Exif; public byte[]? Icc; public string? Xmp; + public bool Animated; + public List? 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; } } diff --git a/src/Febe.Core/Export/ExportFrames.cs b/src/Febe.Core/Export/ExportFrames.cs new file mode 100644 index 0000000..60fcb52 --- /dev/null +++ b/src/Febe.Core/Export/ExportFrames.cs @@ -0,0 +1,145 @@ +using System.Globalization; + +namespace Febe.Core.Export; + +/// +/// The instants, names and labels of frames (spec §4.10 «Fotogrammi», decisions D12 and D13 of tappa E3): which instants +/// a request asks for, the suffix a frame file gets, and how an instant is shown. +/// +public static class ExportFrames +{ + /// The shortest step of «Uno ogni k secondi». + public static readonly TimeSpan MinEvery = TimeSpan.FromMilliseconds(100); + + /// The most frames of «N in tutto». + public const int MaxCount = 1000; + + /// The most frames taken from one video. + public const int MaxPerVideo = 1000; + + /// The most frames of one request. + public const int MaxPerRequest = 20000; + + /// Why a request over is refused. + public const string OverCapMessage = "Più di 1.000 fotogrammi per un video: scegli un intervallo più lungo"; + + /// The suffix of the single frame of «Salva il fotogramma» (tappa E4). + public const string SingleSuffix = "_fotogramma"; + + /// How many frames asks of a video of . + public static long FrameCount(TimeSpan duration, ExportFramesRequest request) + { + ArgumentNullException.ThrowIfNull(request); + return request.Mode switch + { + FrameMode.At => 1, + FrameMode.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)), + }; + } + + /// + /// The instants asks of a video of , in increasing order. + /// Refused ( with ) over . + /// + public static IReadOnlyList 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)), + }; + } + + /// «Uno ogni k secondi»: 0, k, 2k… before (only 0 for a video without length). + public static IReadOnlyList 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] = TimeSpan.FromTicks(step.Ticks * i); + } + + return instants; + } + + /// «N in tutto»: (i + ½) · duration / N for i = 0…N − 1, in 100 ns ticks rounded down. + public static IReadOnlyList 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] = TimeSpan.FromTicks((long)(((2 * i) + 1) * length / (2 * (Int128)count))); + } + + return instants; + } + + /// + /// The suffix of a frame file, appended to the stem: _t0m12s340 (the actual instant: minutes, seconds on two + /// digits, milliseconds on three) for «Questo istante» and «Uno ogni k secondi»; _f001 (the position among + /// the instants, at least three digits) for «N in tutto». + /// + /// 0-based position of the instant in the request. + 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}"); + } + + /// + /// An instant as the viewer and the dialog show it: m:ss («0:01»), followed by a comma and the milliseconds + /// without trailing zeros only when it is not a whole second («0:01,25»). + /// + 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'); + } + + /// The identity of a frame's instant: its shown time in milliseconds, rounded up. + public static long ActualMs(TimeSpan shown) => + shown <= TimeSpan.Zero ? 0 : (shown.Ticks + TimeSpan.TicksPerMillisecond - 1) / TimeSpan.TicksPerMillisecond; + + 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); + } +} diff --git a/src/Febe.Core/Export/ExportModels.cs b/src/Febe.Core/Export/ExportModels.cs index e21e4bb..428e744 100644 --- a/src/Febe.Core/Export/ExportModels.cs +++ b/src/Febe.Core/Export/ExportModels.cs @@ -23,6 +23,22 @@ public abstract record ExportSelection public sealed record Account(long AccountId) : ExportSelection; } +/// How the instants of «Fotogrammi» are chosen (spec §4.10 «Fotogrammi»). +public enum FrameMode +{ + /// «Questo istante»: one frame at . + At, + + /// «Uno ogni k secondi»: at 0, k, 2k… before the end. + Every, + + /// «N in tutto»: N frames spread over the video, each in the middle of its share. + Count, +} + +/// A request of frames of videos, in a photo format (Jpg, Png or WebpLossless). +public sealed record ExportFramesRequest(FrameMode Mode, TimeSpan? At, TimeSpan? Every, int? Count, ExportFormat Format); + /// A «Copia in…»: what to copy, whether «Tolti» and «Superati» are copied again (D9), who asked. public sealed record ExportJobRequest(ExportSelection Selection, bool CopyAgain = false, ExportRunOrigin Origin = ExportRunOrigin.Manual); diff --git a/src/Febe.Core/Export/ExportPaths.cs b/src/Febe.Core/Export/ExportPaths.cs index d085b1f..be93271 100644 --- a/src/Febe.Core/Export/ExportPaths.cs +++ b/src/Febe.Core/Export/ExportPaths.cs @@ -4,6 +4,12 @@ using Febe.Core.Library; namespace Febe.Core.Export; +/// +/// 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. +/// +public sealed record ExportNameOptions(string? Extension, string? Suffix); + /// Paths and content types of the export (spec §4.10). 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; } + /// The last segment with the suffix appended to its stem and the extension of . + private static IReadOnlyList Renamed(IReadOnlyList 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]; + } + /// The relative path ('/' separated) of a copy: the segments fitted to the length limit under the root. + /// The destination. + /// The segments of . + /// The longest full path. + /// The frame suffix of the file name, never cut by the shortening. /// Even shortened, the path does not fit. - public static string RelativePathFor(ExportDestination d, IReadOnlyList segments, int maxPath = WindowsFileNames.MaxPathLength) + public static string RelativePathFor(ExportDestination d, IReadOnlyList 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)); } /// /// The name the safe writer gives a file at its -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 + /// (a frame suffix, ) the number comes after + /// it and both survive the shortening: «x_f001 (2).png». /// - 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)); } /// The scheme that names an entry kind. diff --git a/src/Febe.Core/Library/Conversion/ConversionThrottle.cs b/src/Febe.Core/Library/Conversion/ConversionThrottle.cs new file mode 100644 index 0000000..6a41961 --- /dev/null +++ b/src/Febe.Core/Library/Conversion/ConversionThrottle.cs @@ -0,0 +1,29 @@ +namespace Febe.Core.Library.Conversion; + +/// +/// 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. +/// +public sealed class ConversionThrottle +{ + private readonly SemaphoreSlim gate = new(1, 1); + + /// The throttle every conversion of the process shares. + public static ConversionThrottle Shared { get; } = new(); + + /// Runs on the thread pool once no other conversion runs. + public async Task RunAsync(Func 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(); + } + } +} diff --git a/src/Febe.Core/Library/Conversion/MediaConverter.cs b/src/Febe.Core/Library/Conversion/MediaConverter.cs new file mode 100644 index 0000000..7f3d36f --- /dev/null +++ b/src/Febe.Core/Library/Conversion/MediaConverter.cs @@ -0,0 +1,213 @@ +using System.Security.Cryptography; +using Febe.Core.Codecs.Containers; +using Febe.Core.Codecs.Images; +using Febe.Core.Domain; + +namespace Febe.Core.Library.Conversion; + +/// +/// 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. +/// +/// (the file byte for byte) or . +/// The effective format: for a whole file. +/// The extension of the file written, with its dot («.jpg»; a whole file keeps its own). +/// The bytes writes. +/// +/// The SHA-256 (lowercase hex) of what writes; null for a remux, known once written. +/// +/// Note codes: why the file is copied as it is, or what the conversion could not carry. +/// Writes the file into the stream given. +public sealed record MediaConversionResult(ExportVariant Variant, ExportFormat Format, string Extension, + long Length, string? Sha256, IReadOnlyList Notes, Func Produce) : IDisposable +{ + /// The note prefix of a video that cannot be remuxed; the follows the colon. + public const string AsIsNotRemuxable = "AsIsNotRemuxable"; + + /// Converted bytes or a remux plan, released on . + internal object? Held { get; set; } + + /// + public void Dispose() => Held = null; +} + +/// +/// 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 , videos are remuxed into MP4 while being +/// written. The source is never changed. +/// +public static class MediaConverter +{ + /// The raw camera formats, copied as they are (spec §4.10). + private static readonly HashSet RawExtensions = new(StringComparer.OrdinalIgnoreCase) + { + ".dng", ".cr2", ".cr3", ".nef", ".arw", ".raf", ".orf", ".rw2", ".pef", ".srw", + }; + + /// + /// Prepares (only its name is used) in . + /// opens the source for reading, seekable; it may be called more than once. + /// + /// A photo's bytes do not have . + /// The target does not belong to the kind of file. + public static async Task PrepareAsync(Func 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); + } + + /// The image format written for an export format; null for Original and MP4. + public static ImageFormat? ImageFormatOf(ExportFormat format) => format switch + { + ExportFormat.Jpg => ImageFormat.Jpeg, + ExportFormat.Png => ImageFormat.Png, + ExportFormat.WebpLossless => ImageFormat.WebP, + _ => null, + }; + + /// The extension of a converted file, with its dot. + 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 PreparePhotoAsync(Func 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 = await throttle.RunAsync(token => + { + token.ThrowIfCancellationRequested(); + try + { + return ImageConverter.Convert(bytes, format); + } + catch (ImageLimitException) + { + return null; + } + catch (ImageDecodeException) + { + return null; + } + }, ct).ConfigureAwait(false); + if (converted is null) + { + return Whole(bytes, extension, sha, [ImageConversionLosses.AsIsNotDecodable]); + } + + 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 PrepareVideoAsync(Func 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); + } + + /// A whole file streamed from the source (a video, or a photo not read into memory). + private static MediaConversionResult Whole(Func open, string extension, long length, string sha, IReadOnlyList 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); + }); + + /// A whole photo from the bytes already read and checked. + private static MediaConversionResult Whole(byte[] bytes, string extension, string sha, IReadOnlyList notes) => + new(ExportVariant.Whole, ExportFormat.Original, extension, bytes.Length, sha, notes, Writer(bytes)) { Held = bytes }; + + private static Func Writer(byte[] data) => + (output, token) => output.WriteAsync(data, token).AsTask(); +} diff --git a/src/Febe.Core/Library/SafeFileWriter.cs b/src/Febe.Core/Library/SafeFileWriter.cs index 244e9f9..9455414 100644 --- a/src/Febe.Core/Library/SafeFileWriter.cs +++ b/src/Febe.Core/Library/SafeFileWriter.cs @@ -42,6 +42,12 @@ public sealed record SafeWriteOptions /// is removed and an says so. /// public bool VerifyFromDisk { get; init; } + + /// + /// 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 ExportPaths.NumberedName gives it. + /// + public string? KeepSuffix { get; init; } } /// The content exceeded ; nothing was kept. @@ -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); + } + + /// + /// As , + /// for content that is made while it is written (a converted photo, a remuxed video, a frame): + /// writes it into the temporary file, through a stream that hashes and counts it (and honours + /// and ); then the same checks, + /// and the free-name rename. Our own temporary file is removed on any failure. + /// + public async Task SaveAsync( + Func produce, + string rootFolder, + string tempDirectory, + Func> 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 SaveCoreAsync( + Func> write, + string rootFolder, + string tempDirectory, + Func> 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 ProduceTempAsync(Func 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(); + } + + /// A write-only stream that hashes and counts what goes through it into the temporary file. + 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 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 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 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); + } + } + /// Reads the temporary file back and compares its SHA-256 with the one computed while writing. 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)!); diff --git a/src/Febe.Core/Library/VideoFrameDecoder.cs b/src/Febe.Core/Library/VideoFrameDecoder.cs index 261bfcf..93e26e4 100644 --- a/src/Febe.Core/Library/VideoFrameDecoder.cs +++ b/src/Febe.Core/Library/VideoFrameDecoder.cs @@ -58,7 +58,7 @@ public sealed record VideoStillness(bool IsStill, int SampledFrames, double Diff /// (, ). Videos in other codecs (VP9, AV1, ...) give no frame: the /// interface shows the neutral tile. /// -public sealed class VideoFrameDecoder +public sealed partial class VideoFrameDecoder { /// Differences up to this value (0–255) count as compression noise of a still picture. public const double StillThreshold = 3.0; @@ -77,8 +77,6 @@ public sealed class VideoFrameDecoder /// How far back from a sample flagged as key the decoder looks for one it can really start from. 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 /// Exact: an H.264 IDR picture, an HEVC IDR or BLA picture. Idr, + + /// + /// 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 + /// . + /// + Recovery, } /// Size of the NAL length fields of the samples (0: Annex B), from the configuration record. @@ -436,9 +441,11 @@ public sealed class VideoFrameDecoder /// /// Decodes chosen samples, each from the random access point before it, reusing a run when the targets share it. /// - 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 found = []; + private readonly HashSet produced = []; + private readonly List<(int Sample, Frame Frame)> pending = []; private readonly HashSet wanted = []; private readonly int[] keys = KeyIndices(video); private readonly Dictionary accessPoints = []; @@ -458,6 +465,11 @@ public sealed class VideoFrameDecoder /// 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; } + /// + /// The nearest start from which comes out exact, however far: an IDR picture, or a + /// recovery point shown no later than it; otherwise the first sample. + /// + private int ExactStart(int index) + { + 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 Decode(int[] targets, CancellationToken ct) + /// + /// Decodes the targets (sample indices in ascending order) and keeps every frame: the few a thumbnail or a + /// stillness check asks for. + /// + internal Dictionary DecodeAll(int[] targets, CancellationToken ct) + { + foreach (var (sample, frame) in Decode(targets, ct)) + { + found.TryAdd(sample, frame); + } + + return found; + } + + /// + /// 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. + /// + 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; + /// Decodes one sample; false when the stream is damaged there. + 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)); + } } } diff --git a/src/Febe.Core/Library/VideoFrames.cs b/src/Febe.Core/Library/VideoFrames.cs new file mode 100644 index 0000000..67ec46c --- /dev/null +++ b/src/Febe.Core/Library/VideoFrames.cs @@ -0,0 +1,346 @@ +using Febe.Core.Codecs; +using Febe.Core.Codecs.Containers; +using Febe.Core.Codecs.Images; +using YuvToRgb = Febe.Core.Codecs.YuvToRgb; + +namespace Febe.Core.Library; + +/// What found about a video. +/// False when no frame can be taken from it: says why. +/// The Italian message shown when frames are not available; null otherwise. +/// The presentation length (zero when unknown). +/// Width of a frame as shown (rotation applied). +/// Height of a frame as shown (rotation applied). +/// Clockwise rotation of the track: 0, 90, 180 or 270. +/// The video codec («H264», «Hevc»), or the container's codec tag of one Febe does not decode. +/// The mean time between two frames (zero when unknown). +/// Whether the container has an audio track. +/// Samples of the video track. +public sealed record VideoFrameInfo(bool Available, string? Unavailable, TimeSpan Duration, int Width, int Height, + int Rotation, string Codec, TimeSpan FrameDuration, bool HasAudio, int SampleCount); + +/// A frame to take: the instant asked for and the sample really shown then (spec §4.10 «Fotogrammi»). +/// Position of the instant in the request (0-based), which names the file. +/// The instant asked for. +/// +/// When the sample is shown, rounded up to the next 100 ns tick: what the frame's identity and name carry. +/// +/// The sample index in decoding order. +public sealed record VideoFrameTarget(int Index, TimeSpan Requested, TimeSpan Actual, int Sample); + +/// A decoded frame, upright, in 8-bit RGBA (alpha 255). Dispose it to give the pixels back. +public sealed class VideoFrame(int index, TimeSpan requested, TimeSpan actual, RgbaImage image) : IDisposable +{ + /// Position of the instant in the request. + public int Index { get; } = index; + + /// The instant asked for. + public TimeSpan Requested { get; } = requested; + + /// When the frame is shown. + public TimeSpan Actual { get; } = actual; + + /// The pixels, rotated as the video is shown. + public RgbaImage Image { get; } = image; + + /// + public void Dispose() => Image.Dispose(); +} + +/// +/// 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. +/// +public sealed class VideoFrameReader : IDisposable +{ + /// The message for a video whose frames Febe cannot take. + public const string NotAvailableMessage = "Fotogramma non disponibile per questo video"; + + private readonly Stream? stream; + private readonly VideoTrack? video; + + /// Shown time of each sample in track units (presentation time plus the empty edits). + private readonly long[] shown = []; + + /// The samples that can be chosen, by shown time then decoding order. + 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 (cut by the edit list) are not chosen, unless nothing else is. + var visible = Enumerable.Range(0, samples.Count).Where(i => shown[i] >= 0).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)); + } + + /// + /// Opens the video in (left open: the caller disposes it after the reader). Never + /// throws for a video it cannot read: is then not available, and the reader gives no frame. + /// + 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; + } + + /// The length of the video from its headers only (no sample table walked through); null when unreadable. + 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; + } + } + + /// + /// 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. + /// + public IReadOnlyList Locate(IReadOnlyList 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; + } + + /// + /// 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. + /// + public IEnumerable Decode(IReadOnlyList targets, CancellationToken ct) + { + ArgumentNullException.ThrowIfNull(targets); + return video is null || stream is null || targets.Count == 0 ? [] : DecodeCore(targets, ct); + } + + private IEnumerable DecodeCore(IReadOnlyList 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); + } + } + } + + /// + 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]; + } + + /// The shown time of a sample as a TimeSpan, rounded up to the tick (never before it is shown). + 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; +} + +/// The frames part of the decoder: what needs of its private machinery. +public sealed partial class VideoFrameDecoder +{ + /// The track frames can be taken from: H.264 or HEVC with its samples and configuration; else null. + 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; + + /// Whether an exception while reading a video means a file that cannot be read (not a bug). + internal static bool IsUnreadableFile(Exception ex) => IsUnreadable(ex); + + /// + /// 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. + /// + 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)); + } + } + + /// A frame at full size in RGBA (alpha 255), brought to 8 bits, then turned as the video is shown. + 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(in YuvPlanes planes, int matrix, bool fullRange) + where T : unmanaged, System.Numerics.IBinaryInteger + { + 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; + } +} diff --git a/src/Febe.Core/Library/WindowsFileNames.cs b/src/Febe.Core/Library/WindowsFileNames.cs index 24ea67b..53c6438 100644 --- a/src/Febe.Core/Library/WindowsFileNames.cs +++ b/src/Febe.Core/Library/WindowsFileNames.cs @@ -89,8 +89,15 @@ public static class WindowsFileNames /// keeping its extension; then the longest folder segments. A shortened part ends with ~ and eight hex digits /// of the SHA-256 of the original, so different names stay different (for example _1 and _2). /// + /// The folder the path is below. + /// The segments. + /// The longest full path. + /// + /// 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. + /// /// Even shortened, the path does not fit (the base folder is too long). - public static IReadOnlyList FitPath(string baseFolder, IReadOnlyList segments, int maxLength = MaxPathLength) + public static IReadOnlyList FitPath(string baseFolder, IReadOnlyList 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..]); } - /// Shortens a name to at most characters with a hash suffix of the original. - private static string Shorten(string name, int maxLength, bool keepExtension) + /// + /// The stem and the end that is kept of a file name: the extension, preceded by when + /// the stem ends with it. + /// + 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); + } + + /// Shortens a name to at most characters with a hash suffix of the original. + 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) { diff --git a/tests/Febe.Tests/Export/ExportFrameNamesTests.cs b/tests/Febe.Tests/Export/ExportFrameNamesTests.cs new file mode 100644 index 0000000..db03fcf --- /dev/null +++ b/tests/Febe.Tests/Export/ExportFrameNamesTests.cs @@ -0,0 +1,122 @@ +using System.Security.Cryptography; +using Febe.Core.Codecs.Images; +using Febe.Core.Domain; +using Febe.Core.Export; +using Febe.Core.Library; +using Febe.Core.Library.Conversion; +using Febe.Tests.Codecs.Containers; + +namespace Febe.Tests.Export; + +/// +/// Instants, suffixes and labels of frames (tappa E3, D12 and D13), the protected suffix of the shortening and of the +/// numbered names (WP1.8), and the environment-free media conversion (WP1.6b). +/// +[TestClass] +public sealed class ExportFrameNamesTests +{ + [TestMethod] + public void EveryKSecondsStartsAtZeroAndStopsBeforeTheEnd() + { + var instants = ExportFrames.Every(TimeSpan.FromSeconds(2), TimeSpan.FromMilliseconds(500)); + + CollectionAssert.AreEqual( + new[] { 0, 500, 1000, 1500 }.Select(ms => TimeSpan.FromMilliseconds(ms)).ToArray(), + instants.ToArray()); + Assert.ThrowsExactly(() => ExportFrames.Every(TimeSpan.FromSeconds(2), TimeSpan.FromMilliseconds(50))); + var over = Assert.ThrowsExactly(() => ExportFrames.Every(TimeSpan.FromHours(1), TimeSpan.FromSeconds(1))); + StringAssert.StartsWith(over.Message, ExportFrames.OverCapMessage); + } + + [TestMethod] + public void NInAllAreCentred() + { + var instants = ExportFrames.Spread(TimeSpan.FromSeconds(4), 4); + + CollectionAssert.AreEqual( + new[] { 500, 1500, 2500, 3500 }.Select(ms => TimeSpan.FromMilliseconds(ms)).ToArray(), + instants.ToArray()); + Assert.ThrowsExactly(() => ExportFrames.Spread(TimeSpan.FromSeconds(4), 1001)); + } + + [TestMethod] + public void SuffixesAndLabels() + { + var actual = TimeSpan.FromTicks((12_340 * TimeSpan.TicksPerMillisecond) - 3); // rounded up to 12.340 s + + Assert.AreEqual("_t0m12s340", ExportFrames.Suffix(FrameMode.At, actual, 0, 1)); + Assert.AreEqual("_t1m05s000", ExportFrames.Suffix(FrameMode.Every, TimeSpan.FromSeconds(65), 3, 9)); + Assert.AreEqual("_f001", ExportFrames.Suffix(FrameMode.Count, actual, 0, 12)); + Assert.AreEqual("_f0042", ExportFrames.Suffix(FrameMode.Count, actual, 41, 1000)); + Assert.AreEqual("0:01", ExportFrames.Label(TimeSpan.FromSeconds(1))); + Assert.AreEqual("0:01,25", ExportFrames.Label(TimeSpan.FromMilliseconds(1250))); + Assert.AreEqual("2:03,007", ExportFrames.Label(TimeSpan.FromMilliseconds(123_007))); + } + + [TestMethod] + public void AKeptSuffixIsNotCutAndNumberingComesAfterIt() + { + var root = "/destinazione/" + new string('d', 120); + var name = new string('n', 200) + "_t0m12s340.png"; + + var fitted = WindowsFileNames.FitPath(root, ["post", name], keepSuffix: "_t0m12s340"); + Assert.EndsWith("_t0m12s340.png", fitted[^1]); + Assert.IsLessThanOrEqualTo(WindowsFileNames.MaxPathLength, root.Length + fitted.Sum(s => s.Length + 1)); + CollectionAssert.AreEqual( + WindowsFileNames.FitPath(root, ["post", name]).ToArray(), + WindowsFileNames.FitPath(root, ["post", name], keepSuffix: null).ToArray(), + "Senza suffisso nulla cambia."); + + var numbered = ExportPaths.NumberedName(root, "post/" + name, 2, keepSuffix: "_t0m12s340"); + Assert.EndsWith("_t0m12s340 (2).png", numbered); + Assert.AreEqual("post/a_f001 (3).png", ExportPaths.NumberedName("/d", "post/a_f001.png", 3, keepSuffix: "_f001")); + } + + [TestMethod] + public async Task APhotoIsConvertedWithItsShaAndAChangedSourceIsRefused() + { + using var picture = Imaging.TestImages.Gradient(40, 30, seed: 5); + var png = ImageConverter.Encode(picture, ImageFormat.Png, null); + var sha = Convert.ToHexStringLower(SHA256.HashData(png)); + + using var jpg = await MediaConverter.PrepareAsync(() => new MemoryStream(png), "a/b.png", MediaKind.Photo, + ExportFormat.Jpg, sha, new ConversionThrottle(), CancellationToken.None); + using var output = new MemoryStream(); + await jpg.Produce(output, CancellationToken.None); + + Assert.AreEqual(ExportVariant.Converted, jpg.Variant); + Assert.AreEqual(".jpg", jpg.Extension); + Assert.AreEqual(jpg.Length, output.Length); + Assert.AreEqual(jpg.Sha256, Convert.ToHexStringLower(SHA256.HashData(output.ToArray()))); + CollectionAssert.Contains(jpg.Notes.ToList(), ImageConversionLosses.TransparencyWhite); + + using var same = await MediaConverter.PrepareAsync(() => new MemoryStream(png), "a/b.png", MediaKind.Photo, + ExportFormat.Png, sha, ConversionThrottle.Shared, CancellationToken.None); + Assert.AreEqual((ExportVariant.Whole, ExportFormat.Original, sha, ".png"), (same.Variant, same.Format, same.Sha256, same.Extension)); + + await Assert.ThrowsExactlyAsync(() => MediaConverter.PrepareAsync(() => new MemoryStream(png), + "a/b.png", MediaKind.Photo, ExportFormat.Jpg, new string('0', 64), ConversionThrottle.Shared, CancellationToken.None)); + } + + [TestMethod] + public async Task AVideoIsRemuxedOrCopiedWithTheReason() + { + var es = ElementaryStream.Load("BA1_Sony_D"); + var mkv = TestVideos.Matroska(es); + var sha = Convert.ToHexStringLower(SHA256.HashData(mkv)); + + using var remux = await MediaConverter.PrepareAsync(() => new MemoryStream(mkv), "v.mkv", MediaKind.Video, + ExportFormat.Mp4, sha, ConversionThrottle.Shared, CancellationToken.None); + using var output = new MemoryStream(); + await remux.Produce(output, CancellationToken.None); + Assert.AreEqual((ExportVariant.Converted, ".mp4", (string?)null), (remux.Variant, remux.Extension, remux.Sha256)); + Assert.AreEqual(remux.Length, output.Length); + + var garbage = new byte[2048]; + using var asIs = await MediaConverter.PrepareAsync(() => new MemoryStream(garbage), "v.mov", MediaKind.Video, + ExportFormat.Mp4, sha, ConversionThrottle.Shared, CancellationToken.None); + Assert.AreEqual(ExportVariant.Whole, asIs.Variant); + Assert.HasCount(1, asIs.Notes); + StringAssert.StartsWith(asIs.Notes[0], MediaConversionResult.AsIsNotRemuxable + ":"); + } +} diff --git a/tests/Febe.Tests/Imaging/ImageConversionTests.cs b/tests/Febe.Tests/Imaging/ImageConversionTests.cs new file mode 100644 index 0000000..119a6d1 --- /dev/null +++ b/tests/Febe.Tests/Imaging/ImageConversionTests.cs @@ -0,0 +1,90 @@ +using System.Security.Cryptography; +using Febe.Core.Codecs.Images; +using static Febe.Tests.Imaging.TestImages; + +namespace Febe.Tests.Imaging; + +/// +/// The photo conversion of tappa E3: what is copied as it is and why (D5, D6), what a conversion reports instead of +/// throwing, and that converting the same picture twice gives the same bytes (D9). +/// +[TestClass] +public sealed class ImageConversionTests +{ + private static readonly byte[] Palette4 = [0, 0, 0, 255, 0, 0, 0, 255, 0, 0, 0, 255]; + + [TestMethod] + [DataRow(ImageFormat.Jpeg)] + [DataRow(ImageFormat.Png)] + [DataRow(ImageFormat.WebP)] + public void ConvertingTwiceGivesTheSameBytes(ImageFormat target) + { + using var picture = Gradient(97, 61, seed: 7); + var source = ImageConverter.Encode(picture, target == ImageFormat.Png ? ImageFormat.Jpeg : ImageFormat.Png, null); + + var first = ImageConverter.Convert(source, target); + var second = ImageConverter.Convert(source, target); + + Assert.AreEqual(target, ImageFormatSniffer.Detect(first.Data)); + CollectionAssert.AreEqual(SHA256.HashData(first.Data), SHA256.HashData(second.Data)); + Assert.AreEqual(target == ImageFormat.Jpeg, first.Lossy); + } + + [TestMethod] + public void WebpCostsUseNoFloatingPointLog() + { + // The fixed-point log2 of the VP8L cost estimates is exact on powers of two and monotonic. + var previous = -1L; + for (ulong v = 1; v < 70_000; v += 13) + { + var log = Vp8LEncoder.Log2Fixed(v); + Assert.IsGreaterThanOrEqualTo(previous, log); + previous = log; + } + + Assert.AreEqual(10L << 16, Vp8LEncoder.Log2Fixed(1024)); + Assert.AreEqual(20L << 16, Vp8LEncoder.Log2Fixed(1UL << 20)); + Assert.AreEqual(0L, Vp8LEncoder.Log2Fixed(1)); + } + + [TestMethod] + public void TheSameFormatIsCopiedAsItIs() + { + using var picture = Gradient(16, 16, seed: 3); + var png = ImageConverter.Encode(picture, ImageFormat.Png, null); + + var check = ImageConverter.Check(png, ImageFormat.Png); + + Assert.AreEqual(ImageConversionAction.CopyAsIs, check.Action); + Assert.IsNull(check.NoteCode); + Assert.AreEqual(ImageConversionAction.Convert, ImageConverter.Check(png, ImageFormat.Jpeg).Action); + } + + [TestMethod] + public void AnimationsAndDamagedFilesAreCopiedWithTheirReason() + { + byte[] indices = [0, 1]; + var animated = Gif(2, 1, Palette4, GifFrame(0, 0, 2, 1, indices, 2), GifControl(1), GifFrame(0, 0, 2, 1, indices, 2)); + var still = Gif(2, 1, Palette4, GifFrame(0, 0, 2, 1, indices, 2)); + + Assert.AreEqual(ImageConversionLosses.AsIsAnimated, ImageConverter.Check(animated, ImageFormat.Png).NoteCode); + Assert.AreEqual(ImageConversionAction.Convert, ImageConverter.Check(still, ImageFormat.Png).Action); + var damaged = ImageConverter.Check(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 }, ImageFormat.Jpeg); + Assert.AreEqual(ImageConversionAction.CopyOriginal, damaged.Action); + Assert.AreEqual(ImageConversionLosses.AsIsNotDecodable, damaged.NoteCode); + } + + [TestMethod] + public void TransparencyToJpgIsAnnouncedAndTheImageIsLeftAlone() + { + using var picture = Random(8, 8, seed: 11); + var before = picture.ToArray(); + var png = ImageConverter.Encode(picture, ImageFormat.Png, null); + + var result = ImageConverter.Convert(png, ImageFormat.Jpeg); + _ = ImageConverter.Encode(picture, ImageFormat.Jpeg, null); + + CollectionAssert.Contains(result.Losses.ToList(), ImageConversionLosses.TransparencyWhite); + CollectionAssert.AreEqual(before, picture.ToArray(), "Encode lavora su una copia."); + } +} diff --git a/tests/Febe.Tests/Library/SafeFileWriterTests.cs b/tests/Febe.Tests/Library/SafeFileWriterTests.cs index 57a5a84..6ff8dcc 100644 --- a/tests/Febe.Tests/Library/SafeFileWriterTests.cs +++ b/tests/Febe.Tests/Library/SafeFileWriterTests.cs @@ -14,6 +14,36 @@ public sealed class SafeFileWriterTests return bytes; } + [TestMethod] + public async Task ProducedContentIsHashedAndATakenNameIsNumberedAfterTheKeptSuffix() + { + using var temp = new TempFolder(); + var content = Content(3000, 7); + Directory.CreateDirectory(Path.Combine(temp.Path, "post")); + File.WriteAllBytes(Path.Combine(temp.Path, "post", "a_f001.png"), [1, 2, 3]); + var tempDirectory = Path.Combine(temp.Path, ".tmp"); + Directory.CreateDirectory(tempDirectory); + FileDigest? seen = null; + + var saved = await new SafeFileWriter().SaveAsync( + (output, token) => output.WriteAsync(content, token).AsTask(), + temp.Path, + tempDirectory, + (digest, _) => + { + seen = digest; + return ValueTask.FromResult("post/a_f001.png"); + }, + new SafeWriteOptions { KeepSuffix = "_f001" }); + + Assert.IsNotNull(saved); + Assert.AreEqual(Convert.ToHexStringLower(SHA256.HashData(content)), seen!.Value.Sha256); + Assert.AreEqual(3000L, seen.Value.Bytes); + Assert.AreEqual("post/a_f001 (2).png", saved.RelativePath); + CollectionAssert.AreEqual(new byte[] { 1, 2, 3 }, File.ReadAllBytes(Path.Combine(temp.Path, "post", "a_f001.png")), "Il file che c'era non è toccato."); + CollectionAssert.AreEqual(content, File.ReadAllBytes(saved.FullPath)); + } + [TestMethod] public async Task WritesTheFileWithItsHashAndPublicationTime() { diff --git a/tests/Febe.Tests/Media/Containers/VideoFramesTests.cs b/tests/Febe.Tests/Media/Containers/VideoFramesTests.cs new file mode 100644 index 0000000..6f77033 --- /dev/null +++ b/tests/Febe.Tests/Media/Containers/VideoFramesTests.cs @@ -0,0 +1,153 @@ +using System.Security.Cryptography; +using Febe.Core.Codecs.Containers; +using Febe.Core.Codecs.H264; +using Febe.Core.Export; +using Febe.Core.Library; + +namespace Febe.Tests.Codecs.Containers; + +/// +/// Frames at chosen instants (tappa E3, D12): the sample shown at an instant, exact decoding at full size, rotation, +/// and the remux into MP4 (D9: the same bytes every time). +/// +[TestClass] +public sealed class VideoFramesTests +{ + [TestMethod] + [DataRow("mp4")] + [DataRow("mkv")] + public void TheFrameAtAnInstantIsTheOneShown(string kind) + { + var es = ElementaryStream.Load("CABA3_SVA_B"); + var data = kind == "mkv" ? TestVideos.Matroska(es) : TestVideos.Mp4(es); + using var stream = new MemoryStream(data); + using var reader = VideoFrameReader.Open(stream, out var info); + Assert.IsTrue(info.Available); + Assert.AreEqual((es.Width, es.Height), (info.Width, info.Height)); + + // 30 frames per second: 0.51 s shows frame 15 (shown at 0.5 s), 0.499 s still frame 14. The Matroska file starts + // showing later by the reordering delay of its B frames (its block times are presentation times as written). + var shift = kind == "mkv" ? Enumerable.Range(0, es.Count).Max(i => i - es.Rank[i]) : 0; + var targets = reader.Locate([TimeSpan.FromMilliseconds(510), TimeSpan.FromMilliseconds(499)]); + Assert.AreEqual(TimeSpan.FromMilliseconds(500), targets[0].Actual); + Assert.AreEqual(500L, ExportFrames.ActualMs(targets[0].Actual)); + Assert.IsLessThan(TimeSpan.FromMilliseconds(500), targets[1].Actual); + + var frames = reader.Decode(targets, CancellationToken.None).ToList(); + try + { + Assert.HasCount(2, frames); + foreach (var (frame, rank) in new[] { (frames.Single(f => f.Index == 0), 15 - shift), (frames.Single(f => f.Index == 1), 14 - shift) }) + { + var expected = VideoFrameDecoder.ToImage(ShownFrame(es, rank), 0, 0); + Assert.AreEqual((expected.Width, expected.Height), (frame.Image.Width, frame.Image.Height)); + var pixels = frame.Image.ToArray(); + for (var i = 0; i < expected.Width * expected.Height; i++) + { + Assert.AreEqual(expected.Rgb[i * 3], pixels[i * 4]); + Assert.AreEqual(expected.Rgb[(i * 3) + 1], pixels[(i * 4) + 1]); + Assert.AreEqual(expected.Rgb[(i * 3) + 2], pixels[(i * 4) + 2]); + Assert.AreEqual((byte)255, pixels[(i * 4) + 3]); + } + } + } + finally + { + frames.ForEach(f => f.Dispose()); + } + } + + [TestMethod] + public void BeforeTheStartAndPastTheEndGiveTheFirstAndLastFrames() + { + var es = ElementaryStream.Load("CABA3_SVA_B"); + using var stream = new MemoryStream(TestVideos.Mp4(es)); + using var reader = VideoFrameReader.Open(stream, out var info); + + var targets = reader.Locate([TimeSpan.Zero, TimeSpan.FromHours(1), info.Duration]); + + Assert.AreEqual(Array.IndexOf(es.Rank, 0), targets[0].Sample); + Assert.AreEqual(Array.IndexOf(es.Rank, es.Count - 1), targets[1].Sample); + Assert.AreEqual(targets[1].Sample, targets[2].Sample); + } + + [TestMethod] + public void ReRequestingTheActualMsGivesTheSameFrame() + { + var es = ElementaryStream.Load("CABA3_SVA_B"); + using var stream = new MemoryStream(TestVideos.Matroska(es)); + using var reader = VideoFrameReader.Open(stream, out var info); + var instants = ExportFrames.Spread(info.Duration, 7); + + var first = reader.Locate(instants); + var again = reader.Locate([.. first.Select(t => TimeSpan.FromMilliseconds(ExportFrames.ActualMs(t.Actual)))]); + + CollectionAssert.AreEqual(first.Select(t => t.Sample).ToArray(), again.Select(t => t.Sample).ToArray()); + } + + [TestMethod] + public void RotationIsApplied() + { + var es = ElementaryStream.Load("BA1_Sony_D"); + using var stream = new MemoryStream(TestVideos.Mp4(es, rotation: 90)); + using var reader = VideoFrameReader.Open(stream, out var info); + Assert.AreEqual((es.Height, es.Width), (info.Width, info.Height)); + + using var frame = reader.Decode(reader.Locate([TimeSpan.Zero]), CancellationToken.None).Single(); + + Assert.AreEqual((es.Height, es.Width), (frame.Image.Width, frame.Image.Height)); + } + + [TestMethod] + public void AnUnreadableVideoSaysNotAvailable() + { + using var stream = new MemoryStream(new byte[4096]); + using var reader = VideoFrameReader.Open(stream, out var info); + + Assert.IsFalse(info.Available); + Assert.AreEqual(VideoFrameReader.NotAvailableMessage, info.Unavailable); + Assert.IsEmpty(reader.Locate([TimeSpan.Zero])); + } + + [TestMethod] + public void RemuxingTwiceGivesTheSameBytesOfThePlannedLength() + { + var es = ElementaryStream.Load("CABA3_SVA_B"); + var mkv = TestVideos.Matroska(es, new DateTimeOffset(2024, 1, 2, 3, 4, 5, TimeSpan.Zero)); + using var source = new MemoryStream(mkv); + + Assert.AreEqual(RemuxRefusal.None, Mp4Remuxer.Check(source, "video.mkv", out var plan, CancellationToken.None)); + using var first = new MemoryStream(); + using var second = new MemoryStream(); + Mp4Remuxer.Write(plan!, source, first, CancellationToken.None); + Mp4Remuxer.Write(plan!, source, second, CancellationToken.None); + + Assert.AreEqual(plan!.OutputLength, first.Length); + CollectionAssert.AreEqual(SHA256.HashData(first.ToArray()), SHA256.HashData(second.ToArray())); + + // The MP4 shows the same frames at the same instants as the Matroska file. + first.Position = 0; + using var remuxed = VideoFrameReader.Open(first, out var info); + Assert.IsTrue(info.Available); + using var original = VideoFrameReader.Open(source, out _); + var instants = ExportFrames.Every(info.Duration, TimeSpan.FromMilliseconds(250)); + CollectionAssert.AreEqual( + original.Locate(instants).Select(t => t.Actual).ToArray(), + remuxed.Locate(instants).Select(t => t.Actual).ToArray()); + + // An MP4 named .mp4 is already what was asked. + using var mp4 = new MemoryStream(TestVideos.Mp4(es)); + Assert.AreEqual(RemuxRefusal.AlreadyMp4, Mp4Remuxer.Check(mp4, "video.mp4", out _, CancellationToken.None)); + } + + /// The frame shown at position , decoded straight from the stream. + private static H264Frame ShownFrame(ElementaryStream es, int rank) + { + var decoder = new H264Decoder(); + var frames = new List(); + decoder.FrameDecoded += frames.Add; + decoder.DecodeAnnexB(ElementaryStream.AnnexB(es.Name)); + var index = Array.IndexOf(es.Rank, rank); + return frames.Single(f => f.DecodeIndex == index); + } +}