E3: conversione delle foto, rimux in MP4 e fotogrammi esatti nel nucleo

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 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-27 22:30:23 +01:00
1 parent 7faf92e667
commit 704c1ed9cf
28 files changed
+2830 -144

No files matched your search

@@ -6,6 +6,12 @@ namespace Febe.Core.Codecs.Containers;
/// </summary> /// </summary>
public static class ContainerReader public static class ContainerReader
{ {
/// <summary>
/// A «now» far in the future, for readers that must not depend on the clock (frames, remux): every plausible date
/// in the file is accepted.
/// </summary>
internal static readonly DateTimeOffset AnyDate = new(9000, 1, 1, 0, 0, 0, TimeSpan.Zero);
/// <summary>The largest sample read into memory: an 8K frame of H.264 at its highest level stays far below.</summary> /// <summary>The largest sample read into memory: an 8K frame of H.264 at its highest level stays far below.</summary>
public const int MaxSampleSize = 64 * 1024 * 1024; public const int MaxSampleSize = 64 * 1024 * 1024;
+158 -18
View File
@@ -39,6 +39,7 @@ public static class IsoBmffReader
long position = 0; long position = 0;
Span<byte> header = stackalloc byte[16]; Span<byte> header = stackalloc byte[16];
Movie? movie = null; Movie? movie = null;
string? brand = null;
var pending = new List<(long Start, byte[] Body)>(); var pending = new List<(long Start, byte[] Body)>();
for (var i = 0; i < MaxTopLevelBoxes && position + 8 <= length; i++) for (var i = 0; i < MaxTopLevelBoxes && position + 8 <= length; i++)
{ {
@@ -75,6 +76,12 @@ public static class IsoBmffReader
} }
var type = header.Slice(4, 4); var type = header.Slice(4, 4);
if (type.SequenceEqual("ftyp"u8) && brand is null && size - headerSize >= 4)
{
stream.ReadExactly(header[..4]); // the size field is read already: its bytes can hold the brand
brand = System.Text.Encoding.Latin1.GetString(header[..4]);
}
if (type.SequenceEqual("moov"u8) && movie is null) if (type.SequenceEqual("moov"u8) && movie is null)
{ {
movie = ParseMoov(ReadBody(stream, position + headerSize, size - headerSize), now, samples, length); movie = ParseMoov(ReadBody(stream, position + headerSize, size - headerSize), now, samples, length);
@@ -112,7 +119,7 @@ public static class IsoBmffReader
throw new ContainerException("Manca il box moov."); throw new ContainerException("Manca il box moov.");
} }
return movie.Build(); return movie.Build(brand);
} }
private static byte[] ReadBody(Stream stream, long offset, long count) private static byte[] ReadBody(Stream stream, long offset, long count)
@@ -141,7 +148,11 @@ public static class IsoBmffReader
case "mvhd": case "mvhd":
movie.ParseMvhd(body, now); movie.ParseMvhd(body, now);
break; break;
case "udta" or "meta":
movie.HasUserData = true;
break;
case "trak": case "trak":
movie.TrackCount++;
try try
{ {
movie.ParseTrak(moov, start, count); movie.ParseTrak(moov, start, count);
@@ -269,6 +280,11 @@ public static class IsoBmffReader
internal byte[]? Hvcc; internal byte[]? Hvcc;
internal byte[]? Asc; internal byte[]? Asc;
internal long EditOffset; internal long EditOffset;
internal bool HasEdits;
internal long EmptyEditMovie;
internal int EditCount;
internal string? Language;
internal int ObjectType;
internal List<MediaSample> Samples = []; internal List<MediaSample> Samples = [];
internal long FragmentTime = -1; internal long FragmentTime = -1;
} }
@@ -279,6 +295,7 @@ public static class IsoBmffReader
internal readonly Dictionary<uint, (uint Duration, uint Size, uint Flags)> TrackDefaults = []; internal readonly Dictionary<uint, (uint Duration, uint Size, uint Flags)> TrackDefaults = [];
private readonly List<Track> tracks = []; private readonly List<Track> tracks = [];
private DateTimeOffset? created; private DateTimeOffset? created;
private DateTimeOffset? modified;
private long timescale; private long timescale;
private long duration; private long duration;
@@ -288,6 +305,12 @@ public static class IsoBmffReader
/// <summary>fragment_duration of the <c>mehd</c> box, in movie units; 0 when absent.</summary> /// <summary>fragment_duration of the <c>mehd</c> box, in movie units; 0 when absent.</summary>
internal long FragmentDuration; internal long FragmentDuration;
/// <summary>The <c>trak</c> boxes of the movie, of every kind.</summary>
internal int TrackCount;
/// <summary>True when the movie has a <c>udta</c> or <c>meta</c> box.</summary>
internal bool HasUserData;
/// <summary>A fragmented movie whose headers give no duration: only its fragments tell it.</summary> /// <summary>A fragmented movie whose headers give no duration: only its fragments tell it.</summary>
internal bool NeedsFragmentsForDuration => internal bool NeedsFragmentsForDuration =>
Fragmented && duration <= 0 && FragmentDuration <= 0 && !tracks.Exists(t => t.Handler == "vide" && t.Duration > 0); Fragmented && duration <= 0 && FragmentDuration <= 0 && !tracks.Exists(t => t.Handler == "vide" && t.Duration > 0);
@@ -295,15 +318,18 @@ public static class IsoBmffReader
internal void ParseMvhd(ReadOnlySpan<byte> body, DateTimeOffset now) internal void ParseMvhd(ReadOnlySpan<byte> body, DateTimeOffset now)
{ {
ulong creation; ulong creation;
ulong modification;
if (body[0] == 1) if (body[0] == 1)
{ {
creation = BinaryPrimitives.ReadUInt64BigEndian(body[4..]); creation = BinaryPrimitives.ReadUInt64BigEndian(body[4..]);
modification = BinaryPrimitives.ReadUInt64BigEndian(body[12..]);
timescale = BinaryPrimitives.ReadUInt32BigEndian(body[20..]); timescale = BinaryPrimitives.ReadUInt32BigEndian(body[20..]);
duration = (long)Math.Min(BinaryPrimitives.ReadUInt64BigEndian(body[24..]), long.MaxValue); duration = (long)Math.Min(BinaryPrimitives.ReadUInt64BigEndian(body[24..]), long.MaxValue);
} }
else else
{ {
creation = BinaryPrimitives.ReadUInt32BigEndian(body[4..]); creation = BinaryPrimitives.ReadUInt32BigEndian(body[4..]);
modification = BinaryPrimitives.ReadUInt32BigEndian(body[8..]);
timescale = BinaryPrimitives.ReadUInt32BigEndian(body[12..]); timescale = BinaryPrimitives.ReadUInt32BigEndian(body[12..]);
duration = BinaryPrimitives.ReadUInt32BigEndian(body[16..]); duration = BinaryPrimitives.ReadUInt32BigEndian(body[16..]);
if (duration == uint.MaxValue) if (duration == uint.MaxValue)
@@ -312,14 +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)) if (instant >= Earliest && instant <= now.AddDays(1))
{ {
created = instant; return instant;
} }
} }
return null;
} }
internal void ParseTrak(byte[] data, int start, int count) internal void ParseTrak(byte[] data, int start, int count)
@@ -365,15 +399,33 @@ public static class IsoBmffReader
var v1 = body[0] == 1; var v1 = body[0] == 1;
var entries = BinaryPrimitives.ReadUInt32BigEndian(body[4..]); var entries = BinaryPrimitives.ReadUInt32BigEndian(body[4..]);
var offset = 8; var offset = 8;
var leading = true;
for (var i = 0; i < entries && i < 16; i++) for (var i = 0; i < entries && i < 16; i++)
{ {
var segment = v1 ? (long)Math.Min(BinaryPrimitives.ReadUInt64BigEndian(body[offset..]), long.MaxValue / 4) : BinaryPrimitives.ReadUInt32BigEndian(body[offset..]);
long mediaTime = v1 ? BinaryPrimitives.ReadInt64BigEndian(body[(offset + 8)..]) : BinaryPrimitives.ReadInt32BigEndian(body[(offset + 4)..]); long mediaTime = v1 ? BinaryPrimitives.ReadInt64BigEndian(body[(offset + 8)..]) : BinaryPrimitives.ReadInt32BigEndian(body[(offset + 4)..]);
var rate = BinaryPrimitives.ReadInt16BigEndian(body[(offset + (v1 ? 16 : 8))..]);
offset += v1 ? 20 : 12; offset += v1 ? 20 : 12;
if (mediaTime >= 0) if (leading && mediaTime < 0)
{ {
track.EditOffset = mediaTime; // the first non-empty edit: media time shown at presentation zero track.EmptyEditMovie += segment; // a delayed start
return; continue;
} }
if (leading)
{
leading = false;
track.HasEdits = true;
track.EditOffset = mediaTime; // the first non-empty edit: media time shown at presentation zero
}
// 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.Duration = d == uint.MaxValue ? 0 : d;
} }
track.Language = Language(body[0] == 1 ? body[32..] : body[20..]);
break; break;
case "hdlr": case "hdlr":
track.Handler = System.Text.Encoding.Latin1.GetString(body.Slice(8, 4)); track.Handler = System.Text.Encoding.Latin1.GetString(body.Slice(8, 4));
@@ -478,6 +531,39 @@ public static class IsoBmffReader
} }
} }
/// <summary>
/// The ISO 639-2/T code packed in an <c>mdhd</c> (three letters of five bits each); null for «und», for a
/// QuickTime Macintosh language code (below 0x400) or for a damaged value.
/// </summary>
private static string? Language(ReadOnlySpan<byte> field)
{
if (field.Length < 2)
{
return null;
}
var packed = BinaryPrimitives.ReadUInt16BigEndian(field) & 0x7FFF;
if (packed < 0x400)
{
return null;
}
Span<char> code = stackalloc char[3];
for (var i = 0; i < 3; i++)
{
var letter = (packed >> (10 - (5 * i))) & 0x1F;
if (letter is < 1 or > 26)
{
return null;
}
code[i] = (char)('a' + letter - 1);
}
var text = new string(code);
return text == "und" ? null : text;
}
private static void ParseStsd(byte[] data, int start, int count, Track track) private static void ParseStsd(byte[] data, int start, int count, Track track)
{ {
if (count < 16) if (count < 16)
@@ -524,16 +610,31 @@ public static class IsoBmffReader
{ {
if (t == "esds") if (t == "esds")
{ {
track.Asc = EsdsConfig(data.AsSpan(s, c)); (track.ObjectType, track.Asc) = EsdsConfig(data.AsSpan(s, c));
}
else if (t == "wave" && track.ObjectType == 0)
{
// QuickTime keeps the esds of an mp4a entry inside a wave box (QTFF, sound sample description).
foreach (var (wt, ws, wc) in Children(data, s, c))
{
if (wt == "esds")
{
(track.ObjectType, track.Asc) = EsdsConfig(data.AsSpan(ws, wc));
}
}
} }
} }
} }
} }
} }
/// <summary>The DecoderSpecificInfo of an <c>esds</c> box (ISO/IEC 14496-1 descriptors).</summary> /// <summary>
private static byte[]? EsdsConfig(ReadOnlySpan<byte> body) /// The objectTypeIndication (0 when absent) and the DecoderSpecificInfo of an <c>esds</c> box (ISO/IEC 14496-1
/// descriptors).
/// </summary>
private static (int ObjectType, byte[]? Config) EsdsConfig(ReadOnlySpan<byte> body)
{ {
var objectType = 0;
var p = 4; // version and flags var p = 4; // version and flags
while (p + 2 <= body.Length) while (p + 2 <= body.Length)
{ {
@@ -555,7 +656,7 @@ public static class IsoBmffReader
{ {
if (p + 3 > body.Length) if (p + 3 > body.Length)
{ {
return null; return (objectType, null);
} }
var flags = body[p + 2]; var flags = body[p + 2];
@@ -569,7 +670,7 @@ public static class IsoBmffReader
{ {
if (p >= body.Length) if (p >= body.Length)
{ {
return null; return (objectType, null);
} }
p += 1 + body[p]; p += 1 + body[p];
@@ -583,18 +684,23 @@ public static class IsoBmffReader
break; break;
} }
case 0x04: // DecoderConfigDescriptor: its fixed fields, then the children case 0x04: // DecoderConfigDescriptor: objectTypeIndication and the other fixed fields, then the children
if (p < body.Length)
{
objectType = body[p];
}
p += 13; p += 13;
break; break;
case 0x05: case 0x05:
return p + length <= body.Length ? body.Slice(p, length).ToArray() : null; return (objectType, p + length <= body.Length ? body.Slice(p, length).ToArray() : null);
default: default:
p += length; p += length;
break; break;
} }
} }
return null; return (objectType, null);
} }
private void BuildSamples(Track track, byte[] stts, byte[]? ctts, byte[] stsc, byte[] stsz, bool stz2, byte[] stco, bool co64, byte[]? stss) private void BuildSamples(Track track, byte[] stts, byte[]? ctts, byte[] stsc, byte[] stsz, bool stz2, byte[] stco, bool co64, byte[]? stss)
@@ -903,7 +1009,7 @@ public static class IsoBmffReader
return total; return total;
} }
internal MediaContainer Build() internal MediaContainer Build(string? brand)
{ {
var video = tracks.Find(t => t.Handler == "vide"); var video = tracks.Find(t => t.Handler == "vide");
var audio = tracks.Find(t => t.Handler == "soun"); var audio = tracks.Find(t => t.Handler == "soun");
@@ -932,6 +1038,10 @@ public static class IsoBmffReader
AvcConfiguration = video.Avcc, AvcConfiguration = video.Avcc,
HevcConfiguration = video.Hvcc, HevcConfiguration = video.Hvcc,
Samples = video.Samples, Samples = video.Samples,
EditMediaTime = video.HasEdits ? video.EditOffset : null,
EmptyEditDuration = EmptyEdit(video),
EditCount = video.EditCount,
Language = video.Language,
}; };
} }
@@ -942,6 +1052,8 @@ public static class IsoBmffReader
{ {
Codec = audio.Format switch Codec = audio.Format switch
{ {
// objectTypeIndication 0x69 and 0x6B are MPEG-1/2 audio (MP3) in an mp4a entry (ISO/IEC 14496-1 Table 5).
"mp4a" when audio.ObjectType is 0x69 or 0x6B => AudioCodec.Mp3,
"mp4a" => AudioCodec.Aac, "mp4a" => AudioCodec.Aac,
".mp3" => AudioCodec.Mp3, ".mp3" => AudioCodec.Mp3,
"Opus" => AudioCodec.Opus, "Opus" => AudioCodec.Opus,
@@ -951,10 +1063,15 @@ public static class IsoBmffReader
CodecTag = audio.Format, CodecTag = audio.Format,
Channels = audio.Channels, Channels = audio.Channels,
SampleRate = audio.SampleRate, SampleRate = audio.SampleRate,
AacConfiguration = audio.Asc, AacConfiguration = audio.ObjectType is 0x69 or 0x6B ? null : audio.Asc,
AudioObjectType = audio.ObjectType is 0x69 or 0x6B ? null : AudioTrack.ObjectTypeOf(audio.Asc),
Timescale = audio.Timescale > 0 ? audio.Timescale : 1, Timescale = audio.Timescale > 0 ? audio.Timescale : 1,
Duration = DurationOf(audio), Duration = DurationOf(audio),
Samples = audio.Samples, Samples = audio.Samples,
EditMediaTime = audio.HasEdits ? audio.EditOffset : null,
EmptyEditDuration = EmptyEdit(audio),
EditCount = audio.EditCount,
Language = audio.Language,
}; };
} }
@@ -965,7 +1082,30 @@ public static class IsoBmffReader
total = Seconds(v.Seconds(v.Duration)); total = Seconds(v.Seconds(v.Duration));
} }
return new MediaContainer { Format = ContainerFormat.IsoBmff, CreatedAt = created, Duration = total, Video = v, Audio = a }; return new MediaContainer
{
Format = ContainerFormat.IsoBmff,
CreatedAt = created,
ModifiedAt = modified,
MajorBrand = brand,
TrackCount = TrackCount,
HasUserData = HasUserData,
Duration = total,
Video = v,
Audio = a,
};
}
/// <summary>The leading empty edits of a track (movie units) in track units, rounded to the nearest.</summary>
private long EmptyEdit(Track track)
{
if (track.EmptyEditMovie <= 0 || timescale <= 0 || track.Timescale <= 0)
{
return 0;
}
var value = (((Int128)track.EmptyEditMovie * track.Timescale) + (timescale / 2)) / timescale;
return value > long.MaxValue / 4 ? 0 : (long)value;
} }
/// <summary>A duration in seconds; null when it is beyond what a video can last (a damaged header).</summary> /// <summary>A duration in seconds; null when it is beyond what a video can last (a damaged header).</summary>
@@ -107,6 +107,9 @@ public static class MatroskaReader
case TracksId: case TracksId:
ParseTracks(reader, bodyEnd, state); ParseTracks(reader, bodyEnd, state);
break; break;
case TagsId:
state.HasTags = true;
break;
case ClusterId: case ClusterId:
if (!samples) if (!samples)
{ {
@@ -214,6 +217,13 @@ public static class MatroskaReader
case 0x23E383: case 0x23E383:
track.DefaultDuration = (long)reader.Unsigned(tsize); track.DefaultDuration = (long)reader.Unsigned(tsize);
break; break;
case 0x22B59C:
track.Language = reader.String(tsize);
break;
case 0x6D80: // ContentEncodings: the frames are compressed, stripped or encrypted
track.Encoded = true;
reader.Skip(tsize);
break;
case 0x55EE: // MaxBlockAdditionID, and others: ignored case 0x55EE: // MaxBlockAdditionID, and others: ignored
reader.Skip(tsize); reader.Skip(tsize);
break; break;
@@ -289,6 +299,7 @@ public static class MatroskaReader
} }
stream.Position = Math.Min(entryEnd, stream.Length); stream.Position = Math.Min(entryEnd, stream.Length);
state.TrackCount++;
if (track.Type == 1 && state.Video is null) if (track.Type == 1 && state.Video is null)
{ {
state.Video = track; state.Video = track;
@@ -498,6 +509,8 @@ public static class MatroskaReader
internal double Roll; internal double Roll;
internal int SampleRate; internal int SampleRate;
internal int Channels; internal int Channels;
internal string? Language;
internal bool Encoded;
internal readonly List<MediaSample> Samples = []; internal readonly List<MediaSample> Samples = [];
} }
@@ -509,6 +522,12 @@ public static class MatroskaReader
internal TrackEntry? Video; internal TrackEntry? Video;
internal TrackEntry? Audio; internal TrackEntry? Audio;
/// <summary>Every TrackEntry of the file.</summary>
internal int TrackCount;
/// <summary>True when the segment has a Tags element.</summary>
internal bool HasTags;
/// <summary>Nanoseconds of one unit of the sample times; fixed by the first block, 0 before.</summary> /// <summary>Nanoseconds of one unit of the sample times; fixed by the first block, 0 before.</summary>
private long unit; private long unit;
@@ -599,12 +618,15 @@ public static class MatroskaReader
Timescale = timescale, Timescale = timescale,
Duration = trackUnits, Duration = trackUnits,
Samples = samples, Samples = samples,
Language = Language(v.Language),
Encoded = v.Encoded,
}; };
} }
AudioTrack? audio = null; AudioTrack? audio = null;
if (Audio is { } a) if (Audio is { } a)
{ {
var asc = a.CodecId == "A_AAC" ? a.CodecPrivate : a.CodecId.StartsWith("A_AAC/", StringComparison.Ordinal) ? LegacyAacConfig(a) : null;
audio = new AudioTrack audio = new AudioTrack
{ {
Codec = a.CodecId switch Codec = a.CodecId switch
@@ -619,16 +641,91 @@ public static class MatroskaReader
CodecTag = a.CodecId, CodecTag = a.CodecId,
SampleRate = a.SampleRate, SampleRate = a.SampleRate,
Channels = a.Channels, Channels = a.Channels,
AacConfiguration = a.CodecId == "A_AAC" ? a.CodecPrivate : null, AacConfiguration = asc,
AudioObjectType = AudioTrack.ObjectTypeOf(asc),
Timescale = timescale, Timescale = timescale,
Duration = trackUnits, Duration = trackUnits,
Samples = a.Samples, Samples = a.Samples,
Language = Language(a.Language),
Encoded = a.Encoded,
}; };
} }
var seconds = DurationTicks * TimecodeScale / 1e9; var seconds = DurationTicks * TimecodeScale / 1e9;
TimeSpan? duration = seconds is > 0 and < 1e9 ? TimeSpan.FromSeconds(seconds) : null; TimeSpan? duration = seconds is > 0 and < 1e9 ? TimeSpan.FromSeconds(seconds) : null;
return new MediaContainer { Format = ContainerFormat.Matroska, CreatedAt = Created, Duration = duration, Video = video, Audio = audio }; return new MediaContainer
{
Format = ContainerFormat.Matroska,
CreatedAt = Created,
Duration = duration,
Video = video,
Audio = audio,
TrackCount = TrackCount,
HasUserData = HasTags,
};
}
/// <summary>A three-letter ISO 639-2 language; null for «und», absent or malformed.</summary>
private static string? Language(string? code) =>
code is { Length: 3 } && code != "und" && code.All(char.IsAsciiLetterLower) ? code : null;
/// <summary>
/// The AudioSpecificConfig (ISO/IEC 14496-3 §1.6.2.1) of a track with an old codec ID that names the profile
/// («A_AAC/MPEG4/LC», «A_AAC/MPEG2/MAIN», «…/SBR»...) instead of carrying the configuration in CodecPrivate:
/// object type, sampling frequency index (or the explicit frequency), channel configuration, then a
/// GASpecificConfig of zeros (1024-sample frames, no core coder, no extension).
/// </summary>
private static byte[]? LegacyAacConfig(TrackEntry track)
{
if (track.CodecPrivate is { Length: >= 2 })
{
return track.CodecPrivate;
}
var profile = track.CodecId[(track.CodecId.LastIndexOf('/') + 1)..];
var objectType = profile switch
{
"MAIN" => 1,
"LC" or "SBR" => 2, // SBR is signalled implicitly: the core rate in SamplingFrequency
"SSR" => 3,
"LTP" => 4,
_ => 0,
};
if (objectType == 0 || track.SampleRate <= 0 || track.Channels is < 1 or > 7)
{
return null;
}
int[] rates = [96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350];
var index = Array.IndexOf(rates, track.SampleRate);
var bits = new List<(int Value, int Count)> { (objectType, 5) };
if (index >= 0)
{
bits.Add((index, 4));
}
else
{
bits.Add((15, 4));
bits.Add((track.SampleRate & 0xFFFFFF, 24));
}
bits.Add((track.Channels, 4));
bits.Add((0, 3));
var total = bits.Sum(b => b.Count);
var config = new byte[(total + 7) / 8];
var position = 0;
foreach (var (value, count) in bits)
{
for (var i = count - 1; i >= 0; i--, position++)
{
if (((value >> i) & 1) != 0)
{
config[position / 8] |= (byte)(0x80 >> (position % 8));
}
}
}
return config;
} }
} }
@@ -94,6 +94,31 @@ public abstract class MediaTrack
/// <summary>The four-character code or codec identifier of the container, for messages.</summary> /// <summary>The four-character code or codec identifier of the container, for messages.</summary>
public string CodecTag { get; init; } = string.Empty; public string CodecTag { get; init; } = string.Empty;
/// <summary>
/// The media time (track units) shown at the start of the presentation, from the first non-empty edit of an ISO edit
/// list; null when the track has no edit list (Matroska never has one). The reader's presentation times already
/// have it subtracted.
/// </summary>
public long? EditMediaTime { get; init; }
/// <summary>
/// The empty edits before the first non-empty one (a delayed start), in track units; 0 when none. A sample is shown
/// at its <see cref="MediaSample.PresentationTime"/> plus this.
/// </summary>
public long EmptyEditDuration { get; init; }
/// <summary>The edits of the edit list after the leading empty ones (1 for an ordinary one, 0 without edit list).</summary>
public int EditCount { get; init; }
/// <summary>The language of the track as an ISO 639-2 code («ita», «eng»); null when unknown or undetermined.</summary>
public string? Language { get; init; }
/// <summary>
/// True when the frames of the track are stored transformed (Matroska ContentEncodings: compression, header
/// stripping, encryption): their bytes are not the codec's.
/// </summary>
public bool Encoded { get; init; }
/// <summary>Time in seconds of a value in track units.</summary> /// <summary>Time in seconds of a value in track units.</summary>
public double Seconds(long ticks) => Timescale > 0 ? (double)ticks / Timescale : 0; public double Seconds(long ticks) => Timescale > 0 ? (double)ticks / Timescale : 0;
} }
@@ -143,6 +168,26 @@ public sealed class AudioTrack : MediaTrack
/// <summary>The AudioSpecificConfig of an AAC track.</summary> /// <summary>The AudioSpecificConfig of an AAC track.</summary>
public byte[]? AacConfiguration { get; init; } public byte[]? AacConfiguration { get; init; }
/// <summary>The audio object type of an AAC track (ISO/IEC 14496-3: 2 is AAC LC, 5 SBR, 29 PS); null when unknown.</summary>
public int? AudioObjectType { get; init; }
/// <summary>The audio object type of an AudioSpecificConfig (5 bits, 31 escaping to 32 + 6 more).</summary>
internal static int? ObjectTypeOf(byte[]? asc)
{
if (asc is not { Length: > 0 })
{
return null;
}
var type = asc[0] >> 3;
if (type == 31)
{
return asc.Length > 1 ? 32 + (((asc[0] & 7) << 3) | (asc[1] >> 5)) : null;
}
return type == 0 ? null : type;
}
} }
/// <summary>What a container says: its creation time, duration and first video and audio tracks.</summary> /// <summary>What a container says: its creation time, duration and first video and audio tracks.</summary>
@@ -153,6 +198,21 @@ public sealed class MediaContainer
/// <summary>Creation time written in the container, when plausible.</summary> /// <summary>Creation time written in the container, when plausible.</summary>
public DateTimeOffset? CreatedAt { get; init; } public DateTimeOffset? CreatedAt { get; init; }
/// <summary>Modification time written in the container (ISO <c>mvhd</c>), when plausible.</summary>
public DateTimeOffset? ModifiedAt { get; init; }
/// <summary>The major brand of an ISO file («isom», «qt », «M4V », «3gp4»...), null for other containers or without <c>ftyp</c>.</summary>
public string? MajorBrand { get; init; }
/// <summary>Tracks of every kind in the file (video, audio, timecode, subtitles...), of which only the first video and audio are read.</summary>
public int TrackCount { get; init; }
/// <summary>
/// True when the file has metadata of its own that the readers do not interpret (ISO <c>udta</c> or <c>meta</c>
/// boxes, Matroska tags): a remux does not carry it.
/// </summary>
public bool HasUserData { get; init; }
/// <summary>Duration of the whole presentation.</summary> /// <summary>Duration of the whole presentation.</summary>
public TimeSpan? Duration { get; init; } public TimeSpan? Duration { get; init; }
@@ -0,0 +1,335 @@
namespace Febe.Core.Codecs.Containers;
/// <summary>Why a video cannot be brought into MP4 without re-encoding it (tappa E3: then it is copied as it is).</summary>
public enum RemuxRefusal
{
/// <summary>It can.</summary>
None,
/// <summary>Not a video Febe recognises, or a file without a video track.</summary>
NotAVideo,
/// <summary>Already an MP4 (an ISO file with an <c>.mp4</c> name and a brand other than QuickTime's): copied byte for byte.</summary>
AlreadyMp4,
/// <summary>A container whose frames MP4 cannot take as they are (AVI, ASF, FLV, MPEG-PS, Annex B streams).</summary>
ContainerNotRemuxable,
/// <summary>A video codec other than H.264 and HEVC.</summary>
VideoCodec,
/// <summary>An audio codec other than AAC and MP3.</summary>
AudioCodec,
/// <summary>A track without the configuration record of its codec.</summary>
MissingConfiguration,
/// <summary>A Matroska track whose frames are stored transformed (ContentEncodings).</summary>
EncodedTrack,
/// <summary>A track with more than one edit (a cut or a still segment), which the writer does not reproduce.</summary>
EditList,
/// <summary>A video track without samples.</summary>
NoSamples,
/// <summary>A damaged or truncated file.</summary>
Unreadable,
}
/// <summary>
/// A remux planned by <see cref="Mp4Remuxer.Check(Stream, string, out RemuxPlan, CancellationToken)"/>: the source as
/// read, the MP4 to write (its exact length is <see cref="OutputLength"/>) and the note codes of what it does not keep.
/// </summary>
public sealed record RemuxPlan(MediaContainer Source, Mp4Layout Layout, IReadOnlyList<string> Losses)
{
/// <summary>Bytes of the MP4 that <see cref="Mp4Remuxer.Write"/> writes.</summary>
public long OutputLength => Layout.Length;
/// <summary>The stream the sample writers of <see cref="Layout"/> read from, set by <see cref="Mp4Remuxer.Write"/>.</summary>
internal RemuxSource Reading { get; init; } = new();
}
/// <summary>Where the samples of a planned remux are read from while it is written.</summary>
internal sealed class RemuxSource
{
internal Stream? Stream { get; set; }
}
/// <summary>
/// Brings a MOV, M4V, 3GP or Matroska video into MP4 by copying its samples (tappa E3, «MOV → MP4 solo rimuxaggio»):
/// one H.264 or HEVC video track and at most one AAC or MP3 audio track, with their configuration records, sync
/// samples, composition offsets, edit (the delayed start and the hidden AAC priming), rotation, language and dates.
/// Nothing is re-encoded; anything that would need it is refused with its reason. Only the tables and the
/// <c>moov</c> are in memory: the samples are read and written one at a time, and the same source always gives the
/// same bytes (the reader's «now» is fixed).
/// </summary>
public static class Mp4Remuxer
{
/// <summary>Note code (with «:n») of the tracks left behind: timecode, subtitles, a second audio track...</summary>
public const string LostTracks = "LostTracks";
/// <summary>Note code of the metadata of the source the MP4 does not carry (ISO <c>udta</c>/<c>meta</c>, Matroska tags).</summary>
public const string LostVideoMetadata = "LostVideoMetadata";
/// <summary>Plans the remux of a seekable <paramref name="source"/> without knowing its name: never <see cref="RemuxRefusal.AlreadyMp4"/>.</summary>
public static RemuxRefusal Check(Stream source, out RemuxPlan? plan, CancellationToken ct) => Check(source, null, out plan, ct);
/// <summary>
/// Plans the remux of a seekable <paramref name="source"/>; <paramref name="fileName"/> (or a path) tells an MP4
/// already (<see cref="RemuxRefusal.AlreadyMp4"/>). Never throws for a bad file.
/// </summary>
public static RemuxRefusal Check(Stream source, string? fileName, out RemuxPlan? plan, CancellationToken ct)
{
ArgumentNullException.ThrowIfNull(source);
plan = null;
MediaContainer? container;
try
{
container = ContainerReader.Read(source, ContainerReader.AnyDate, samples: true, ct);
}
catch (Exception ex) when (ex is ContainerException or EndOfStreamException or IOException or ArgumentException
or IndexOutOfRangeException or OverflowException or InvalidDataException)
{
return RemuxRefusal.Unreadable;
}
if (container is null)
{
return RemuxRefusal.NotAVideo;
}
if (container.Format is not (ContainerFormat.IsoBmff or ContainerFormat.Matroska))
{
return container.Video is null ? RemuxRefusal.NotAVideo : RemuxRefusal.ContainerNotRemuxable;
}
if (container.Format == ContainerFormat.IsoBmff && container.MajorBrand != "qt "
&& string.Equals(Path.GetExtension(fileName ?? string.Empty), ".mp4", StringComparison.OrdinalIgnoreCase))
{
return RemuxRefusal.AlreadyMp4;
}
if (container.Video is not { } video)
{
return RemuxRefusal.NotAVideo;
}
var audio = container.Audio is { Samples.Count: > 0 } a ? a : null;
var refusal = Refusal(video, audio);
if (refusal != RemuxRefusal.None)
{
return refusal;
}
var length = source.Length;
if (!InFile(video, length) || (audio is not null && !InFile(audio, length)))
{
return RemuxRefusal.Unreadable;
}
var reading = new RemuxSource();
var tracks = new List<Mp4OutputTrack> { VideoTrackOf(container, video, reading) };
if (audio is not null)
{
tracks.Add(AudioTrackOf(container, audio, reading));
}
Mp4Layout layout;
try
{
layout = Mp4Writer.Prepare(tracks, new Mp4MovieInfo(container.CreatedAt, container.ModifiedAt));
}
catch (Exception ex) when (ex is ArgumentException or OverflowException)
{
return RemuxRefusal.Unreadable;
}
var losses = new List<string>();
var dropped = container.TrackCount - tracks.Count;
if (dropped > 0)
{
losses.Add(FormattableString.Invariant($"{LostTracks}:{dropped}"));
}
if (container.HasUserData)
{
losses.Add(LostVideoMetadata);
}
plan = new RemuxPlan(container, layout, losses) { Reading = reading };
return RemuxRefusal.None;
}
/// <summary>
/// Writes the MP4 of <paramref name="plan"/> into <paramref name="output"/>, reading the samples from
/// <paramref name="source"/> (the same file the plan was made from, seekable). <paramref name="ct"/> is checked
/// between samples.
/// </summary>
/// <exception cref="ContainerException">A sample lies outside the file (it changed since the plan).</exception>
public static void Write(RemuxPlan plan, Stream source, Stream output, CancellationToken ct)
{
ArgumentNullException.ThrowIfNull(plan);
ArgumentNullException.ThrowIfNull(source);
ArgumentNullException.ThrowIfNull(output);
lock (plan.Reading)
{
plan.Reading.Stream = source;
try
{
plan.Layout.WriteTo(output, ct);
}
finally
{
plan.Reading.Stream = null;
}
}
}
private static RemuxRefusal Refusal(VideoTrack video, AudioTrack? audio)
{
if (video.Encoded || audio?.Encoded == true)
{
return RemuxRefusal.EncodedTrack;
}
if (video.Codec is not (VideoCodec.H264 or VideoCodec.Hevc))
{
return RemuxRefusal.VideoCodec;
}
if (video.AnnexB)
{
return RemuxRefusal.ContainerNotRemuxable;
}
if ((video.Codec == VideoCodec.H264 ? video.AvcConfiguration : video.HevcConfiguration) is not { Length: > 0 })
{
return RemuxRefusal.MissingConfiguration;
}
if (video.Samples.Count == 0)
{
return RemuxRefusal.NoSamples;
}
if (video.EditCount > 1)
{
return RemuxRefusal.EditList;
}
if (audio is null)
{
return RemuxRefusal.None;
}
if (audio.Codec is not (AudioCodec.Aac or AudioCodec.Mp3))
{
return RemuxRefusal.AudioCodec;
}
if (audio.Codec == AudioCodec.Aac && audio.AacConfiguration is not { Length: >= 2 })
{
return RemuxRefusal.MissingConfiguration;
}
return audio.EditCount > 1 ? RemuxRefusal.EditList : RemuxRefusal.None;
}
private static bool InFile(MediaTrack track, long length)
{
foreach (var s in track.Samples)
{
if (s.Offset < 0 || s.Size < 0 || s.Size > ContainerReader.MaxSampleSize || s.Offset + s.Size > length)
{
return false;
}
}
return true;
}
private static Mp4OutputTrack VideoTrackOf(MediaContainer container, VideoTrack video, RemuxSource reading)
{
var (samples, edit) = Times(container, video);
return new Mp4OutputTrack
{
IsVideo = true,
Timescale = video.Timescale,
Samples = samples,
WriteSample = Writer(video, reading),
Width = video.Width,
Height = video.Height,
Rotation = video.Rotation,
AvcConfiguration = video.Codec == VideoCodec.H264 ? video.AvcConfiguration : null,
HevcConfiguration = video.Codec == VideoCodec.Hevc ? video.HevcConfiguration : null,
SampleEntryType = container.Format == ContainerFormat.IsoBmff ? video.CodecTag : null,
Language = video.Language,
EditMediaTime = edit,
EmptyEditDuration = video.EmptyEditDuration,
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),
};
}
/// <summary>
/// The samples with their composition times and the media time shown first: an ISO reader's presentation times
/// have the edit's media time taken off, so it is put back and becomes the edit of the output; without an edit
/// list (and in Matroska, whose block times are presentation times) the media time 0 is shown at 0.
/// </summary>
private static (Mp4OutputSample[] Samples, long Edit) Times(MediaContainer container, MediaTrack track)
{
var edit = container.Format == ContainerFormat.IsoBmff ? track.EditMediaTime ?? 0 : 0;
var samples = new Mp4OutputSample[track.Samples.Count];
for (var i = 0; i < samples.Length; i++)
{
var s = track.Samples[i];
samples[i] = new Mp4OutputSample(s.Size, s.DecodeTime, s.PresentationTime + edit, s.Key);
}
return (samples, edit);
}
/// <summary>The duration of the last sample from the track's duration, when it is plausible (else the writer's default).</summary>
private static long LastDuration(MediaTrack track)
{
var samples = track.Samples;
var last = track.Duration - samples[^1].DecodeTime;
if (last <= 0)
{
return 0;
}
var before = samples.Count > 1 ? samples[^1].DecodeTime - samples[^2].DecodeTime : last;
return before > 0 && last > 4 * before ? 0 : last;
}
private static Action<int, Stream> Writer(MediaTrack track, RemuxSource reading)
{
var buffer = new byte[64 * 1024];
return (i, output) =>
{
var source = reading.Stream ?? throw new InvalidOperationException("Il rimuxaggio non ha la sua sorgente.");
output.Write(ContainerReader.ReadSample(source, track.Samples[i], ref buffer));
};
}
}
+208 -48
View File
@@ -41,6 +41,129 @@ public sealed class Mp4OutputTrack
/// <summary>Duration of the last sample, when the times cannot tell it (0: as the one before it).</summary> /// <summary>Duration of the last sample, when the times cannot tell it (0: as the one before it).</summary>
public long LastSampleDuration { get; init; } public long LastSampleDuration { get; init; }
/// <summary>The ISO 639-2/T language of the <c>mdhd</c> («ita»); null writes «und».</summary>
public string? Language { get; init; }
/// <summary>
/// The sample entry of a video track: «avc1» or «avc3» (H.264), «hvc1» or «hev1» (HEVC), as the source has it;
/// null writes «avc1» or «hvc1».
/// </summary>
public string? SampleEntryType { get; init; }
/// <summary>
/// MPEG-1/2 audio layer III in an <c>mp4a</c> entry (objectTypeIndication 0x6B, ISO/IEC 14496-1): it has no
/// AudioSpecificConfig, so <see cref="AacConfiguration"/> stays null.
/// </summary>
public bool IsMp3 { get; init; }
/// <summary>
/// The media time, on the scale of <see cref="Mp4OutputSample.PresentationTime"/>, shown at the start of the
/// presentation (the source's edit, so that AAC priming stays hidden); null lets the writer start at the first
/// shown sample, as before tappa E3.
/// </summary>
public long? EditMediaTime { get; init; }
/// <summary>A delayed start in track units: an empty edit before the media (0: none).</summary>
public long EmptyEditDuration { get; init; }
}
/// <summary>The dates of the movie header; the modification date falls back to the creation date.</summary>
public sealed record Mp4MovieInfo(DateTimeOffset? Created, DateTimeOffset? Modified);
/// <summary>
/// An MP4 file planned by <see cref="Mp4Writer.Prepare"/>: its exact <see cref="Length"/> is known before a byte is
/// written, and <see cref="WriteTo"/> streams it, one sample at a time.
/// </summary>
public sealed class Mp4Layout
{
private readonly IReadOnlyList<Mp4OutputTrack> tracks;
private readonly List<(int Track, int First, int Count)> chunks;
private readonly byte[] head;
internal Mp4Layout(IReadOnlyList<Mp4OutputTrack> tracks, List<(int Track, int First, int Count)> chunks, byte[] head, long payload)
{
this.tracks = tracks;
this.chunks = chunks;
this.head = head;
Length = head.LongLength + payload;
}
/// <summary>Bytes of the whole file.</summary>
public long Length { get; }
/// <summary>Writes the file into <paramref name="output"/> (from its current position).</summary>
/// <exception cref="InvalidOperationException">A sample writer wrote another number of bytes than its size.</exception>
public void WriteTo(Stream output, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(output);
var counting = new CountingStream(output);
counting.Write(head);
foreach (var (track, first, count) in chunks)
{
for (var k = first; k < first + count; k++)
{
ct.ThrowIfCancellationRequested();
var before = counting.Count;
tracks[track].WriteSample(k, counting);
if (counting.Count - before != tracks[track].Samples[k].Size)
{
throw new InvalidOperationException("Un campione non ha la lunghezza dichiarata.");
}
}
}
if (counting.Count != Length)
{
throw new InvalidOperationException("Il file scritto non ha la lunghezza prevista.");
}
}
/// <summary>Counts the bytes written through it, whatever the stream below can tell.</summary>
private sealed class CountingStream(Stream inner) : Stream
{
public long Count { get; private set; }
public override bool CanRead => false;
public override bool CanSeek => false;
public override bool CanWrite => true;
public override long Length => throw new NotSupportedException();
public override long Position
{
get => Count;
set => throw new NotSupportedException();
}
public override void Flush() => inner.Flush();
public override int Read(byte[] buffer, int offset, int count) => throw new NotSupportedException();
public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException();
public override void SetLength(long value) => throw new NotSupportedException();
public override void Write(byte[] buffer, int offset, int count)
{
inner.Write(buffer, offset, count);
Count += count;
}
public override void Write(ReadOnlySpan<byte> buffer)
{
inner.Write(buffer);
Count += buffer.Length;
}
public override void WriteByte(byte value)
{
inner.WriteByte(value);
Count++;
}
}
} }
/// <summary> /// <summary>
@@ -57,6 +180,16 @@ public static class Mp4Writer
public static void Write(Stream output, IReadOnlyList<Mp4OutputTrack> tracks, DateTimeOffset? created = null) public static void Write(Stream output, IReadOnlyList<Mp4OutputTrack> tracks, DateTimeOffset? created = null)
{ {
ArgumentNullException.ThrowIfNull(output); ArgumentNullException.ThrowIfNull(output);
Prepare(tracks, created is null ? null : new Mp4MovieInfo(created, created)).WriteTo(output);
}
/// <summary>
/// Plans the file of <paramref name="tracks"/>: every box but the media data is built, so the length is known;
/// <see cref="Mp4Layout.WriteTo"/> writes it.
/// </summary>
/// <exception cref="ArgumentException">A track has no samples, no timescale or no codec configuration.</exception>
public static Mp4Layout Prepare(IReadOnlyList<Mp4OutputTrack> tracks, Mp4MovieInfo? info)
{
ArgumentNullException.ThrowIfNull(tracks); ArgumentNullException.ThrowIfNull(tracks);
if (tracks.Count == 0 || tracks.Any(t => t.Samples.Count == 0 || t.Timescale <= 0)) if (tracks.Count == 0 || tracks.Any(t => t.Samples.Count == 0 || t.Timescale <= 0))
{ {
@@ -65,7 +198,7 @@ public static class Mp4Writer
foreach (var track in tracks) foreach (var track in tracks)
{ {
if (track.IsVideo ? (track.AvcConfiguration is null) == (track.HevcConfiguration is null) : track.AacConfiguration is null) if (track.IsVideo ? (track.AvcConfiguration is null) == (track.HevcConfiguration is null) : track.AacConfiguration is null && !track.IsMp3)
{ {
throw new ArgumentException("Manca la configurazione del codificatore.", nameof(tracks)); throw new ArgumentException("Manca la configurazione del codificatore.", nameof(tracks));
} }
@@ -84,7 +217,9 @@ public static class Mp4Writer
var wideMdat = payload + 8 > uint.MaxValue; var wideMdat = payload + 8 > uint.MaxValue;
var ftyp = Ftyp(); var ftyp = Ftyp();
var time = created is { } c && c > Epoch1904 ? (ulong)(c - Epoch1904).TotalSeconds : 0UL; var creation = info?.Created is { } c && c > Epoch1904 ? (ulong)(c - Epoch1904).TotalSeconds : 0UL;
var modification = (info?.Modified ?? info?.Created) is { } m && m > Epoch1904 ? (ulong)(m - Epoch1904).TotalSeconds : 0UL;
var time = (creation, modification);
// The moov box has the same size whatever the chunk offsets: build it once to know where the data starts. // The moov box has the same size whatever the chunk offsets: build it once to know where the data starts.
var co64 = false; var co64 = false;
@@ -110,39 +245,27 @@ public static class Mp4Writer
} }
moov = Moov(tracks, timing, chunks, offsets, co64, time); moov = Moov(tracks, timing, chunks, offsets, co64, time);
output.Write(ftyp); var head = new byte[ftyp.Length + moov.Length + (wideMdat ? 16 : 8)];
output.Write(moov); ftyp.CopyTo(head, 0);
Span<byte> header = stackalloc byte[16]; moov.CopyTo(head, ftyp.Length);
var header = head.AsSpan(ftyp.Length + moov.Length);
if (wideMdat) if (wideMdat)
{ {
BinaryPrimitives.WriteUInt32BigEndian(header, 1); BinaryPrimitives.WriteUInt32BigEndian(header, 1);
"mdat"u8.CopyTo(header[4..]); "mdat"u8.CopyTo(header[4..]);
BinaryPrimitives.WriteUInt64BigEndian(header[8..], (ulong)(payload + 16)); BinaryPrimitives.WriteUInt64BigEndian(header[8..], (ulong)(payload + 16));
output.Write(header);
} }
else else
{ {
BinaryPrimitives.WriteUInt32BigEndian(header, (uint)(payload + 8)); BinaryPrimitives.WriteUInt32BigEndian(header, (uint)(payload + 8));
"mdat"u8.CopyTo(header[4..]); "mdat"u8.CopyTo(header[4..]);
output.Write(header[..8]);
} }
foreach (var (track, first, count) in chunks) return new Mp4Layout(tracks, chunks, head, payload);
{
for (var k = first; k < first + count; k++)
{
var before = output.CanSeek ? output.Position : -1;
tracks[track].WriteSample(k, output);
if (before >= 0 && output.Position - before != tracks[track].Samples[k].Size)
{
throw new InvalidOperationException("Un campione non ha la lunghezza dichiarata.");
}
}
}
} }
/// <summary>Times of a track as the boxes need them.</summary> /// <summary>Times of a track as the boxes need them; <paramref name="EmptyEdit"/> is in track units.</summary>
private sealed record Timing(long[] Durations, int[] CompositionOffsets, long MediaDuration, long EditMediaTime, bool AllKey) private sealed record Timing(long[] Durations, int[] CompositionOffsets, long MediaDuration, long EditMediaTime, bool AllKey, long EmptyEdit)
{ {
internal static Timing Of(Mp4OutputTrack track) internal static Timing Of(Mp4OutputTrack track)
{ {
@@ -180,9 +303,17 @@ public static class Mp4Writer
total += d; total += d;
} }
// The edit list starts the presentation at the first shown sample. // The edit list starts the presentation at the first shown sample, or where the track says; a start before
var editTime = minPts - first + shift; // the first sample becomes an empty edit.
return new Timing(durations, offsets, total, editTime, allKey); 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(); return box.ToArray();
} }
private static byte[] Moov(IReadOnlyList<Mp4OutputTrack> tracks, Timing[] timing, List<(int Track, int First, int Count)> chunks, long[] offsets, bool co64, ulong time) private static byte[] Moov(IReadOnlyList<Mp4OutputTrack> tracks, Timing[] timing, List<(int Track, int First, int Count)> chunks, long[] offsets, bool co64, (ulong Created, ulong Modified) time)
{ {
long movieDuration = 0; long movieDuration = 0;
for (var t = 0; t < tracks.Count; t++) for (var t = 0; t < tracks.Count; t++)
{ {
movieDuration = Math.Max(movieDuration, ToMovie(timing[t].MediaDuration - timing[t].EditMediaTime, tracks[t].Timescale)); movieDuration = Math.Max(movieDuration, EmptyMovie(timing[t], tracks[t].Timescale) + ToMovie(timing[t].MediaDuration - timing[t].EditMediaTime, tracks[t].Timescale));
} }
var moov = new Box("moov"); var moov = new Box("moov");
var mvhd = new Box("mvhd"); var mvhd = new Box("mvhd");
var wide = movieDuration > uint.MaxValue || time > uint.MaxValue; var wide = movieDuration > uint.MaxValue || Wide(time);
mvhd.U32(wide ? 0x01000000u : 0); mvhd.U32(wide ? 0x01000000u : 0);
Times(mvhd, wide, time, MovieTimescale, movieDuration); Times(mvhd, wide, time, MovieTimescale, movieDuration);
mvhd.U32(0x00010000); mvhd.U32(0x00010000);
@@ -253,19 +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 long ToMovie(long ticks, long timescale) => (long)Math.Ceiling(Math.Max(0, ticks) * (double)MovieTimescale / timescale);
private static void Times(Box box, bool wide, ulong time, long timescale, long duration) /// <summary>The empty edit of a track in movie units, rounded to the nearest.</summary>
private static long EmptyMovie(Timing timing, long timescale) =>
timing.EmptyEdit <= 0 ? 0 : (long)((((Int128)timing.EmptyEdit * MovieTimescale) + (timescale / 2)) / timescale);
private static bool Wide((ulong Created, ulong Modified) time) => time.Created > uint.MaxValue || time.Modified > uint.MaxValue;
private static void Times(Box box, bool wide, (ulong Created, ulong Modified) time, long timescale, long duration)
{ {
if (wide) if (wide)
{ {
box.U64(time); box.U64(time.Created);
box.U64(time); box.U64(time.Modified);
box.U32((uint)timescale); box.U32((uint)timescale);
box.U64((ulong)duration); box.U64((ulong)duration);
} }
else else
{ {
box.U32((uint)time); box.U32((uint)time.Created);
box.U32((uint)time); box.U32((uint)time.Modified);
box.U32((uint)timescale); box.U32((uint)timescale);
box.U32((uint)duration); box.U32((uint)duration);
} }
@@ -293,25 +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 trak = new Box("trak");
var duration = ToMovie(timing.MediaDuration - timing.EditMediaTime, track.Timescale); var segment = ToMovie(timing.MediaDuration - timing.EditMediaTime, track.Timescale);
var wide = duration > uint.MaxValue || time > uint.MaxValue; var empty = EmptyMovie(timing, track.Timescale);
var duration = empty + segment;
var wide = duration > uint.MaxValue || Wide(time);
var tkhd = new Box("tkhd"); var tkhd = new Box("tkhd");
tkhd.U32((wide ? 0x01000000u : 0) | 3); tkhd.U32((wide ? 0x01000000u : 0) | 3);
if (wide) if (wide)
{ {
tkhd.U64(time); tkhd.U64(time.Created);
tkhd.U64(time); tkhd.U64(time.Modified);
tkhd.U32((uint)index + 1); tkhd.U32((uint)index + 1);
tkhd.U32(0); tkhd.U32(0);
tkhd.U64((ulong)duration); tkhd.U64((ulong)duration);
} }
else else
{ {
tkhd.U32((uint)time); tkhd.U32((uint)time.Created);
tkhd.U32((uint)time); tkhd.U32((uint)time.Modified);
tkhd.U32((uint)index + 1); tkhd.U32((uint)index + 1);
tkhd.U32(0); tkhd.U32(0);
tkhd.U32((uint)duration); tkhd.U32((uint)duration);
@@ -327,13 +466,21 @@ public static class Mp4Writer
tkhd.U32(track.IsVideo ? (uint)track.Height << 16 : 0); tkhd.U32(track.IsVideo ? (uint)track.Height << 16 : 0);
trak.Child(tkhd); trak.Child(tkhd);
if (timing.EditMediaTime != 0) if (timing.EditMediaTime != 0 || empty > 0)
{ {
var edts = new Box("edts"); var edts = new Box("edts");
var elst = new Box("elst"); var elst = new Box("elst");
elst.U32(0x01000000); elst.U32(0x01000000);
elst.U32(1); elst.U32(empty > 0 ? 2u : 1u);
elst.U64((ulong)duration); if (empty > 0)
{
elst.U64((ulong)empty);
elst.U64(ulong.MaxValue); // media_time −1: an empty edit
elst.U16(1);
elst.U16(0);
}
elst.U64((ulong)segment);
elst.U64((ulong)timing.EditMediaTime); elst.U64((ulong)timing.EditMediaTime);
elst.U16(1); elst.U16(1);
elst.U16(0); elst.U16(0);
@@ -343,10 +490,10 @@ public static class Mp4Writer
var mdia = new Box("mdia"); var mdia = new Box("mdia");
var mdhd = new Box("mdhd"); var mdhd = new Box("mdhd");
var mediaWide = timing.MediaDuration > uint.MaxValue || time > uint.MaxValue; var mediaWide = timing.MediaDuration > uint.MaxValue || Wide(time);
mdhd.U32(mediaWide ? 0x01000000u : 0); mdhd.U32(mediaWide ? 0x01000000u : 0);
Times(mdhd, mediaWide, time, track.Timescale, timing.MediaDuration); Times(mdhd, mediaWide, time, track.Timescale, timing.MediaDuration);
mdhd.U16(0x55C4); // «und» mdhd.U16(PackedLanguage(track.Language));
mdhd.U16(0); mdhd.U16(0);
mdia.Child(mdhd); mdia.Child(mdhd);
@@ -389,6 +536,17 @@ public static class Mp4Writer
return trak; return trak;
} }
/// <summary>An ISO 639-2/T code packed in 15 bits (ISO/IEC 14496-12 §8.4.2.3); «und» for anything else.</summary>
private static ushort PackedLanguage(string? language)
{
if (language is not { Length: 3 } || !language.All(char.IsAsciiLetterLower))
{
return 0x55C4; // «und»
}
return (ushort)(((language[0] - 0x60) << 10) | ((language[1] - 0x60) << 5) | (language[2] - 0x60));
}
private static Box Stbl(Mp4OutputTrack track, Timing timing, int index, List<(int Track, int First, int Count)> chunks, long[] offsets, bool co64) private static Box Stbl(Mp4OutputTrack track, Timing timing, int index, List<(int Track, int First, int Count)> chunks, long[] offsets, bool co64)
{ {
var stbl = new Box("stbl"); var stbl = new Box("stbl");
@@ -540,7 +698,10 @@ public static class Mp4Writer
private static Box Avc1(Mp4OutputTrack track) private static Box Avc1(Mp4OutputTrack track)
{ {
var hevc = track.HevcConfiguration is not null; var hevc = track.HevcConfiguration is not null;
var entry = new Box(hevc ? "hvc1" : "avc1"); var type = hevc
? track.SampleEntryType is "hvc1" or "hev1" ? track.SampleEntryType : "hvc1"
: track.SampleEntryType is "avc1" or "avc3" ? track.SampleEntryType : "avc1";
var entry = new Box(type);
entry.Zero(6); entry.Zero(6);
entry.U16(1); entry.U16(1);
entry.Zero(16); entry.Zero(16);
@@ -571,10 +732,9 @@ public static class Mp4Writer
entry.U16(0); entry.U16(0);
entry.U32((uint)Math.Min(track.SampleRate, 65535) << 16); entry.U32((uint)Math.Min(track.SampleRate, 65535) << 16);
var asc = track.AacConfiguration!; var decoderSpecific = track.IsMp3 ? [] : Descriptor(0x05, track.AacConfiguration!);
var decoderSpecific = Descriptor(0x05, asc);
var config = new byte[13 + decoderSpecific.Length]; var config = new byte[13 + decoderSpecific.Length];
config[0] = 0x40; // MPEG-4 audio config[0] = track.IsMp3 ? (byte)0x6B : (byte)0x40; // MPEG-1 audio (layer III) or MPEG-4 audio
config[1] = 0x15; // audio stream config[1] = 0x15; // audio stream
decoderSpecific.CopyTo(config, 13); decoderSpecific.CopyTo(config, 13);
byte[] es = [0, 0, 0, .. Descriptor(0x04, config), .. Descriptor(0x06, [0x02])]; byte[] es = [0, 0, 0, .. Descriptor(0x04, config), .. Descriptor(0x06, [0x02])];
+78
View File
@@ -216,6 +216,84 @@ public sealed partial class H264Decoder
} }
} }
/// <summary>
/// Whether the access unit carries a recovery point SEI (H.264 §D.1.8) with recovery_frame_cnt 0: decoding from it
/// gives exact pictures from it on in output order, as from an IDR picture. Only the SEI before the first slice counts.
/// </summary>
internal static bool HasExactRecoveryPoint(ReadOnlySpan<byte> accessUnit, int lengthSize)
{
var position = 0;
while (true)
{
Range unit;
var more = lengthSize == 0
? NalUnits.NextAnnexB(accessUnit, ref position, out unit)
: NalUnits.NextLengthPrefixed(accessUnit, lengthSize, ref position, out unit);
if (!more)
{
return false;
}
var nal = accessUnit[unit];
var type = nal[0] & 0x1F;
if (type is 1 or 2 or 5)
{
return false;
}
if (type != 6)
{
continue;
}
try
{
var sei = NalUnits.Parse(nal);
var data = sei.Rbsp;
var length = sei.Length;
var p = sei.HeaderLength;
while (p < length - 1)
{
var payloadType = 0;
while (p < length && data[p] == 0xFF)
{
payloadType += 255;
p++;
}
var payloadSize = 0;
if (p < length)
{
payloadType += data[p++];
}
while (p < length && data[p] == 0xFF)
{
payloadSize += 255;
p++;
}
if (p >= length)
{
break;
}
payloadSize += data[p++];
if (payloadType == 6)
{
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<byte> stream) private void DecodeUnitsAnnexB(ReadOnlySpan<byte> stream)
{ {
var position = 0; var position = 0;
@@ -71,6 +71,21 @@ internal static class ExifOrientation
return 1; return 1;
} }
/// <summary>
/// Whether <paramref name="tiff"/> is a TIFF structure an encoder can carry: the «II*\0» or «MM\0*» header and a
/// first IFD whose entry count lies inside the block. A damaged EXIF block fails and is left behind by a conversion.
/// </summary>
public static bool IsTiff(ReadOnlySpan<byte> tiff)
{
if (tiff.Length < 8 || !(tiff.StartsWith("II*\0"u8) || tiff.StartsWith("MM\0*"u8)))
{
return false;
}
var ifd = U32(tiff[4..], tiff[0] == (byte)'I');
return ifd >= 8 && ifd <= (uint)(tiff.Length - 2);
}
private static ushort U16(ReadOnlySpan<byte> b, bool little) => private static ushort U16(ReadOnlySpan<byte> b, bool little) =>
little ? BinaryPrimitives.ReadUInt16LittleEndian(b) : BinaryPrimitives.ReadUInt16BigEndian(b); little ? BinaryPrimitives.ReadUInt16LittleEndian(b) : BinaryPrimitives.ReadUInt16BigEndian(b);
+4 -1
View File
@@ -77,7 +77,10 @@ public static class GifDecoder
CanvasHeight, CanvasHeight,
Math.Max(1, FrameCount), Math.Max(1, FrameCount),
true, true,
Comments is null ? ImageMetadata.Empty : new ImageMetadata { Texts = Comments }); Comments is null ? ImageMetadata.Empty : new ImageMetadata { Texts = Comments })
{
IsAnimated = FrameCount > 1,
};
} }
private static GifFile Walk(ReadOnlySpan<byte> data, ImageLimits limits, bool countFrames) private static GifFile Walk(ReadOnlySpan<byte> data, ImageLimits limits, bool countFrames)
+269 -18
View File
@@ -33,6 +33,10 @@ public sealed record ImageConversionOptions
/// </param> /// </param>
/// <param name="Metadata">The metadata written.</param> /// <param name="Metadata">The metadata written.</param>
/// <param name="NotCarried">What of the source's metadata the target could not take, in Italian, for the interface.</param> /// <param name="NotCarried">What of the source's metadata the target could not take, in Italian, for the interface.</param>
/// <param name="Losses">
/// The same as note codes (tappa E3, <see cref="ImageConversionLosses"/>), once each, in a fixed order: what the export
/// and the library conversion record.
/// </param>
public sealed record ImageConversionResult( public sealed record ImageConversionResult(
byte[] Data, byte[] Data,
ImageFormat Source, ImageFormat Source,
@@ -41,7 +45,60 @@ public sealed record ImageConversionResult(
int Height, int Height,
bool Lossy, bool Lossy,
ImageMetadata Metadata, ImageMetadata Metadata,
IReadOnlyList<string> NotCarried); IReadOnlyList<string> NotCarried,
IReadOnlyList<string> Losses);
/// <summary>What a conversion does with a source (tappa E3, decisions D5 and D6).</summary>
public enum ImageConversionAction
{
/// <summary>The source is already in the target format: it is copied byte for byte, without a note.</summary>
CopyAsIs,
/// <summary>The source is decoded and written in the target format.</summary>
Convert,
/// <summary>The source cannot be converted without losing what matters: it is copied as it is, with a note.</summary>
CopyOriginal,
}
/// <summary>The outcome of <see cref="ImageConverter.Check"/>.</summary>
/// <param name="Action">What to do.</param>
/// <param name="Source">The format of the source by its bytes; null when it is not recognised.</param>
/// <param name="NoteCode">For <see cref="ImageConversionAction.CopyOriginal"/>, why (<c>AsIsHeif</c>, <c>AsIsAnimated</c>...).</param>
public sealed record ImageConversionCheck(ImageConversionAction Action, ImageFormat? Source, string? NoteCode);
/// <summary>The note codes of what a conversion copies as it is or does not keep (decision D19 of tappa E3).</summary>
public static class ImageConversionLosses
{
public const string AsIsHeif = "AsIsHeif";
public const string AsIsAvif = "AsIsAvif";
public const string AsIsRaw = "AsIsRaw";
public const string AsIsAnimated = "AsIsAnimated";
public const string AsIsNotDecodable = "AsIsNotDecodable";
public const string AsIsDeepColor = "AsIsDeepColor";
public const string AsIsCmyk = "AsIsCmyk";
public const string AsIsTooLarge = "AsIsTooLarge";
public const string LostTexts = "LostTexts";
public const string LostColorChunks = "LostColorChunks";
public const string LostIcc = "LostIcc";
public const string LostIccTooLarge = "LostIccTooLarge";
public const string LostExifTooLarge = "LostExifTooLarge";
public const string LostXmpTooLarge = "LostXmpTooLarge";
public const string LostExtendedXmp = "LostExtendedXmp";
public const string LostExifUnreadable = "LostExifUnreadable";
public const string LostIptc = "LostIptc";
public const string LostOtherSegments = "LostOtherSegments";
public const string LostCommentTooLarge = "LostCommentTooLarge";
public const string TransparencyWhite = "TransparencyWhite";
/// <summary>The order in which the codes are listed, so that the same source always gives the same note.</summary>
internal static readonly string[] Order =
[
TransparencyWhite, LostExifUnreadable, LostExifTooLarge, LostIcc, LostIccTooLarge, LostXmpTooLarge, LostExtendedXmp,
LostIptc, LostTexts, LostCommentTooLarge, LostColorChunks, LostOtherSegments,
];
}
/// <summary> /// <summary>
/// Turns a picture into another format with the same pixels and the same metadata, so that the converted file is /// Turns a picture into another format with the same pixels and the same metadata, so that the converted file is
@@ -57,9 +114,97 @@ public sealed record ImageConversionResult(
/// </summary> /// </summary>
public static class ImageConverter public static class ImageConverter
{ {
/// <summary>The largest source a conversion reads into memory (decision D6 of tappa E3: 512 MiB).</summary>
public const long MaxSourceBytes = 512L * 1024 * 1024;
/// <summary>The largest picture written as WebP (decision D6 of tappa E3: about 1.1 GB of working memory).</summary>
public const long MaxWebPPixels = 40_000_000;
/// <summary>The formats a conversion can write.</summary> /// <summary>The formats a conversion can write.</summary>
public static bool CanWrite(ImageFormat format) => format is ImageFormat.Jpeg or ImageFormat.Png or ImageFormat.WebP; public static bool CanWrite(ImageFormat format) => format is ImageFormat.Jpeg or ImageFormat.Png or ImageFormat.WebP;
/// <summary>
/// What a conversion of <paramref name="data"/> to <paramref name="target"/> does, from its bytes and its header
/// only (tappa E3, D5 and D6): the same format is copied byte for byte (a lossy WebP to WebP too); HEIF, AVIF, TIFF
/// and raw files, animations, damaged or unknown files, CMYK and deep-colour sources to PNG or WebP and pictures
/// over the pixel budget of the target are copied as they are, with the reason. Never throws for a bad file.
/// </summary>
/// <exception cref="ArgumentException">The target is not JPEG, PNG or WebP.</exception>
public static ImageConversionCheck Check(ReadOnlyMemory<byte> data, ImageFormat target, ImageConversionOptions? options = null)
{
if (!CanWrite(target))
{
throw new ArgumentException($"Febe non scrive immagini {target.ToString().ToUpperInvariant()}.", nameof(target));
}
options ??= ImageConversionOptions.Default;
var source = ImageFormatSniffer.Detect(data.Span);
if (source == target)
{
return new ImageConversionCheck(ImageConversionAction.CopyAsIs, source, null);
}
string? asIs = source switch
{
ImageFormat.Heif => ImageConversionLosses.AsIsHeif,
ImageFormat.Avif => ImageConversionLosses.AsIsAvif,
ImageFormat.Tiff => ImageConversionLosses.AsIsRaw, // TIFF and the raw formats built on it (DNG, NEF, CR2...)
ImageFormat.Unknown => ImageConversionLosses.AsIsNotDecodable,
_ => null,
};
if (asIs is null && data.Length > MaxSourceBytes)
{
asIs = ImageConversionLosses.AsIsTooLarge;
}
if (asIs is null)
{
asIs = IdentifyOutcome(data, target, options.Limits);
}
return asIs is null
? new ImageConversionCheck(ImageConversionAction.Convert, source, null)
: new ImageConversionCheck(ImageConversionAction.CopyOriginal, source == ImageFormat.Unknown ? null : source, asIs);
}
private static string? IdentifyOutcome(ReadOnlyMemory<byte> data, ImageFormat target, ImageLimits limits)
{
ImageInfo info;
try
{
info = ImageDecoder.Identify(data, limits);
}
catch (ImageLimitException)
{
return ImageConversionLosses.AsIsTooLarge;
}
catch (ImageDecodeException)
{
return ImageConversionLosses.AsIsNotDecodable;
}
if (info.IsAnimated)
{
return ImageConversionLosses.AsIsAnimated;
}
if (target != ImageFormat.Jpeg && info.IsCmyk)
{
return ImageConversionLosses.AsIsCmyk;
}
if (target != ImageFormat.Jpeg && info.BitsPerSample > 8)
{
return ImageConversionLosses.AsIsDeepColor;
}
var pixels = (long)info.Width * info.Height;
var tooLarge = target == ImageFormat.WebP
? pixels > MaxWebPPixels || info.Width > WebPEncoder.MaxDimension || info.Height > WebPEncoder.MaxDimension
: pixels > ImageLimits.Default.MaxPixels;
return tooLarge ? ImageConversionLosses.AsIsTooLarge : null;
}
/// <summary>Converts <paramref name="source"/> (any format <see cref="ImageDecoder"/> reads) to <paramref name="target"/>.</summary> /// <summary>Converts <paramref name="source"/> (any format <see cref="ImageDecoder"/> reads) to <paramref name="target"/>.</summary>
/// <exception cref="ArgumentException">The target is not JPEG, PNG or WebP.</exception> /// <exception cref="ArgumentException">The target is not JPEG, PNG or WebP.</exception>
/// <exception cref="ImageDecodeException">The source is damaged, too large or in a format Febe does not read.</exception> /// <exception cref="ImageDecodeException">The source is damaged, too large or in a format Febe does not read.</exception>
@@ -85,8 +230,58 @@ public static class ImageConverter
lossy = true; lossy = true;
} }
var metadata = info.Metadata; var losses = new HashSet<string>(StringComparer.Ordinal);
var data = EncodeCore(image, target, info.Metadata, options, notCarried, losses, out var written);
return new ImageConversionResult(data, info.Format, target, image.Width, image.Height, lossy, written, notCarried, Ordered(losses));
}
/// <summary>
/// Writes <paramref name="image"/> (straight RGBA) as <paramref name="target"/> with what of
/// <paramref name="metadata"/> the target can carry (none when null: the frames of tappa E3). A transparent image
/// to JPEG is first flattened over the background of the options, on a copy: <paramref name="image"/> is never
/// changed.
/// </summary>
/// <exception cref="ArgumentException">The target is not JPEG, PNG or WebP, or a WebP side is over 16384.</exception>
public static byte[] Encode(RgbaImage image, ImageFormat target, ImageMetadata? metadata, ImageConversionOptions? options = null)
{
ArgumentNullException.ThrowIfNull(image);
if (!CanWrite(target))
{
throw new ArgumentException($"Febe non scrive immagini {target.ToString().ToUpperInvariant()}.", nameof(target));
}
options ??= ImageConversionOptions.Default;
if (target == ImageFormat.Jpeg && !image.IsOpaque())
{
using var copy = new RgbaImage(image.Width, image.Height, image.ToArray());
return EncodeCore(copy, target, metadata ?? ImageMetadata.Empty, options, [], new HashSet<string>(StringComparer.Ordinal), out _);
}
return EncodeCore(image, target, metadata ?? ImageMetadata.Empty, options, [], new HashSet<string>(StringComparer.Ordinal), out _);
}
/// <summary>The codes of <paramref name="losses"/> in the order of <see cref="ImageConversionLosses.Order"/>.</summary>
private static string[] Ordered(HashSet<string> losses) =>
[.. ImageConversionLosses.Order.Where(losses.Contains)];
/// <summary>Encodes; flattens <paramref name="image"/> in place for a JPEG target that is not opaque.</summary>
private static byte[] EncodeCore(
RgbaImage image,
ImageFormat target,
ImageMetadata metadata,
ImageConversionOptions options,
List<string> notCarried,
HashSet<string> losses,
out ImageMetadata written)
{
var exif = metadata.Exif; var exif = metadata.Exif;
if (exif is not null && !ExifOrientation.IsTiff(exif))
{
notCarried.Add("l'EXIF (rovinato: non è una struttura TIFF leggibile)");
losses.Add(ImageConversionLosses.LostExifUnreadable);
exif = null;
}
var icc = metadata.IccProfile; var icc = metadata.IccProfile;
var iccName = metadata.IccProfileName; var iccName = metadata.IccProfileName;
if (icc is not null && IccColorSpace(icc) != "RGB ") if (icc is not null && IccColorSpace(icc) != "RGB ")
@@ -97,6 +292,7 @@ public static class ImageConverter
"GRAY" => "il profilo colore in scala di grigi (i pixel sono scritti in RGB)", "GRAY" => "il profilo colore in scala di grigi (i pixel sono scritti in RGB)",
_ => "il profilo colore (non descrive pixel RGB)", _ => "il profilo colore (non descrive pixel RGB)",
}); });
losses.Add(ImageConversionLosses.LostIcc);
icc = null; icc = null;
iccName = null; iccName = null;
} }
@@ -104,23 +300,49 @@ public static class ImageConverter
foreach (var chunk in metadata.ColorChunks) foreach (var chunk in metadata.ColorChunks)
{ {
notCarried.Add($"il blocco di colore {chunk} del PNG (non viene scritto)"); notCarried.Add($"il blocco di colore {chunk} del PNG (non viene scritto)");
losses.Add(ImageConversionLosses.LostColorChunks);
}
foreach (var block in metadata.Unread)
{
switch (block)
{
case "APP13":
notCarried.Add("i dati IPTC (segmento APP13)");
losses.Add(ImageConversionLosses.LostIptc);
break;
case "ExtendedXmp":
notCarried.Add("l'XMP esteso");
losses.Add(ImageConversionLosses.LostExtendedXmp);
break;
default:
notCarried.Add($"il blocco {block}");
losses.Add(ImageConversionLosses.LostOtherSegments);
break;
}
} }
var xmp = metadata.Xmp; var xmp = metadata.Xmp;
var texts = metadata.Texts; var texts = metadata.Texts;
IReadOnlyList<ImageText> writtenTexts = texts;
byte[] data; byte[] data;
switch (target) switch (target)
{ {
case ImageFormat.Png: case ImageFormat.Png:
data = PngEncoder.Encode(image, new PngEncoderOptions
{ {
Exif = exif, var pngTexts = PngTexts(texts, notCarried, losses);
IccProfile = icc, writtenTexts = pngTexts;
IccProfileName = ValidIccName(iccName) ?? PngEncoderOptions.Default.IccProfileName, data = PngEncoder.Encode(image, new PngEncoderOptions
Xmp = xmp, {
Texts = PngTexts(texts, notCarried), Exif = exif,
}); IccProfile = icc,
break; IccProfileName = ValidIccName(iccName) ?? PngEncoderOptions.Default.IccProfileName,
Xmp = xmp,
Texts = pngTexts,
});
break;
}
case ImageFormat.WebP: case ImageFormat.WebP:
if (image.Width > WebPEncoder.MaxDimension || image.Height > WebPEncoder.MaxDimension) if (image.Width > WebPEncoder.MaxDimension || image.Height > WebPEncoder.MaxDimension)
{ {
@@ -130,8 +352,10 @@ public static class ImageConverter
if (texts.Count > 0) if (texts.Count > 0)
{ {
notCarried.Add(texts.Count == 1 ? "un testo (WebP non ne ha)" : $"{texts.Count} testi (WebP non ne ha)"); notCarried.Add(texts.Count == 1 ? "un testo (WebP non ne ha)" : $"{texts.Count} testi (WebP non ne ha)");
losses.Add(ImageConversionLosses.LostTexts);
} }
writtenTexts = [];
data = WebPEncoder.Encode(image, new WebPEncoderOptions { Exif = exif, IccProfile = icc, Xmp = xmp }); data = WebPEncoder.Encode(image, new WebPEncoderOptions { Exif = exif, IccProfile = icc, Xmp = xmp });
break; break;
default: default:
@@ -139,25 +363,47 @@ public static class ImageConverter
if (exif is not null && exif.Length > JpegMaxSegmentPayload - 6) if (exif is not null && exif.Length > JpegMaxSegmentPayload - 6)
{ {
notCarried.Add($"l'EXIF ({exif.Length} byte, più di quanto entra in un segmento JPEG)"); notCarried.Add($"l'EXIF ({exif.Length} byte, più di quanto entra in un segmento JPEG)");
losses.Add(ImageConversionLosses.LostExifTooLarge);
exif = null; exif = null;
} }
if (xmp is not null && Encoding.UTF8.GetByteCount(xmp) > JpegMaxSegmentPayload - 29) if (xmp is not null && Encoding.UTF8.GetByteCount(xmp) > JpegMaxSegmentPayload - 29)
{ {
notCarried.Add("l'XMP (più di quanto entra in un segmento JPEG)"); notCarried.Add("l'XMP (più di quanto entra in un segmento JPEG)");
losses.Add(ImageConversionLosses.LostXmpTooLarge);
xmp = null; xmp = null;
} }
var comments = new List<string>(); if (icc is not null && (icc.Length + JpegIccChunk - 1) / JpegIccChunk > 255)
foreach (var text in texts)
{ {
comments.Add(text.Keyword.Length == 0 || text.Keyword == "Comment" ? text.Text : $"{text.Keyword}: {text.Text}"); notCarried.Add($"il profilo colore ({icc.Length} byte, più di quanto entra in 255 segmenti JPEG)");
losses.Add(ImageConversionLosses.LostIccTooLarge);
icc = null;
iccName = null;
} }
var comments = new List<string>();
var kept = new List<ImageText>();
foreach (var text in texts)
{
var comment = text.Keyword.Length == 0 || text.Keyword == "Comment" ? text.Text : $"{text.Keyword}: {text.Text}";
if (Encoding.UTF8.GetByteCount(comment) > JpegMaxSegmentPayload)
{
notCarried.Add("un commento (più lungo di quanto entra in un segmento JPEG)");
losses.Add(ImageConversionLosses.LostCommentTooLarge);
continue;
}
comments.Add(comment);
kept.Add(text);
}
writtenTexts = kept;
if (!image.IsOpaque()) if (!image.IsOpaque())
{ {
ImageBackground.Flatten(image, options.JpegBackground); ImageBackground.Flatten(image, options.JpegBackground);
notCarried.Add("la trasparenza (JPEG non ce l'ha: le parti trasparenti diventano dello sfondo)"); notCarried.Add("la trasparenza (JPEG non ce l'ha: le parti trasparenti diventano dello sfondo)");
losses.Add(ImageConversionLosses.TransparencyWhite);
} }
data = JpegEncoder.Encode(image, new JpegEncoderOptions data = JpegEncoder.Encode(image, new JpegEncoderOptions
@@ -173,16 +419,16 @@ public static class ImageConverter
} }
} }
var written = new ImageMetadata written = new ImageMetadata
{ {
Exif = exif, Exif = exif,
Orientation = metadata.Orientation, Orientation = exif is null ? 1 : metadata.Orientation,
IccProfile = icc, IccProfile = icc,
IccProfileName = icc is null ? null : iccName, IccProfileName = icc is null ? null : iccName,
Xmp = xmp, Xmp = xmp,
Texts = target == ImageFormat.WebP ? [] : texts, Texts = writtenTexts,
}; };
return new ImageConversionResult(data, info.Format, target, image.Width, image.Height, lossy, written, notCarried); return data;
} }
/// <summary>The data colour space of an ICC profile (bytes 16-19 of its header: «RGB », «GRAY», «CMYK»...), or null.</summary> /// <summary>The data colour space of an ICC profile (bytes 16-19 of its header: «RGB », «GRAY», «CMYK»...), or null.</summary>
@@ -211,6 +457,9 @@ public static class ImageConverter
/// <summary>Bytes of payload in one JPEG marker segment (65535 less the two of the length).</summary> /// <summary>Bytes of payload in one JPEG marker segment (65535 less the two of the length).</summary>
private const int JpegMaxSegmentPayload = 65533; private const int JpegMaxSegmentPayload = 65533;
/// <summary>Bytes of an ICC profile in one APP2 segment (the payload less «ICC_PROFILE\0» and the two counters).</summary>
private const int JpegIccChunk = 65519;
private static string? ValidIccName(string? name) private static string? ValidIccName(string? name)
{ {
if (string.IsNullOrEmpty(name) || name.Length > 79) if (string.IsNullOrEmpty(name) || name.Length > 79)
@@ -229,7 +478,7 @@ public static class ImageConverter
return name.Trim().Length == name.Length ? name : null; return name.Trim().Length == name.Length ? name : null;
} }
private static List<ImageText> PngTexts(IReadOnlyList<ImageText> texts, List<string> notCarried) private static List<ImageText> PngTexts(IReadOnlyList<ImageText> texts, List<string> notCarried, HashSet<string> losses)
{ {
var result = new List<ImageText>(texts.Count); var result = new List<ImageText>(texts.Count);
foreach (var text in texts) foreach (var text in texts)
@@ -238,6 +487,7 @@ public static class ImageConverter
if (!PngEncoder.IsValidKeyword(keyword)) if (!PngEncoder.IsValidKeyword(keyword))
{ {
notCarried.Add($"il testo «{keyword}» (nome non valido per un PNG)"); notCarried.Add($"il testo «{keyword}» (nome non valido per un PNG)");
losses.Add(ImageConversionLosses.LostTexts);
continue; continue;
} }
@@ -248,6 +498,7 @@ public static class ImageConverter
} }
} }
/// <summary>Composites an image over a plain colour.</summary> /// <summary>Composites an image over a plain colour.</summary>
public static class ImageBackground public static class ImageBackground
{ {
@@ -39,6 +39,13 @@ public sealed class ImageMetadata
/// not applied to the pixels and no encoder writes them, so a conversion says they are left behind. /// not applied to the pixels and no encoder writes them, so a conversion says they are left behind.
/// </summary> /// </summary>
public IReadOnlyList<string> ColorChunks { get; init; } = []; public IReadOnlyList<string> ColorChunks { get; init; } = [];
/// <summary>
/// Blocks of the file that hold data no reader of Febe interprets and no encoder writes, in file order and once
/// each: JPEG segments («APP13» for IPTC/Photoshop, «ExtendedXmp», «APP2» for MPF, other «APPn»), PNG ancillary
/// chunks («pHYs», «tIME»...), WebP chunks. A conversion reports them as not kept.
/// </summary>
public IReadOnlyList<string> Unread { get; init; } = [];
} }
/// <summary>What a file says about its image, read without decoding the pixels.</summary> /// <summary>What a file says about its image, read without decoding the pixels.</summary>
@@ -55,4 +62,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. /// for GIF and WebP). The decoders give 8-bit samples, so above 8 the decoded pixels have lost precision.
/// </summary> /// </summary>
public int BitsPerSample { get; init; } = 8; public int BitsPerSample { get; init; } = 8;
/// <summary>
/// Whether the file is an animation, by the presence of its marks (spec §4.10): a PNG with an <c>acTL</c> chunk
/// before its image data, a WebP with an <c>ANIM</c> or <c>ANMF</c> chunk, a GIF with more than one image.
/// </summary>
public bool IsAnimated { get; init; }
/// <summary>Whether the pixels are stored as CMYK or YCCK (a JPEG with four components).</summary>
public bool IsCmyk { get; init; }
} }
+35 -3
View File
@@ -76,6 +76,7 @@ internal sealed partial class JpegFile : IDisposable
private string? _xmp; private string? _xmp;
private List<(int Sequence, int Count, byte[] Data)>? _iccChunks; private List<(int Sequence, int Count, byte[] Data)>? _iccChunks;
private List<ImageText>? _texts; private List<ImageText>? _texts;
private List<string>? _unread;
private bool _allocated; private bool _allocated;
private bool _pooledArrays; private bool _pooledArrays;
@@ -320,7 +321,7 @@ internal sealed partial class JpegFile : IDisposable
public ImageInfo ToInfo() public ImageInfo ToInfo()
{ {
var icc = AssembleIcc(); var icc = AssembleIcc();
var metadata = _exif is null && icc is null && _xmp is null && _texts is null var metadata = _exif is null && icc is null && _xmp is null && _texts is null && _unread is null
? ImageMetadata.Empty ? ImageMetadata.Empty
: new ImageMetadata : new ImageMetadata
{ {
@@ -329,8 +330,9 @@ internal sealed partial class JpegFile : IDisposable
IccProfile = icc, IccProfile = icc,
Xmp = _xmp, Xmp = _xmp,
Texts = _texts ?? [], Texts = _texts ?? [],
Unread = _unread ?? [],
}; };
return new ImageInfo(ImageFormat.Jpeg, Width, Height, 1, false, metadata) { BitsPerSample = Precision }; return new ImageInfo(ImageFormat.Jpeg, Width, Height, 1, false, metadata) { BitsPerSample = Precision, IsCmyk = Components.Length == 4 };
} }
public JpegCoefficients ToCoefficients() public JpegCoefficients ToCoefficients()
@@ -625,6 +627,12 @@ internal sealed partial class JpegFile : IDisposable
return; return;
} }
if (marker is not (0xE1 or 0xE2))
{
NotRead(marker == 0xED ? "APP13" : $"APP{marker - 0xE0}");
return;
}
// Damaged or oversized metadata is skipped: it must never stop an image from being shown. // Damaged or oversized metadata is skipped: it must never stop an image from being shown.
if (marker == 0xE1) if (marker == 0xE1)
{ {
@@ -644,8 +652,16 @@ internal sealed partial class JpegFile : IDisposable
_xmp = Encoding.UTF8.GetString(packet); _xmp = Encoding.UTF8.GetString(packet);
} }
} }
else if (p.StartsWith(ExtendedXmpNamespace))
{
NotRead("ExtendedXmp");
}
else if (!(p.Length > 6 && p[..4].SequenceEqual("Exif"u8)) && !p.StartsWith(XmpNamespace))
{
NotRead("APP1");
}
} }
else if (marker == 0xE2 && p.Length > 14 && p[..12].SequenceEqual("ICC_PROFILE\0"u8)) else if (p.Length > 14 && p[..12].SequenceEqual("ICC_PROFILE\0"u8))
{ {
int sequence = p[12]; int sequence = p[12];
int count = p[13]; int count = p[13];
@@ -655,6 +671,22 @@ internal sealed partial class JpegFile : IDisposable
(_iccChunks ??= []).Add((sequence, count, chunk.ToArray())); (_iccChunks ??= []).Add((sequence, count, chunk.ToArray()));
} }
} }
else
{
NotRead("APP2"); // MPF and the like
}
}
/// <summary>The namespace that starts an extended XMP APP1 segment (XMP part 3), with its terminating zero.</summary>
private static ReadOnlySpan<byte> ExtendedXmpNamespace => "http://ns.adobe.com/xmp/extension/\0"u8;
private void NotRead(string name)
{
_unread ??= [];
if (!_unread.Contains(name))
{
_unread.Add(name);
}
} }
/// <summary>The namespace that starts an XMP APP1 segment, with its terminating zero.</summary> /// <summary>The namespace that starts an XMP APP1 segment, with its terminating zero.</summary>
+14 -1
View File
@@ -103,6 +103,8 @@ public static class PngDecoder
public string? Xmp; public string? Xmp;
public List<ImageText>? Texts; public List<ImageText>? Texts;
public List<string>? ColorChunks; public List<string>? ColorChunks;
public List<string>? Unread;
public bool Animated;
public int Channels => ColorType switch { 2 => 3, 4 => 2, 6 => 4, _ => 1 }; public int Channels => ColorType switch { 2 => 3, 4 => 2, 6 => 4, _ => 1 };
@@ -114,7 +116,7 @@ public static class PngDecoder
Height, Height,
FrameCount, FrameCount,
ColorType is 4 or 6 || HasColorKey || HasPaletteAlpha, ColorType is 4 or 6 || HasColorKey || HasPaletteAlpha,
Exif is null && Icc is null && Xmp is null && Texts is null && ColorChunks is null Exif is null && Icc is null && Xmp is null && Texts is null && ColorChunks is null && Unread is null
? ImageMetadata.Empty ? ImageMetadata.Empty
: new ImageMetadata : new ImageMetadata
{ {
@@ -125,9 +127,11 @@ public static class PngDecoder
Xmp = Xmp, Xmp = Xmp,
Texts = Texts ?? [], Texts = Texts ?? [],
ColorChunks = ColorChunks ?? [], ColorChunks = ColorChunks ?? [],
Unread = Unread ?? [],
}) })
{ {
BitsPerSample = ColorType == 3 ? 8 : BitDepth, BitsPerSample = ColorType == 3 ? 8 : BitDepth,
IsAnimated = Animated,
}; };
} }
@@ -248,6 +252,7 @@ public static class PngDecoder
break; break;
case "acTL": case "acTL":
file.Animated |= idatState == 0;
if (payload.Length >= 8 && idatState == 0) if (payload.Length >= 8 && idatState == 0)
{ {
var frames = BinaryPrimitives.ReadUInt32BigEndian(payload); var frames = BinaryPrimitives.ReadUInt32BigEndian(payload);
@@ -272,12 +277,20 @@ public static class PngDecoder
break; break;
case "fcTL" or "fdAT":
break;
default: default:
if (critical) if (critical)
{ {
throw new ImageFormatNotSupportedException($"PNG con un blocco critico che Febe non conosce ({name})."); throw new ImageFormatNotSupportedException($"PNG con un blocco critico che Febe non conosce ({name}).");
} }
if (readMetadata && !(file.Unread ??= []).Contains(name))
{
file.Unread.Add(name);
}
break; break;
} }
} }
+56 -7
View File
@@ -576,7 +576,7 @@ internal static class Vp8LEncoder
private static int ChooseCacheBits(uint[] pixels, ReadOnlySpan<int> lengths) private static int ChooseCacheBits(uint[] pixels, ReadOnlySpan<int> lengths)
{ {
var bestBits = 0; var bestBits = 0;
var bestCost = double.MaxValue; var bestCost = long.MaxValue;
var green = new int[256 + NumLengthCodes + (1 << 10)]; var green = new int[256 + NumLengthCodes + (1 << 10)];
var red = new int[256]; var red = new int[256];
var blue = new int[256]; var blue = new int[256];
@@ -637,8 +637,10 @@ internal static class Vp8LEncoder
return bestBits; return bestBits;
} }
// Bits to code the counts with an ideal code, plus a rough price for describing the code. // Bits to code the counts with an ideal code, plus a rough price for describing the code, in units of
private static double Entropy(ReadOnlySpan<int> counts) // 2^-LogFractionBits bits: Σ c·log2(total / c) = total·log2(total) − Σ c·log2(c), in integers only, so that the
// choice never depends on the floating-point library of the platform (decision D9 of tappa E3).
internal static long Entropy(ReadOnlySpan<int> counts)
{ {
long total = 0; long total = 0;
var used = 0; var used = 0;
@@ -650,19 +652,66 @@ internal static class Vp8LEncoder
if (used <= 1) if (used <= 1)
{ {
return 8; return 8L << LogFractionBits;
} }
var bits = 0.0; var bits = total * Log2Fixed((ulong)total);
foreach (var c in counts) foreach (var c in counts)
{ {
if (c > 0) if (c > 0)
{ {
bits -= c * Math.Log2((double)c / total); bits -= c * Log2Fixed((ulong)c);
} }
} }
return bits + (used * 4.0); return bits + ((long)used * 4 << LogFractionBits);
}
/// <summary>Fractional bits of <see cref="Log2Fixed"/>.</summary>
internal const int LogFractionBits = 16;
/// <summary>Base-2 logarithms of 1-4095 in fixed point, computed once by <see cref="Log2Exact"/>.</summary>
private static readonly long[] SmallLog2 = BuildSmallLog2();
private static long[] BuildSmallLog2()
{
var table = new long[4096];
for (var i = 1; i < table.Length; i++)
{
table[i] = Log2Exact((ulong)i);
}
return table;
}
/// <summary>log2(<paramref name="value"/>) in fixed point with <see cref="LogFractionBits"/> fractional bits; 0 for 0.</summary>
internal static long Log2Fixed(ulong value) => value < (ulong)SmallLog2.Length ? SmallLog2[value] : Log2Exact(value);
/// <summary>
/// log2 by integers only: the integer part from the highest bit, the fraction bit by bit by repeated squaring of
/// the mantissa (kept as a 1.31 fixed-point number), rounded down.
/// </summary>
private static long Log2Exact(ulong value)
{
if (value == 0)
{
return 0;
}
var high = 63 - System.Numerics.BitOperations.LeadingZeroCount(value);
ulong mantissa = high >= 31 ? value >> (high - 31) : value << (31 - high); // in [2^31, 2^32): 1.0 ≤ m < 2.0
long fraction = 0;
for (var bit = LogFractionBits - 1; bit >= 0; bit--)
{
mantissa = (mantissa * mantissa) >> 31;
if (mantissa >= 1UL << 32)
{
mantissa >>= 1;
fraction |= 1L << bit;
}
}
return ((long)high << LogFractionBits) | fraction;
} }
// Writes a prefix code: the simple form for at most two symbols below 256, otherwise the code lengths, run-length // Writes a prefix code: the simple form for at most two symbols below 256, otherwise the code lengths, run-length
+30 -2
View File
@@ -96,6 +96,8 @@ public static class WebPDecoder
public byte[]? Exif; public byte[]? Exif;
public byte[]? Icc; public byte[]? Icc;
public string? Xmp; public string? Xmp;
public bool Animated;
public List<string>? Unread;
public ImageInfo ToInfo() => new( public ImageInfo ToInfo() => new(
ImageFormat.WebP, ImageFormat.WebP,
@@ -103,9 +105,12 @@ public static class WebPDecoder
Height, Height,
FrameCount, FrameCount,
HasAlpha, HasAlpha,
Exif is null && Icc is null && Xmp is null Exif is null && Icc is null && Xmp is null && Unread is null
? ImageMetadata.Empty ? ImageMetadata.Empty
: new ImageMetadata { Exif = Exif, Orientation = Exif is null ? 1 : ExifOrientation.Read(Exif), IccProfile = Icc, Xmp = Xmp }); : new ImageMetadata { Exif = Exif, Orientation = Exif is null ? 1 : ExifOrientation.Read(Exif), IccProfile = Icc, Xmp = Xmp, Unread = Unread ?? [] })
{
IsAnimated = Animated,
};
} }
private static WebPFile Parse(byte[] data, int offset, int length, ImageLimits limits, bool readMetadata) private static WebPFile Parse(byte[] data, int offset, int length, ImageLimits limits, bool readMetadata)
@@ -174,7 +179,11 @@ public static class WebPDecoder
var chunk = chunks[i]; var chunk = chunks[i];
switch (chunk.Type) switch (chunk.Type)
{ {
case Anim:
file.Animated = true;
break;
case Anmf: case Anmf:
file.Animated = true;
if (frames++ == 0) if (frames++ == 0)
{ {
file.FirstFrame = ReadFrame(data, chunk, file.Width, file.Height); file.FirstFrame = ReadFrame(data, chunk, file.Width, file.Height);
@@ -200,6 +209,25 @@ public static class WebPDecoder
case Xmp when readMetadata && file.Xmp is null && chunk.Length <= budget: case Xmp when readMetadata && file.Xmp is null && chunk.Length <= budget:
file.Xmp = Encoding.UTF8.GetString(data, chunk.Start, chunk.Length); file.Xmp = Encoding.UTF8.GetString(data, chunk.Start, chunk.Length);
budget -= chunk.Length; budget -= chunk.Length;
break;
case Iccp or Exif or Xmp:
break;
default:
if (readMetadata)
{
var name = string.Create(4, chunk.Type, static (c, t) =>
{
for (var k = 0; k < 4; k++)
{
c[k] = (char)(byte)(t >> (8 * k));
}
}).TrimEnd();
if (!(file.Unread ??= []).Contains(name))
{
file.Unread.Add(name);
}
}
break; break;
} }
} }
+145
View File
@@ -0,0 +1,145 @@
using System.Globalization;
namespace Febe.Core.Export;
/// <summary>
/// The instants, names and labels of frames (spec §4.10 «Fotogrammi», decisions D12 and D13 of tappa E3): which instants
/// a request asks for, the suffix a frame file gets, and how an instant is shown.
/// </summary>
public static class ExportFrames
{
/// <summary>The shortest step of «Uno ogni k secondi».</summary>
public static readonly TimeSpan MinEvery = TimeSpan.FromMilliseconds(100);
/// <summary>The most frames of «N in tutto».</summary>
public const int MaxCount = 1000;
/// <summary>The most frames taken from one video.</summary>
public const int MaxPerVideo = 1000;
/// <summary>The most frames of one request.</summary>
public const int MaxPerRequest = 20000;
/// <summary>Why a request over <see cref="MaxPerVideo"/> is refused.</summary>
public const string OverCapMessage = "Più di 1.000 fotogrammi per un video: scegli un intervallo più lungo";
/// <summary>The suffix of the single frame of «Salva il fotogramma» (tappa E4).</summary>
public const string SingleSuffix = "_fotogramma";
/// <summary>How many frames <paramref name="request"/> asks of a video of <paramref name="duration"/>.</summary>
public static long FrameCount(TimeSpan duration, ExportFramesRequest request)
{
ArgumentNullException.ThrowIfNull(request);
return request.Mode switch
{
FrameMode.At => 1,
FrameMode.Every => EveryCount(duration, request.Every ?? throw new ArgumentException("Manca l'intervallo dei fotogrammi.", nameof(request))),
FrameMode.Count => request.Count ?? throw new ArgumentException("Manca il numero dei fotogrammi.", nameof(request)),
_ => throw new ArgumentOutOfRangeException(nameof(request)),
};
}
/// <summary>
/// The instants <paramref name="request"/> asks of a video of <paramref name="duration"/>, in increasing order.
/// Refused (<see cref="ArgumentException"/> with <see cref="OverCapMessage"/>) over <see cref="MaxPerVideo"/>.
/// </summary>
public static IReadOnlyList<TimeSpan> Instants(TimeSpan duration, ExportFramesRequest request)
{
ArgumentNullException.ThrowIfNull(request);
return request.Mode switch
{
FrameMode.At => [request.At is { } at && at > TimeSpan.Zero ? at : TimeSpan.Zero],
FrameMode.Every => Every(duration, request.Every ?? throw new ArgumentException("Manca l'intervallo dei fotogrammi.", nameof(request))),
FrameMode.Count => Spread(duration, request.Count ?? throw new ArgumentException("Manca il numero dei fotogrammi.", nameof(request))),
_ => throw new ArgumentOutOfRangeException(nameof(request)),
};
}
/// <summary>«Uno ogni k secondi»: 0, k, 2k… before <paramref name="duration"/> (only 0 for a video without length).</summary>
public static IReadOnlyList<TimeSpan> Every(TimeSpan duration, TimeSpan step)
{
if (step < MinEvery)
{
throw new ArgumentOutOfRangeException(nameof(step), "L'intervallo minimo è 0,1 secondi.");
}
var count = EveryCount(duration, step);
if (count > MaxPerVideo)
{
throw new ArgumentException(OverCapMessage, nameof(step));
}
var instants = new TimeSpan[count];
for (var i = 0; i < count; i++)
{
instants[i] = TimeSpan.FromTicks(step.Ticks * i);
}
return instants;
}
/// <summary>«N in tutto»: (i + ½) · duration / N for i = 0…N − 1, in 100 ns ticks rounded down.</summary>
public static IReadOnlyList<TimeSpan> Spread(TimeSpan duration, int count)
{
if (count is < 1 or > MaxCount)
{
throw new ArgumentOutOfRangeException(nameof(count), "Da 1 a 1.000 fotogrammi.");
}
var length = (Int128)Math.Max(0, duration.Ticks);
var instants = new TimeSpan[count];
for (var i = 0; i < count; i++)
{
instants[i] = TimeSpan.FromTicks((long)(((2 * i) + 1) * length / (2 * (Int128)count)));
}
return instants;
}
/// <summary>
/// The suffix of a frame file, appended to the stem: <c>_t0m12s340</c> (the actual instant: minutes, seconds on two
/// digits, milliseconds on three) for «Questo istante» and «Uno ogni k secondi»; <c>_f001</c> (the position among
/// the <paramref name="count"/> instants, at least three digits) for «N in tutto».
/// </summary>
/// <param name="index">0-based position of the instant in the request.</param>
public static string Suffix(FrameMode mode, TimeSpan actual, int index, int count)
{
if (mode == FrameMode.Count)
{
var digits = Math.Max(3, Math.Max(1, count).ToString(CultureInfo.InvariantCulture).Length);
return "_f" + (index + 1).ToString("D" + digits.ToString(CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
}
var ms = ActualMs(actual);
return string.Create(CultureInfo.InvariantCulture, $"_t{ms / 60000}m{ms / 1000 % 60:D2}s{ms % 1000:D3}");
}
/// <summary>
/// An instant as the viewer and the dialog show it: <c>m:ss</c> («0:01»), followed by a comma and the milliseconds
/// without trailing zeros only when it is not a whole second («0:01,25»).
/// </summary>
public static string Label(TimeSpan actual)
{
var ms = ActualMs(actual);
var label = string.Create(CultureInfo.InvariantCulture, $"{ms / 60000}:{ms / 1000 % 60:D2}");
var fraction = ms % 1000;
return fraction == 0
? label
: label + "," + fraction.ToString("D3", CultureInfo.InvariantCulture).TrimEnd('0');
}
/// <summary>The identity of a frame's instant: its shown time in milliseconds, rounded up.</summary>
public static long ActualMs(TimeSpan shown) =>
shown <= TimeSpan.Zero ? 0 : (shown.Ticks + TimeSpan.TicksPerMillisecond - 1) / TimeSpan.TicksPerMillisecond;
private static long EveryCount(TimeSpan duration, TimeSpan step)
{
if (step <= TimeSpan.Zero)
{
throw new ArgumentOutOfRangeException(nameof(step));
}
// 0, k, 2k… strictly before the end: ceil(duration / k), and at least the frame at 0.
return duration <= TimeSpan.Zero ? 1 : Math.Max(1, (duration.Ticks + step.Ticks - 1) / step.Ticks);
}
}
+16
View File
@@ -23,6 +23,22 @@ public abstract record ExportSelection
public sealed record Account(long AccountId) : ExportSelection; public sealed record Account(long AccountId) : ExportSelection;
} }
/// <summary>How the instants of «Fotogrammi» are chosen (spec §4.10 «Fotogrammi»).</summary>
public enum FrameMode
{
/// <summary>«Questo istante»: one frame at <see cref="ExportFramesRequest.At"/>.</summary>
At,
/// <summary>«Uno ogni k secondi»: at 0, k, 2k… before the end.</summary>
Every,
/// <summary>«N in tutto»: N frames spread over the video, each in the middle of its share.</summary>
Count,
}
/// <summary>A request of frames of videos, in a photo format (Jpg, Png or WebpLossless).</summary>
public sealed record ExportFramesRequest(FrameMode Mode, TimeSpan? At, TimeSpan? Every, int? Count, ExportFormat Format);
/// <summary>A «Copia in…»: what to copy, whether «Tolti» and «Superati» are copied again (D9), who asked.</summary> /// <summary>A «Copia in…»: what to copy, whether «Tolti» and «Superati» are copied again (D9), who asked.</summary>
public sealed record ExportJobRequest(ExportSelection Selection, bool CopyAgain = false, ExportRunOrigin Origin = ExportRunOrigin.Manual); public sealed record ExportJobRequest(ExportSelection Selection, bool CopyAgain = false, ExportRunOrigin Origin = ExportRunOrigin.Manual);
+34 -6
View File
@@ -4,6 +4,12 @@ using Febe.Core.Library;
namespace Febe.Core.Export; namespace Febe.Core.Export;
/// <summary>
/// How the file name of a copy differs from the library's (tappa E3): the extension of the effective format
/// («.jpg»; null keeps the source's) and the suffix of a frame («_t0m12s340»; null for none), appended to the stem.
/// </summary>
public sealed record ExportNameOptions(string? Extension, string? Suffix);
/// <summary>Paths and content types of the export (spec §4.10).</summary> /// <summary>Paths and content types of the export (spec §4.10).</summary>
public static class ExportPaths public static class ExportPaths
{ {
@@ -63,7 +69,8 @@ public static class ExportPaths
Media media, Media media,
string? highlightTitle, string? highlightTitle,
bool inHighlight, bool inHighlight,
TimeZoneInfo zone) TimeZoneInfo zone,
ExportNameOptions? name = null)
{ {
ArgumentNullException.ThrowIfNull(d); ArgumentNullException.ThrowIfNull(d);
ArgumentNullException.ThrowIfNull(library); ArgumentNullException.ThrowIfNull(library);
@@ -106,22 +113,42 @@ public static class ExportPaths
segments = scheme.Render(values, zone); segments = scheme.Render(values, zone);
} }
segments = Renamed(segments, name);
return d.Scope == ExportScope.General ? [WindowsFileNames.SanitizeSegment(account.Username), .. segments] : segments; return d.Scope == ExportScope.General ? [WindowsFileNames.SanitizeSegment(account.Username), .. segments] : segments;
} }
/// <summary>The last segment with the suffix appended to its stem and the extension of <paramref name="name"/>.</summary>
private static IReadOnlyList<string> Renamed(IReadOnlyList<string> segments, ExportNameOptions? name)
{
if (name is null || segments.Count == 0 || (name.Extension is null && string.IsNullOrEmpty(name.Suffix)))
{
return segments;
}
var (stem, extension) = WindowsFileNames.SplitExtension(segments[^1]);
var fileName = WindowsFileNames.SanitizeSegment(stem + (name.Suffix ?? string.Empty) + (name.Extension ?? extension));
return [.. segments.Take(segments.Count - 1), fileName];
}
/// <summary>The relative path ('/' separated) of a copy: the segments fitted to the length limit under the root.</summary> /// <summary>The relative path ('/' separated) of a copy: the segments fitted to the length limit under the root.</summary>
/// <param name="d">The destination.</param>
/// <param name="segments">The segments of <see cref="Segments"/>.</param>
/// <param name="maxPath">The longest full path.</param>
/// <param name="keepSuffix">The frame suffix of the file name, never cut by the shortening.</param>
/// <exception cref="PathTooLongException">Even shortened, the path does not fit.</exception> /// <exception cref="PathTooLongException">Even shortened, the path does not fit.</exception>
public static string RelativePathFor(ExportDestination d, IReadOnlyList<string> segments, int maxPath = WindowsFileNames.MaxPathLength) public static string RelativePathFor(ExportDestination d, IReadOnlyList<string> segments, int maxPath = WindowsFileNames.MaxPathLength, string? keepSuffix = null)
{ {
ArgumentNullException.ThrowIfNull(d); ArgumentNullException.ThrowIfNull(d);
return string.Join('/', WindowsFileNames.FitPath(d.RootPath, segments, maxPath)); return string.Join('/', WindowsFileNames.FitPath(d.RootPath, segments, maxPath, keepSuffix));
} }
/// <summary> /// <summary>
/// The name the safe writer gives a file at its <paramref name="attempt"/>-th try when the planned name is taken /// The name the safe writer gives a file at its <paramref name="attempt"/>-th try when the planned name is taken
/// («nome (2).jpg», «nome (3).jpg», …), so a resumed copy finds a file it renamed before a crash. /// («nome (2).jpg», «nome (3).jpg», …), so a resumed copy finds a file it renamed before a crash. With
/// <paramref name="keepSuffix"/> (a frame suffix, <see cref="SafeWriteOptions.KeepSuffix"/>) the number comes after
/// it and both survive the shortening: «x_f001 (2).png».
/// </summary> /// </summary>
public static string NumberedName(string root, string relativePath, int attempt, int maxPath = WindowsFileNames.MaxPathLength) public static string NumberedName(string root, string relativePath, int attempt, int maxPath = WindowsFileNames.MaxPathLength, string? keepSuffix = null)
{ {
ArgumentException.ThrowIfNullOrWhiteSpace(relativePath); ArgumentException.ThrowIfNullOrWhiteSpace(relativePath);
var segments = LibraryLayout.ToStored(relativePath).Split('/', StringSplitOptions.RemoveEmptyEntries); var segments = LibraryLayout.ToStored(relativePath).Split('/', StringSplitOptions.RemoveEmptyEntries);
@@ -132,7 +159,8 @@ public static class ExportPaths
var (stem, extension) = WindowsFileNames.SplitExtension(segments[^1]); var (stem, extension) = WindowsFileNames.SplitExtension(segments[^1]);
var name = WindowsFileNames.SanitizeSegment(string.Create(CultureInfo.InvariantCulture, $"{stem} ({attempt}){extension}")); var name = WindowsFileNames.SanitizeSegment(string.Create(CultureInfo.InvariantCulture, $"{stem} ({attempt}){extension}"));
return string.Join('/', WindowsFileNames.FitPath(root, [.. segments[..^1], name], maxPath)); var keep = keepSuffix is null ? null : string.Create(CultureInfo.InvariantCulture, $"{keepSuffix} ({attempt})");
return string.Join('/', WindowsFileNames.FitPath(root, [.. segments[..^1], name], maxPath, keep));
} }
/// <summary>The scheme that names an entry kind.</summary> /// <summary>The scheme that names an entry kind.</summary>
@@ -0,0 +1,29 @@
namespace Febe.Core.Library.Conversion;
/// <summary>
/// One conversion at a time across the process (tappa E3, decision D16): a photo conversion holds a decoded picture
/// and its encoder state (up to about a gigabyte for 40 megapixels), so the export and the library conversion take
/// turns, each off the calling thread.
/// </summary>
public sealed class ConversionThrottle
{
private readonly SemaphoreSlim gate = new(1, 1);
/// <summary>The throttle every conversion of the process shares.</summary>
public static ConversionThrottle Shared { get; } = new();
/// <summary>Runs <paramref name="work"/> on the thread pool once no other conversion runs.</summary>
public async Task<T> RunAsync<T>(Func<CancellationToken, T> work, CancellationToken ct)
{
ArgumentNullException.ThrowIfNull(work);
await gate.WaitAsync(ct).ConfigureAwait(false);
try
{
return await Task.Run(() => work(ct), ct).ConfigureAwait(false);
}
finally
{
gate.Release();
}
}
}
@@ -0,0 +1,213 @@
using System.Security.Cryptography;
using Febe.Core.Codecs.Containers;
using Febe.Core.Codecs.Images;
using Febe.Core.Domain;
namespace Febe.Core.Library.Conversion;
/// <summary>
/// A library file ready to be written in a format (tappa E3, spec §4.10 «Conversione del formato»): what will be
/// written and how. Dispose it once written or given up.
/// </summary>
/// <param name="Variant"><see cref="ExportVariant.Whole"/> (the file byte for byte) or <see cref="ExportVariant.Converted"/>.</param>
/// <param name="Format">The effective format: <see cref="ExportFormat.Original"/> for a whole file.</param>
/// <param name="Extension">The extension of the file written, with its dot («.jpg»; a whole file keeps its own).</param>
/// <param name="Length">The bytes <see cref="Produce"/> writes.</param>
/// <param name="Sha256">
/// The SHA-256 (lowercase hex) of what <see cref="Produce"/> writes; null for a remux, known once written.
/// </param>
/// <param name="Notes">Note codes: why the file is copied as it is, or what the conversion could not carry.</param>
/// <param name="Produce">Writes the file into the stream given.</param>
public sealed record MediaConversionResult(ExportVariant Variant, ExportFormat Format, string Extension,
long Length, string? Sha256, IReadOnlyList<string> Notes, Func<Stream, CancellationToken, Task> Produce) : IDisposable
{
/// <summary>The note prefix of a video that cannot be remuxed; the <see cref="RemuxRefusal"/> follows the colon.</summary>
public const string AsIsNotRemuxable = "AsIsNotRemuxable";
/// <summary>Converted bytes or a remux plan, released on <see cref="Dispose"/>.</summary>
internal object? Held { get; set; }
/// <inheritdoc />
public void Dispose() => Held = null;
}
/// <summary>
/// Prepares a library file in a target format, independent of where it goes (an export destination, the library):
/// photos are converted in memory under the <see cref="ConversionThrottle"/>, videos are remuxed into MP4 while being
/// written. The source is never changed.
/// </summary>
public static class MediaConverter
{
/// <summary>The raw camera formats, copied as they are (spec §4.10).</summary>
private static readonly HashSet<string> RawExtensions = new(StringComparer.OrdinalIgnoreCase)
{
".dng", ".cr2", ".cr3", ".nef", ".arw", ".raf", ".orf", ".rw2", ".pef", ".srw",
};
/// <summary>
/// Prepares <paramref name="relativePath"/> (only its name is used) in <paramref name="target"/>.
/// <paramref name="openRandomAccess"/> opens the source for reading, seekable; it may be called more than once.
/// </summary>
/// <exception cref="ContentChangedException">A photo's bytes do not have <paramref name="expectedSourceSha256"/>.</exception>
/// <exception cref="ArgumentException">The target does not belong to the kind of file.</exception>
public static async Task<MediaConversionResult> PrepareAsync(Func<Stream> openRandomAccess, string relativePath,
MediaKind kind, ExportFormat target, string expectedSourceSha256, ConversionThrottle throttle, CancellationToken ct)
{
ArgumentNullException.ThrowIfNull(openRandomAccess);
ArgumentException.ThrowIfNullOrEmpty(relativePath);
ArgumentException.ThrowIfNullOrEmpty(expectedSourceSha256);
ArgumentNullException.ThrowIfNull(throttle);
var valid = kind == MediaKind.Photo ? ExportFormats.IsPhotoFormat(target) : ExportFormats.IsVideoFormat(target);
if (!valid)
{
throw new ArgumentException("Il formato non è adatto a questo tipo di file.", nameof(target));
}
return kind == MediaKind.Photo
? await PreparePhotoAsync(openRandomAccess, relativePath, target, expectedSourceSha256.ToLowerInvariant(), throttle, ct).ConfigureAwait(false)
: await PrepareVideoAsync(openRandomAccess, relativePath, target, expectedSourceSha256.ToLowerInvariant(), throttle, ct).ConfigureAwait(false);
}
/// <summary>The image format written for an export format; null for Original and MP4.</summary>
public static ImageFormat? ImageFormatOf(ExportFormat format) => format switch
{
ExportFormat.Jpg => ImageFormat.Jpeg,
ExportFormat.Png => ImageFormat.Png,
ExportFormat.WebpLossless => ImageFormat.WebP,
_ => null,
};
/// <summary>The extension of a converted file, with its dot.</summary>
public static string ExtensionOf(ExportFormat format) => format switch
{
ExportFormat.Jpg => ".jpg",
ExportFormat.Png => ".png",
ExportFormat.WebpLossless => ".webp",
ExportFormat.Mp4 => ".mp4",
_ => throw new ArgumentOutOfRangeException(nameof(format)),
};
private static async Task<MediaConversionResult> PreparePhotoAsync(Func<Stream> open, string relativePath,
ExportFormat target, string expected, ConversionThrottle throttle, CancellationToken ct)
{
var extension = Path.GetExtension(relativePath);
long length;
byte[]? bytes = null;
await using (var source = open())
{
length = source.Length;
if (target != ExportFormat.Original && length <= ImageConverter.MaxSourceBytes)
{
bytes = new byte[length];
await source.ReadExactlyAsync(bytes, ct).ConfigureAwait(false);
}
}
if (bytes is null)
{
// Original, or too large to hold: the file byte for byte, checked against its SHA while written.
return Whole(open, extension, length, expected, target == ExportFormat.Original ? [] : [ImageConversionLosses.AsIsTooLarge]);
}
var sha = Convert.ToHexStringLower(SHA256.HashData(bytes));
if (!string.Equals(sha, expected, StringComparison.Ordinal))
{
throw new ContentChangedException("Il file della libreria è cambiato durante la copia.");
}
if (RawExtensions.Contains(extension))
{
return Whole(bytes, extension, sha, [ImageConversionLosses.AsIsRaw]);
}
var format = ImageFormatOf(target)!.Value;
var check = ImageConverter.Check(bytes, format);
switch (check.Action)
{
case ImageConversionAction.CopyAsIs:
return Whole(bytes, extension, sha, []);
case ImageConversionAction.CopyOriginal:
return Whole(bytes, extension, sha, check.NoteCode is { } note ? [note] : []);
}
var converted = 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<MediaConversionResult> PrepareVideoAsync(Func<Stream> open, string relativePath,
ExportFormat target, string expected, ConversionThrottle throttle, CancellationToken ct)
{
var extension = Path.GetExtension(relativePath);
var fileName = Path.GetFileName(relativePath);
var (length, refusal, plan) = await throttle.RunAsync(token =>
{
using var source = open();
var size = source.Length;
if (target == ExportFormat.Original)
{
return (size, RemuxRefusal.AlreadyMp4, (RemuxPlan?)null);
}
var outcome = Mp4Remuxer.Check(source, fileName, out var made, token);
return (size, outcome, made);
}, ct).ConfigureAwait(false);
if (refusal == RemuxRefusal.None && plan is not null)
{
return new MediaConversionResult(ExportVariant.Converted, ExportFormat.Mp4, ".mp4", plan.OutputLength, null,
plan.Losses, (output, token) => Task.Run(
() =>
{
using var source = open();
Mp4Remuxer.Write(plan, source, output, token);
},
token))
{
Held = plan,
};
}
string[] notes = refusal == RemuxRefusal.AlreadyMp4 ? [] : [$"{MediaConversionResult.AsIsNotRemuxable}:{refusal}"];
return Whole(open, extension, length, expected, notes);
}
/// <summary>A whole file streamed from the source (a video, or a photo not read into memory).</summary>
private static MediaConversionResult Whole(Func<Stream> open, string extension, long length, string sha, IReadOnlyList<string> notes) =>
new(ExportVariant.Whole, ExportFormat.Original, extension, length, sha, notes, async (output, token) =>
{
await using var source = open();
await source.CopyToAsync(output, token).ConfigureAwait(false);
});
/// <summary>A whole photo from the bytes already read and checked.</summary>
private static MediaConversionResult Whole(byte[] bytes, string extension, string sha, IReadOnlyList<string> notes) =>
new(ExportVariant.Whole, ExportFormat.Original, extension, bytes.Length, sha, notes, Writer(bytes)) { Held = bytes };
private static Func<Stream, CancellationToken, Task> Writer(byte[] data) =>
(output, token) => output.WriteAsync(data, token).AsTask();
}
+130 -4
View File
@@ -42,6 +42,12 @@ public sealed record SafeWriteOptions
/// is removed and an <see cref="IOException"/> says so. /// is removed and an <see cref="IOException"/> says so.
/// </summary> /// </summary>
public bool VerifyFromDisk { get; init; } public bool VerifyFromDisk { get; init; }
/// <summary>
/// The end of the stem of the file name that a shortening or a free name never cuts (the frame suffix of tappa
/// E3, «_t0m12s340»): a free name is «nome_t0m12s340 (2).png», as <c>ExportPaths.NumberedName</c> gives it.
/// </summary>
public string? KeepSuffix { get; init; }
} }
/// <summary>The content exceeded <see cref="SafeWriteOptions.MaxBytes"/>; nothing was kept.</summary> /// <summary>The content exceeded <see cref="SafeWriteOptions.MaxBytes"/>; nothing was kept.</summary>
@@ -164,6 +170,38 @@ public sealed class SafeFileWriter(int maxPathLength = WindowsFileNames.MaxPathL
CancellationToken ct = default) CancellationToken ct = default)
{ {
ArgumentNullException.ThrowIfNull(source); ArgumentNullException.ThrowIfNull(source);
return await SaveCoreAsync((path, o, token) => WriteTempAsync(source, path, o, token), rootFolder, tempDirectory, decide, options, ct)
.ConfigureAwait(false);
}
/// <summary>
/// As <see cref="SaveAsync(Stream, string, string, Func{FileDigest, CancellationToken, ValueTask{string}}, SafeWriteOptions, CancellationToken)"/>,
/// for content that is made while it is written (a converted photo, a remuxed video, a frame): <paramref name="produce"/>
/// writes it into the temporary file, through a stream that hashes and counts it (and honours
/// <see cref="SafeWriteOptions.MaxBytes"/> and <see cref="SafeWriteOptions.Progress"/>); then the same checks,
/// <paramref name="decide"/> and the free-name rename. Our own temporary file is removed on any failure.
/// </summary>
public async Task<SavedFile?> SaveAsync(
Func<Stream, CancellationToken, Task> produce,
string rootFolder,
string tempDirectory,
Func<FileDigest, CancellationToken, ValueTask<string?>> decide,
SafeWriteOptions? options = null,
CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(produce);
return await SaveCoreAsync((path, o, token) => ProduceTempAsync(produce, path, o, token), rootFolder, tempDirectory, decide, options, ct)
.ConfigureAwait(false);
}
private async Task<SavedFile?> SaveCoreAsync(
Func<string, SafeWriteOptions, CancellationToken, Task<FileDigest>> write,
string rootFolder,
string tempDirectory,
Func<FileDigest, CancellationToken, ValueTask<string?>> decide,
SafeWriteOptions? options,
CancellationToken ct)
{
ArgumentException.ThrowIfNullOrWhiteSpace(rootFolder); ArgumentException.ThrowIfNullOrWhiteSpace(rootFolder);
ArgumentNullException.ThrowIfNull(decide); ArgumentNullException.ThrowIfNull(decide);
options ??= new SafeWriteOptions(); options ??= new SafeWriteOptions();
@@ -180,7 +218,7 @@ public sealed class SafeFileWriter(int maxPathLength = WindowsFileNames.MaxPathL
try try
{ {
var digest = await WriteTempAsync(source, tempPath, options, ct).ConfigureAwait(false); var digest = await write(tempPath, options, ct).ConfigureAwait(false);
ct.ThrowIfCancellationRequested(); ct.ThrowIfCancellationRequested();
if (options.VerifyFromDisk) if (options.VerifyFromDisk)
{ {
@@ -194,7 +232,7 @@ public sealed class SafeFileWriter(int maxPathLength = WindowsFileNames.MaxPathL
} }
ct.ThrowIfCancellationRequested(); ct.ThrowIfCancellationRequested();
var finalPath = MoveToFreeName(tempPath, root, desired, out var relative); var finalPath = MoveToFreeName(tempPath, root, desired, options.KeepSuffix, out var relative);
var timeSet = true; var timeSet = true;
if (options.LastWriteTime is { } time) if (options.LastWriteTime is { } time)
{ {
@@ -289,6 +327,93 @@ public sealed class SafeFileWriter(int maxPathLength = WindowsFileNames.MaxPathL
return new FileDigest(total, Convert.ToHexStringLower(hash.GetHashAndReset())); return new FileDigest(total, Convert.ToHexStringLower(hash.GetHashAndReset()));
} }
private static async Task<FileDigest> ProduceTempAsync(Func<Stream, CancellationToken, Task> produce, string tempPath, SafeWriteOptions options, CancellationToken ct)
{
await using var target = new FileStream(tempPath, FileMode.CreateNew, FileAccess.Write, FileShare.None, BufferSize, FileOptions.Asynchronous);
using var hashing = new HashingStream(target, options);
await produce(hashing, ct).ConfigureAwait(false);
ct.ThrowIfCancellationRequested();
await target.FlushAsync(ct).ConfigureAwait(false);
target.Flush(flushToDisk: true);
return hashing.Digest();
}
/// <summary>A write-only stream that hashes and counts what goes through it into the temporary file.</summary>
private sealed class HashingStream(Stream inner, SafeWriteOptions options) : Stream
{
private readonly IncrementalHash hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256);
private long total;
public override bool CanRead => false;
public override bool CanSeek => false;
public override bool CanWrite => true;
public override long Length => total;
public override long Position
{
get => total;
set => throw new NotSupportedException();
}
public FileDigest Digest() => new(total, Convert.ToHexStringLower(hash.GetHashAndReset()));
public override void Flush() => inner.Flush();
public override Task FlushAsync(CancellationToken cancellationToken) => inner.FlushAsync(cancellationToken);
public override int Read(byte[] buffer, int offset, int count) => throw new NotSupportedException();
public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException();
public override void SetLength(long value) => throw new NotSupportedException();
public override void Write(byte[] buffer, int offset, int count) => Write(buffer.AsSpan(offset, count));
public override void Write(ReadOnlySpan<byte> buffer)
{
Count(buffer);
inner.Write(buffer);
options.Progress?.Report(total);
}
public override void WriteByte(byte value) => Write([value]);
public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) =>
WriteAsync(buffer.AsMemory(offset, count), cancellationToken).AsTask();
public override async ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken = default)
{
Count(buffer.Span);
await inner.WriteAsync(buffer, cancellationToken).ConfigureAwait(false);
options.Progress?.Report(total);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
hash.Dispose();
}
base.Dispose(disposing);
}
private void Count(ReadOnlySpan<byte> buffer)
{
total += buffer.Length;
if (options.MaxBytes is { } max && total > max)
{
throw new FileTooLargeException(
string.Create(CultureInfo.InvariantCulture, $"Il file supera il limite di {max} byte: non viene salvato."));
}
hash.AppendData(buffer);
}
}
/// <summary>Reads the temporary file back and compares its SHA-256 with the one computed while writing.</summary> /// <summary>Reads the temporary file back and compares its SHA-256 with the one computed while writing.</summary>
private static async Task VerifyFromDiskAsync(string tempPath, FileDigest digest, CancellationToken ct) private static async Task VerifyFromDiskAsync(string tempPath, FileDigest digest, CancellationToken ct)
{ {
@@ -316,7 +441,7 @@ public sealed class SafeFileWriter(int maxPathLength = WindowsFileNames.MaxPathL
return segments.Count == 0 ? throw new ArgumentException("Il nome del file è vuoto.", nameof(relativePath)) : segments; return segments.Count == 0 ? throw new ArgumentException("Il nome del file è vuoto.", nameof(relativePath)) : segments;
} }
private string MoveToFreeName(string tempPath, string root, string desiredRelativePath, out string relative) private string MoveToFreeName(string tempPath, string root, string desiredRelativePath, string? keepSuffix, out string relative)
{ {
var segments = Segments(desiredRelativePath); var segments = Segments(desiredRelativePath);
var (stem, extension) = WindowsFileNames.SplitExtension(segments[^1]); var (stem, extension) = WindowsFileNames.SplitExtension(segments[^1]);
@@ -324,7 +449,8 @@ public sealed class SafeFileWriter(int maxPathLength = WindowsFileNames.MaxPathL
{ {
var name = attempt == 1 ? segments[^1] : string.Create(CultureInfo.InvariantCulture, $"{stem} ({attempt}){extension}"); var name = attempt == 1 ? segments[^1] : string.Create(CultureInfo.InvariantCulture, $"{stem} ({attempt}){extension}");
var candidate = segments.Take(segments.Count - 1).Append(WindowsFileNames.SanitizeSegment(name)).ToList(); var candidate = segments.Take(segments.Count - 1).Append(WindowsFileNames.SanitizeSegment(name)).ToList();
var fitted = WindowsFileNames.FitPath(root, candidate, maxPathLength); var keep = keepSuffix is null ? null : attempt == 1 ? keepSuffix : string.Create(CultureInfo.InvariantCulture, $"{keepSuffix} ({attempt})");
var fitted = WindowsFileNames.FitPath(root, candidate, maxPathLength, keep);
relative = string.Join('/', fitted); relative = string.Join('/', fitted);
var finalPath = LibraryLayout.FullPath(root, relative); var finalPath = LibraryLayout.FullPath(root, relative);
Directory.CreateDirectory(Path.GetDirectoryName(finalPath)!); Directory.CreateDirectory(Path.GetDirectoryName(finalPath)!);
+114 -28
View File
@@ -58,7 +58,7 @@ public sealed record VideoStillness(bool IsStill, int SampledFrames, double Diff
/// (<see cref="H264Decoder"/>, <see cref="H265Decoder"/>). Videos in other codecs (VP9, AV1, ...) give no frame: the /// (<see cref="H264Decoder"/>, <see cref="H265Decoder"/>). Videos in other codecs (VP9, AV1, ...) give no frame: the
/// interface shows the neutral tile. /// interface shows the neutral tile.
/// </summary> /// </summary>
public sealed class VideoFrameDecoder public sealed partial class VideoFrameDecoder
{ {
/// <summary>Differences up to this value (0–255) count as compression noise of a still picture.</summary> /// <summary>Differences up to this value (0–255) count as compression noise of a still picture.</summary>
public const double StillThreshold = 3.0; public const double StillThreshold = 3.0;
@@ -77,8 +77,6 @@ public sealed class VideoFrameDecoder
/// <summary>How far back from a sample flagged as key the decoder looks for one it can really start from.</summary> /// <summary>How far back from a sample flagged as key the decoder looks for one it can really start from.</summary>
private const int MaxRunStartSearch = 2000; private const int MaxRunStartSearch = 2000;
private static readonly DateTimeOffset AnyDate = new(9000, 1, 1, 0, 0, 0, TimeSpan.Zero);
private readonly TimeSpan budget; private readonly TimeSpan budget;
private readonly int maxRun; private readonly int maxRun;
@@ -184,10 +182,10 @@ public sealed class VideoFrameDecoder
// The frame where the run starts comes along: it stands for a target that gives no picture (a RASL picture // The frame where the run starts comes along: it stands for a target that gives no picture (a RASL picture
// of the HEVC CRA picture decoding starts from, a damaged sample). // of the HEVC CRA picture decoding starts from, a damaged sample).
var frames = decoding.Decode(start < target ? [start, target] : [target], ct); var frames = decoding.DecodeAll(start < target ? [start, target] : [target], ct);
if (!frames.TryGetValue(target, out var frame) && !frames.TryGetValue(start, out frame) && target != 0) if (!frames.TryGetValue(target, out var frame) && !frames.TryGetValue(start, out frame) && target != 0)
{ {
frames = new Decoding(stream, video, maxRun).Decode([0], ct); frames = new Decoding(stream, video, maxRun).DecodeAll([0], ct);
frames.TryGetValue(0, out frame); frames.TryGetValue(0, out frame);
} }
@@ -248,7 +246,7 @@ public sealed class VideoFrameDecoder
return null; return null;
} }
var frames = decoding.Decode([.. targets], ct); var frames = decoding.DecodeAll([.. targets], ct);
if (frames.Count < 2) if (frames.Count < 2)
{ {
return null; return null;
@@ -295,7 +293,7 @@ public sealed class VideoFrameDecoder
private static VideoTrack? Open(Stream stream) private static VideoTrack? Open(Stream stream)
{ {
// The creation time does not matter here: any date is accepted (the readers add a day to «now»). // The creation time does not matter here: any date is accepted (the readers add a day to «now»).
var container = ContainerReader.Read(stream, AnyDate, samples: true); var container = ContainerReader.Read(stream, ContainerReader.AnyDate, samples: true);
return container?.Video is { Samples.Count: > 0 } video && video.Codec switch return container?.Video is { Samples.Count: > 0 } video && video.Codec switch
{ {
VideoCodec.H264 => video.AnnexB || video.AvcConfiguration is not null, VideoCodec.H264 => video.AnnexB || video.AvcConfiguration is not null,
@@ -362,6 +360,13 @@ public sealed class VideoFrameDecoder
/// <summary>Exact: an H.264 IDR picture, an HEVC IDR or BLA picture.</summary> /// <summary>Exact: an H.264 IDR picture, an HEVC IDR or BLA picture.</summary>
Idr, Idr,
/// <summary>
/// Exact for the pictures shown from it on: an HEVC CRA picture (only its RASL pictures, shown before it, are
/// lost), an H.264 I picture with a recovery point SEI whose recovery_frame_cnt is 0. Elsewhere close, as
/// <see cref="Intra"/>.
/// </summary>
Recovery,
} }
/// <summary>Size of the NAL length fields of the samples (0: Annex B), from the configuration record.</summary> /// <summary>Size of the NAL length fields of the samples (0: Annex B), from the configuration record.</summary>
@@ -436,9 +441,11 @@ public sealed class VideoFrameDecoder
/// <summary> /// <summary>
/// Decodes chosen samples, each from the random access point before it, reusing a run when the targets share it. /// Decodes chosen samples, each from the random access point before it, reusing a run when the targets share it.
/// </summary> /// </summary>
private sealed class Decoding(Stream stream, VideoTrack video, int maxRun) private sealed class Decoding(Stream stream, VideoTrack video, int maxRun, bool exact = false)
{ {
private readonly Dictionary<int, Frame> found = []; private readonly Dictionary<int, Frame> found = [];
private readonly HashSet<int> produced = [];
private readonly List<(int Sample, Frame Frame)> pending = [];
private readonly HashSet<int> wanted = []; private readonly HashSet<int> wanted = [];
private readonly int[] keys = KeyIndices(video); private readonly int[] keys = KeyIndices(video);
private readonly Dictionary<int, StartPoint> accessPoints = []; private readonly Dictionary<int, StartPoint> accessPoints = [];
@@ -458,6 +465,11 @@ public sealed class VideoFrameDecoder
/// </summary> /// </summary>
internal int RunStart(int index) internal int RunStart(int index)
{ {
if (exact)
{
return ExactStart(index);
}
var position = Array.BinarySearch(keys, index); var position = Array.BinarySearch(keys, index);
position = position >= 0 ? position : Math.Max(0, ~position - 1); position = position >= 0 ? position : Math.Max(0, ~position - 1);
var intra = -1; var intra = -1;
@@ -475,7 +487,7 @@ public sealed class VideoFrameDecoder
return index - candidate <= maxRun || intra < 0 ? candidate : intra; return index - candidate <= maxRun || intra < 0 ? candidate : intra;
} }
if (point == StartPoint.Intra && intra < 0) if (point is StartPoint.Intra or StartPoint.Recovery && intra < 0)
{ {
intra = candidate; intra = candidate;
} }
@@ -490,6 +502,34 @@ public sealed class VideoFrameDecoder
return index <= maxRun || intra < 0 ? 0 : intra; return index <= maxRun || intra < 0 ? 0 : intra;
} }
/// <summary>
/// The nearest start from which <paramref name="index"/> comes out exact, however far: an IDR picture, or a
/// recovery point shown no later than it; otherwise the first sample.
/// </summary>
private int ExactStart(int index)
{
var position = Array.BinarySearch(keys, index);
position = position >= 0 ? position : Math.Max(0, ~position - 1);
var shown = video.Samples[index].PresentationTime;
for (var tried = 0; position > 0 && tried < MaxRunStartSearch; position--, tried++)
{
var candidate = keys[position];
if (!accessPoints.TryGetValue(candidate, out var point))
{
point = AccessPointOf(candidate);
accessPoints[candidate] = point;
}
if (point == StartPoint.Idr
|| (point == StartPoint.Recovery && shown >= video.Samples[candidate].PresentationTime))
{
return candidate;
}
}
return 0;
}
private StartPoint AccessPointOf(int index) private StartPoint AccessPointOf(int index)
{ {
try try
@@ -500,7 +540,7 @@ public sealed class VideoFrameDecoder
return H265Decoder.AccessPoint(sample, lengthSize) switch return H265Decoder.AccessPoint(sample, lengthSize) switch
{ {
H265AccessPoint.Idr => StartPoint.Idr, H265AccessPoint.Idr => StartPoint.Idr,
H265AccessPoint.Cra => StartPoint.Intra, H265AccessPoint.Cra => StartPoint.Recovery,
_ => StartPoint.None, _ => StartPoint.None,
}; };
} }
@@ -508,6 +548,7 @@ public sealed class VideoFrameDecoder
return H264Decoder.AccessPoint(sample, lengthSize) switch return H264Decoder.AccessPoint(sample, lengthSize) switch
{ {
H264AccessPoint.Idr => StartPoint.Idr, H264AccessPoint.Idr => StartPoint.Idr,
H264AccessPoint.IntraPicture when H264Decoder.HasExactRecoveryPoint(sample, lengthSize) => StartPoint.Recovery,
H264AccessPoint.IntraPicture => StartPoint.Intra, H264AccessPoint.IntraPicture => StartPoint.Intra,
_ => StartPoint.None, _ => StartPoint.None,
}; };
@@ -518,7 +559,25 @@ public sealed class VideoFrameDecoder
} }
} }
internal Dictionary<int, Frame> Decode(int[] targets, CancellationToken ct) /// <summary>
/// Decodes the targets (sample indices in ascending order) and keeps every frame: the few a thumbnail or a
/// stillness check asks for.
/// </summary>
internal Dictionary<int, Frame> DecodeAll(int[] targets, CancellationToken ct)
{
foreach (var (sample, frame) in Decode(targets, ct))
{
found.TryAdd(sample, frame);
}
return found;
}
/// <summary>
/// Decodes the targets (sample indices in ascending order) and hands out each frame as soon as the sample that
/// finishes it is decoded, in decoding order, once per sample; a target that gives no picture is left out.
/// </summary>
internal IEnumerable<(int Sample, Frame Frame)> Decode(int[] targets, CancellationToken ct)
{ {
foreach (var t in targets) foreach (var t in targets)
{ {
@@ -536,29 +595,56 @@ public sealed class VideoFrameDecoder
next = key; next = key;
} }
try for (; next <= target; next++)
{ {
// Frames are matched to samples by the sample being decoded, not by the decoder's own count: a ct.ThrowIfCancellationRequested();
// sample without a picture (only parameter sets, a skipped RASL picture, or damaged) must not shift if (!Step(ref runner, next))
// the frames after it.
runner ??= new Runner(video, () => wanted.Contains(current), frame => found.TryAdd(current, frame));
for (; next <= target; next++)
{ {
ct.ThrowIfCancellationRequested(); // This run is damaged (or its samples lie past the end of a truncated file): the next target
current = next; // starts again from its own key frame, and what was decoded so far stands.
runner.Decode(ContainerReader.ReadSample(stream, video.Samples[next], ref buffer)); runner = null;
}
foreach (var item in pending)
{
yield return item;
}
pending.Clear();
if (runner is null)
{
break;
} }
} }
catch (Exception ex) when (ex is H264Exception or H265Exception or ContainerException or EndOfStreamException
or IndexOutOfRangeException or ArgumentException or InvalidOperationException)
{
// This run is damaged (or its samples lie past the end of a truncated file): the next target starts
// again from its own key frame, and what was decoded so far stands.
runner = null;
}
} }
}
return found; /// <summary>Decodes one sample; false when the stream is damaged there.</summary>
private bool Step(ref Runner? runner, int sample)
{
try
{
// Frames are matched to samples by the sample being decoded, not by the decoder's own count: a sample
// without a picture (only parameter sets, a skipped RASL picture, or damaged) must not shift the frames
// after it.
runner ??= new Runner(video, () => wanted.Contains(current), Found);
current = sample;
runner.Decode(ContainerReader.ReadSample(stream, video.Samples[sample], ref buffer));
return true;
}
catch (Exception ex) when (ex is H264Exception or H265Exception or ContainerException or EndOfStreamException
or IndexOutOfRangeException or ArgumentException or InvalidOperationException)
{
return false;
}
}
private void Found(Frame frame)
{
if (produced.Add(current))
{
pending.Add((current, frame));
}
} }
} }
+346
View File
@@ -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;
/// <summary>What <see cref="VideoFrameReader.Open"/> found about a video.</summary>
/// <param name="Available">False when no frame can be taken from it: <paramref name="Unavailable"/> says why.</param>
/// <param name="Unavailable">The Italian message shown when frames are not available; null otherwise.</param>
/// <param name="Duration">The presentation length (zero when unknown).</param>
/// <param name="Width">Width of a frame as shown (rotation applied).</param>
/// <param name="Height">Height of a frame as shown (rotation applied).</param>
/// <param name="Rotation">Clockwise rotation of the track: 0, 90, 180 or 270.</param>
/// <param name="Codec">The video codec («H264», «Hevc»), or the container's codec tag of one Febe does not decode.</param>
/// <param name="FrameDuration">The mean time between two frames (zero when unknown).</param>
/// <param name="HasAudio">Whether the container has an audio track.</param>
/// <param name="SampleCount">Samples of the video track.</param>
public sealed record VideoFrameInfo(bool Available, string? Unavailable, TimeSpan Duration, int Width, int Height,
int Rotation, string Codec, TimeSpan FrameDuration, bool HasAudio, int SampleCount);
/// <summary>A frame to take: the instant asked for and the sample really shown then (spec §4.10 «Fotogrammi»).</summary>
/// <param name="Index">Position of the instant in the request (0-based), which names the file.</param>
/// <param name="Requested">The instant asked for.</param>
/// <param name="Actual">
/// When the sample is shown, rounded up to the next 100 ns tick: what the frame's identity and name carry.
/// </param>
/// <param name="Sample">The sample index in decoding order.</param>
public sealed record VideoFrameTarget(int Index, TimeSpan Requested, TimeSpan Actual, int Sample);
/// <summary>A decoded frame, upright, in 8-bit RGBA (alpha 255). Dispose it to give the pixels back.</summary>
public sealed class VideoFrame(int index, TimeSpan requested, TimeSpan actual, RgbaImage image) : IDisposable
{
/// <summary>Position of the instant in the request.</summary>
public int Index { get; } = index;
/// <summary>The instant asked for.</summary>
public TimeSpan Requested { get; } = requested;
/// <summary>When the frame is shown.</summary>
public TimeSpan Actual { get; } = actual;
/// <summary>The pixels, rotated as the video is shown.</summary>
public RgbaImage Image { get; } = image;
/// <inheritdoc />
public void Dispose() => Image.Dispose();
}
/// <summary>
/// Frames of a video at chosen instants, at full resolution and exact (spec §4.10 «Fotogrammi»): instants are the
/// presentation times as a player shows them (ISO edit lists included), each frame decoded from a point the decoder can
/// start from exactly, and turned upright. One frame lives in memory at a time; the stream must stay open and seekable
/// while the reader is used.
/// </summary>
public sealed class VideoFrameReader : IDisposable
{
/// <summary>The message for a video whose frames Febe cannot take.</summary>
public const string NotAvailableMessage = "Fotogramma non disponibile per questo video";
private readonly Stream? stream;
private readonly VideoTrack? video;
/// <summary>Shown time of each sample in track units (presentation time plus the empty edits).</summary>
private readonly long[] shown = [];
/// <summary>The samples that can be chosen, by shown time then decoding order.</summary>
private readonly int[] order = [];
private VideoFrameReader(Stream? stream, VideoTrack? video)
{
this.stream = stream;
this.video = video;
if (video is null)
{
return;
}
var samples = video.Samples;
shown = new long[samples.Count];
for (var i = 0; i < samples.Count; i++)
{
shown[i] = samples[i].PresentationTime + video.EmptyEditDuration;
}
// Samples shown before the start (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));
}
/// <summary>
/// Opens the video in <paramref name="seekable"/> (left open: the caller disposes it after the reader). Never
/// throws for a video it cannot read: <paramref name="info"/> is then not available, and the reader gives no frame.
/// </summary>
public static VideoFrameReader Open(Stream seekable, out VideoFrameInfo info)
{
ArgumentNullException.ThrowIfNull(seekable);
MediaContainer? container;
VideoTrack? video;
try
{
seekable.Position = 0;
container = ContainerReader.Read(seekable, ContainerReader.AnyDate, samples: true);
video = container is null ? null : VideoFrameDecoder.FrameTrack(container);
}
catch (Exception ex) when (VideoFrameDecoder.IsUnreadableFile(ex))
{
container = null;
video = null;
}
if (container?.Video is not { } track || video is null)
{
var v = container?.Video;
info = new VideoFrameInfo(false, NotAvailableMessage, container?.Duration ?? TimeSpan.Zero,
v?.DisplayWidth ?? 0, v?.DisplayHeight ?? 0, v?.Rotation ?? 0, v is null ? string.Empty : Codec(v),
TimeSpan.Zero, container?.Audio is not null, v?.Samples.Count ?? 0);
return new VideoFrameReader(null, null);
}
var reader = new VideoFrameReader(seekable, video);
info = new VideoFrameInfo(true, null, reader.Duration(container), track.DisplayWidth, track.DisplayHeight,
Rotation(track.Rotation), Codec(track), reader.FrameDuration(), container.Audio is not null, track.Samples.Count);
return reader;
}
/// <summary>The length of the video from its headers only (no sample table walked through); null when unreadable.</summary>
public static TimeSpan? ProbeDuration(Stream seekable)
{
ArgumentNullException.ThrowIfNull(seekable);
try
{
seekable.Position = 0;
return ContainerReader.Read(seekable, ContainerReader.AnyDate, samples: false)?.Duration;
}
catch (Exception ex) when (VideoFrameDecoder.IsUnreadableFile(ex))
{
return null;
}
}
/// <summary>
/// The sample shown at each instant: the one with the greatest shown time not after it; the first one for an
/// instant before it, the last one for an instant past the end. Empty when the video is not available.
/// </summary>
public IReadOnlyList<VideoFrameTarget> Locate(IReadOnlyList<TimeSpan> instants)
{
ArgumentNullException.ThrowIfNull(instants);
if (video is null || order.Length == 0)
{
return [];
}
var targets = new VideoFrameTarget[instants.Count];
for (var i = 0; i < instants.Count; i++)
{
var sample = SampleAt(instants[i]);
targets[i] = new VideoFrameTarget(i, instants[i], ShownAt(sample), sample);
}
return targets;
}
/// <summary>
/// Decodes the targets lazily, in decoding order (not the order of the instants): each frame comes out as soon as it
/// is decoded and must be disposed by the caller. A target whose sample gives no picture (a damaged stream) is left
/// out; targets on the same sample each get their own copy.
/// </summary>
public IEnumerable<VideoFrame> Decode(IReadOnlyList<VideoFrameTarget> targets, CancellationToken ct)
{
ArgumentNullException.ThrowIfNull(targets);
return video is null || stream is null || targets.Count == 0 ? [] : DecodeCore(targets, ct);
}
private IEnumerable<VideoFrame> DecodeCore(IReadOnlyList<VideoFrameTarget> targets, CancellationToken ct)
{
var bySample = targets.Where(t => t.Sample >= 0 && t.Sample < shown.Length)
.GroupBy(t => t.Sample)
.ToDictionary(g => g.Key, g => g.OrderBy(t => t.Index).ToArray());
int[] samples = [.. bySample.Keys.Order()];
foreach (var (sample, image) in VideoFrameDecoder.DecodeExact(stream!, video!, samples, ct))
{
var wanted = bySample[sample];
for (var i = 0; i < wanted.Length; i++)
{
var copy = i == wanted.Length - 1 ? image : new RgbaImage(image.Width, image.Height, image.ToArray());
yield return new VideoFrame(wanted[i].Index, wanted[i].Requested, wanted[i].Actual, copy);
}
}
}
/// <inheritdoc />
public void Dispose()
{
// The stream belongs to the caller; nothing else is held.
}
private int SampleAt(TimeSpan at)
{
// Exact comparison of at (100 ns ticks) with a shown time (track units): at·timescale against shown·10⁷.
var timescale = (Int128)video!.Timescale;
var wanted = (Int128)at.Ticks * timescale;
int low = 0, high = order.Length - 1, best = -1;
while (low <= high)
{
var middle = (low + high) / 2;
if ((Int128)shown[order[middle]] * TimeSpan.TicksPerSecond <= wanted)
{
best = middle;
low = middle + 1;
}
else
{
high = middle - 1;
}
}
if (best < 0)
{
return order[0];
}
// Among samples shown at the same time, the first in decoding order.
while (best > 0 && shown[order[best - 1]] == shown[order[best]])
{
best--;
}
return order[best];
}
/// <summary>The shown time of a sample as a TimeSpan, rounded up to the tick (never before it is shown).</summary>
private TimeSpan ShownAt(int sample)
{
var timescale = (Int128)Math.Max(1, video!.Timescale);
var units = (Int128)Math.Max(0, shown[sample]);
var ticks = ((units * TimeSpan.TicksPerSecond) + timescale - 1) / timescale;
return TimeSpan.FromTicks((long)Int128.Min(ticks, TimeSpan.MaxValue.Ticks));
}
private TimeSpan Duration(MediaContainer container)
{
if (container.Duration is { } d && d > TimeSpan.Zero)
{
return d;
}
if (video!.Duration > 0 && video.Timescale > 0)
{
return TimeSpan.FromTicks((long)((Int128)video.Duration * TimeSpan.TicksPerSecond / video.Timescale));
}
return order.Length == 0 ? TimeSpan.Zero : ShownAt(order[^1]) + FrameDuration();
}
private TimeSpan FrameDuration()
{
if (order.Length < 2 || video!.Timescale <= 0)
{
return TimeSpan.Zero;
}
var span = (Int128)(shown[order[^1]] - shown[order[0]]) * TimeSpan.TicksPerSecond;
return TimeSpan.FromTicks((long)(span / video.Timescale / (order.Length - 1)));
}
private static int Rotation(int rotation) => ((rotation % 360) + 360) % 360 is var r && r is 90 or 180 or 270 ? r : 0;
private static string Codec(VideoTrack video) =>
video.Codec is VideoCodec.H264 or VideoCodec.Hevc ? video.Codec.ToString() : video.CodecTag;
}
/// <summary>The frames part of the decoder: what <see cref="VideoFrameReader"/> needs of its private machinery.</summary>
public sealed partial class VideoFrameDecoder
{
/// <summary>The track frames can be taken from: H.264 or HEVC with its samples and configuration; else null.</summary>
internal static VideoTrack? FrameTrack(MediaContainer container) =>
container.Video is { Samples.Count: > 0, Encoded: false } video && video.Codec switch
{
VideoCodec.H264 => video.AnnexB || video.AvcConfiguration is not null,
VideoCodec.Hevc => video.AnnexB || video.HevcConfiguration is not null,
_ => false,
}
? video
: null;
/// <summary>Whether an exception while reading a video means a file that cannot be read (not a bug).</summary>
internal static bool IsUnreadableFile(Exception ex) => IsUnreadable(ex);
/// <summary>
/// Decodes the samples (ascending indices) exactly, each from an IDR picture or a recovery point shown no later than
/// it (else from the first sample), and gives each frame in RGBA, rotated upright, in decoding order.
/// </summary>
internal static IEnumerable<(int Sample, RgbaImage Image)> DecodeExact(Stream stream, VideoTrack video, int[] samples,
CancellationToken ct)
{
var decoding = new Decoding(stream, video, int.MaxValue, exact: true);
foreach (var (sample, frame) in decoding.Decode(samples, ct))
{
yield return (sample, ToRgba(frame, video.Rotation));
}
}
/// <summary>A frame at full size in RGBA (alpha 255), brought to 8 bits, then turned as the video is shown.</summary>
private static RgbaImage ToRgba(Frame frame, int rotation)
{
RgbaImage image;
if (frame.Hevc is { } h)
{
image = ToRgba(Planes(h), h.MatrixCoefficients, h.FullRange);
}
else
{
var a = frame.Avc!;
image = a.BytesPerSample == 2
? ToRgba(WidePlanes(a), a.MatrixCoefficients, a.FullRange)
: ToRgba(Planes(a), a.MatrixCoefficients, a.FullRange);
}
var orientation = (((rotation % 360) + 360) % 360) switch
{
90 => 6,
180 => 3,
270 => 8,
_ => 1,
};
var upright = ImageOrientation.Apply(image, orientation);
if (!ReferenceEquals(upright, image))
{
image.Dispose();
}
return upright;
}
private static RgbaImage ToRgba<T>(in YuvPlanes<T> planes, int matrix, bool fullRange)
where T : unmanaged, System.Numerics.IBinaryInteger<T>
{
var image = new RgbaImage(planes.Width, planes.Height);
var k = YuvToRgb.For(matrix, fullRange, planes.BitDepthY, planes.BitDepthC, planes.Height);
YuvToRgb.Convert(planes, k, 1, image.Pixels, planes.Width * RgbaImage.BytesPerPixel, RgbaImage.BytesPerPixel,
planes.Width, planes.Height);
return image;
}
}
+25 -6
View File
@@ -89,8 +89,15 @@ public static class WindowsFileNames
/// keeping its extension; then the longest folder segments. A shortened part ends with <c>~</c> and eight hex digits /// keeping its extension; then the longest folder segments. A shortened part ends with <c>~</c> and eight hex digits
/// of the SHA-256 of the original, so different names stay different (for example <c>_1</c> and <c>_2</c>). /// of the SHA-256 of the original, so different names stay different (for example <c>_1</c> and <c>_2</c>).
/// </summary> /// </summary>
/// <param name="baseFolder">The folder the path is below.</param>
/// <param name="segments">The segments.</param>
/// <param name="maxLength">The longest full path.</param>
/// <param name="keepSuffix">
/// When the stem of the file name ends with it (a frame suffix, «_t0m12s340»), the part before it is shortened and the
/// hash goes before it: «nome~1a2b3c4d_t0m12s340.png». Null: the whole stem may be cut, as before tappa E3.
/// </param>
/// <exception cref="PathTooLongException">Even shortened, the path does not fit (the base folder is too long).</exception> /// <exception cref="PathTooLongException">Even shortened, the path does not fit (the base folder is too long).</exception>
public static IReadOnlyList<string> FitPath(string baseFolder, IReadOnlyList<string> segments, int maxLength = MaxPathLength) public static IReadOnlyList<string> FitPath(string baseFolder, IReadOnlyList<string> segments, int maxLength = MaxPathLength, string? keepSuffix = null)
{ {
ArgumentNullException.ThrowIfNull(baseFolder); ArgumentNullException.ThrowIfNull(baseFolder);
ArgumentNullException.ThrowIfNull(segments); ArgumentNullException.ThrowIfNull(segments);
@@ -111,11 +118,11 @@ public static class WindowsFileNames
// 1. The file name, keeping its extension. // 1. The file name, keeping its extension.
var last = parts.Length - 1; var last = parts.Length - 1;
var (stem, extension) = SplitExtension(parts[last]); var (stem, extension) = SplitKept(parts[last], keepSuffix);
var stemTarget = Math.Max(stem.Length - excess, Math.Min(stem.Length, MinimumStem + HashSuffixLength)); var stemTarget = Math.Max(stem.Length - excess, Math.Min(stem.Length, MinimumStem + HashSuffixLength));
if (stemTarget < stem.Length) if (stemTarget < stem.Length)
{ {
parts[last] = Shorten(parts[last], stemTarget + extension.Length, keepExtension: true); parts[last] = Shorten(parts[last], stemTarget + extension.Length, keepExtension: true, keepSuffix);
excess = Total() - maxLength; excess = Total() - maxLength;
} }
@@ -156,10 +163,22 @@ public static class WindowsFileNames
: (fileName[..dot], fileName[dot..]); : (fileName[..dot], fileName[dot..]);
} }
/// <summary>Shortens a name to at most <paramref name="maxLength"/> characters with a hash suffix of the original.</summary> /// <summary>
private static string Shorten(string name, int maxLength, bool keepExtension) /// The stem and the end that is kept of a file name: the extension, preceded by <paramref name="keepSuffix"/> when
/// the stem ends with it.
/// </summary>
private static (string Stem, string Kept) SplitKept(string fileName, string? keepSuffix)
{ {
var (stem, extension) = keepExtension ? SplitExtension(name) : (name, string.Empty); var (stem, extension) = SplitExtension(fileName);
return keepSuffix is { Length: > 0 } && stem.Length > keepSuffix.Length && stem.EndsWith(keepSuffix, StringComparison.Ordinal)
? (stem[..^keepSuffix.Length], keepSuffix + extension)
: (stem, extension);
}
/// <summary>Shortens a name to at most <paramref name="maxLength"/> characters with a hash suffix of the original.</summary>
private static string Shorten(string name, int maxLength, bool keepExtension, string? keepSuffix = null)
{
var (stem, extension) = keepExtension ? SplitKept(name, keepSuffix) : (name, string.Empty);
var room = maxLength - extension.Length - HashSuffixLength; var room = maxLength - extension.Length - HashSuffixLength;
if (room < 1) if (room < 1)
{ {
@@ -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;
/// <summary>
/// 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).
/// </summary>
[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<ArgumentOutOfRangeException>(() => ExportFrames.Every(TimeSpan.FromSeconds(2), TimeSpan.FromMilliseconds(50)));
var over = Assert.ThrowsExactly<ArgumentException>(() => 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<ArgumentOutOfRangeException>(() => 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<ContentChangedException>(() => 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 + ":");
}
}
@@ -0,0 +1,90 @@
using System.Security.Cryptography;
using Febe.Core.Codecs.Images;
using static Febe.Tests.Imaging.TestImages;
namespace Febe.Tests.Imaging;
/// <summary>
/// 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).
/// </summary>
[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.");
}
}
@@ -14,6 +14,36 @@ public sealed class SafeFileWriterTests
return bytes; 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<string?>("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] [TestMethod]
public async Task WritesTheFileWithItsHashAndPublicationTime() public async Task WritesTheFileWithItsHashAndPublicationTime()
{ {
@@ -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;
/// <summary>
/// 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).
/// </summary>
[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));
}
/// <summary>The frame shown at position <paramref name="rank"/>, decoded straight from the stream.</summary>
private static H264Frame ShownFrame(ElementaryStream es, int rank)
{
var decoder = new H264Decoder();
var frames = new List<H264Frame>();
decoder.FrameDecoded += frames.Add;
decoder.DecodeAnnexB(ElementaryStream.AnnexB(es.Name));
var index = Array.IndexOf(es.Rank, rank);
return frames.Single(f => f.DecodeIndex == index);
}
}