E3: prove di codec, rimuxaggio, fotogrammi, copie e conversione

Le prove del nucleo della tappa E3 (WP6a), con i media costruiti dalle
prove: il controllo delle foto (stesso formato, HEIC/AVIF/raw, animate,
CMYK e oltre 8 bit, budget di pixel), metadati nei blocchi giusti e
perdite annotate, pixel identici in WEBP senza perdita; il rimuxaggio
da MOV (nuovo TestVideos.Mov) e Matroska a MP4 con campioni, date,
rotazione, lingua ed edit; i fotogrammi H.264 e H.265 all'istante, ogni
k secondi e N in tutto; i suffissi protetti dal taglio a 240; le copie
convertite, com'è con nota, adozione, «già copiato» in ogni forma,
«Copia di nuovo» esatta, spazio sul convertito, fotogrammi nella
cartella delle copie (FrameOnly, una copia per campione, lotti su più
pagine, tetto); la conversione della libreria (perdite, rimuxaggio,
doppioni, importazione delle copie convertite).

Servono a fissare il comportamento di E3 prima dell'unione. Nessun
codice del prodotto cambia; un limite trovato (istanti a meno di 1 ms
in «N in tutto») è annotato per Alberto.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-28 11:00:40 +01:00
1 parent d06b587806
commit f5e12c5d74
9 files changed
+1408 -4

No files matched your search

@@ -0,0 +1,184 @@
using System.Security.Cryptography;
using Febe.Core.Codecs.Containers;
namespace Febe.Tests.Codecs.Containers;
/// <summary>
/// «MOV → MP4 solo rimuxaggio» (tappa E3, WP1.4): the samples are copied as they are, with their times, sync samples,
/// edit, rotation, languages and dates; what the MP4 cannot take is refused with its reason, and the same source always
/// gives the same bytes of the length planned. The videos are built by the tests from conformance streams.
/// </summary>
[TestClass]
public sealed class Mp4RemuxerTests
{
private static readonly DateTimeOffset Created = new(2025, 7, 14, 18, 30, 5, TimeSpan.Zero);
private static readonly DateTimeOffset Modified = new(2025, 7, 15, 9, 0, 0, TimeSpan.Zero);
[TestMethod]
public void MovBecomesMp4WithTheSameSamplesDatesRotationAndLanguage()
{
var es = ElementaryStream.Load("CABA3_SVA_B"); // B frames: composition offsets and an edit
var mov = TestVideos.Mov(es, new MovOptions(Audio: true, Language: "ita", Rotation: 90, Created: Created, Modified: Modified));
using var source = new MemoryStream(mov);
var before = Read(source);
Assert.AreEqual("qt ", before.MajorBrand);
Assert.AreEqual(RemuxRefusal.None, Mp4Remuxer.Check(source, "clip.mov", out var plan, CancellationToken.None));
Assert.IsEmpty(plan!.Losses);
var mp4 = Remux(plan, source);
Assert.AreEqual(plan.OutputLength, mp4.Length, "the length is known before writing");
using var output = new MemoryStream(mp4);
var after = Read(output);
Assert.AreNotEqual("qt ", after.MajorBrand);
Assert.AreEqual((Created, Modified), (after.CreatedAt, after.ModifiedAt));
Assert.AreEqual(2, after.TrackCount);
Assert.AreEqual((90, "ita", "ita"), (after.Video!.Rotation, after.Video.Language, after.Audio!.Language));
CollectionAssert.AreEqual(before.Video!.AvcConfiguration, after.Video.AvcConfiguration);
CollectionAssert.AreEqual(before.Audio!.AacConfiguration, after.Audio.AacConfiguration);
AssertSameSamples(before.Video, source, after.Video, output, "video");
AssertSameSamples(before.Audio, source, after.Audio, output, "audio");
// The MP4 named .mp4 is what was asked: copied, not remuxed again.
Assert.AreEqual(RemuxRefusal.AlreadyMp4, Mp4Remuxer.Check(output, "clip.mp4", out _, CancellationToken.None));
}
[TestMethod]
public void TheStartAndSyncAreKeptByTheEditList()
{
var es = ElementaryStream.Load("BA1_Sony_D");
var mov = TestVideos.Mov(es, new MovOptions(Audio: true, AudioPriming: 1024, VideoEmptyEdit: TestVideos.Timescale / 2));
using var source = new MemoryStream(mov);
var before = Read(source);
Assert.AreEqual((1024L, 1), (before.Audio!.EditMediaTime, before.Audio.EditCount), "the priming is hidden by the edit");
Assert.AreEqual((long)TestVideos.Timescale / 2, before.Video!.EmptyEditDuration, "the video starts half a second later");
Assert.AreEqual(RemuxRefusal.None, Mp4Remuxer.Check(source, "clip.mov", out var plan, CancellationToken.None));
using var output = new MemoryStream(Remux(plan!, source));
var after = Read(output);
Assert.AreEqual((before.Audio.EditMediaTime, before.Video.EmptyEditDuration), (after.Audio!.EditMediaTime, after.Video!.EmptyEditDuration));
Assert.AreEqual(before.Video.EditMediaTime ?? 0, after.Video.EditMediaTime ?? 0);
AssertSameSamples(before.Video, source, after.Video, output, "video");
AssertSameSamples(before.Audio, source, after.Audio, output, "audio");
}
[TestMethod]
public void ExtraTracksAreDroppedAndCountedAndMp3IsKept()
{
var es = ElementaryStream.Load("BA1_Sony_D");
using var two = new MemoryStream(TestVideos.Mov(es, new MovOptions(Audio: true, ExtraAudioTracks: 1)));
Assert.AreEqual(RemuxRefusal.None, Mp4Remuxer.Check(two, "clip.mov", out var plan, CancellationToken.None));
CollectionAssert.AreEqual(new[] { Mp4Remuxer.LostTracks + ":1" }, plan!.Losses.ToArray());
using (var output = new MemoryStream(Remux(plan, two)))
{
Assert.AreEqual(2, Read(output).TrackCount);
}
using var mp3 = new MemoryStream(TestVideos.Mov(es, new MovOptions(Audio: true, Mp3: true)));
Assert.AreEqual(AudioCodec.Mp3, Read(mp3).Audio!.Codec);
Assert.AreEqual(RemuxRefusal.None, Mp4Remuxer.Check(mp3, "clip.mov", out var mp3Plan, CancellationToken.None));
using var mp3Output = new MemoryStream(Remux(mp3Plan!, mp3));
Assert.AreEqual(AudioCodec.Mp3, Read(mp3Output).Audio!.Codec);
}
[TestMethod]
public void HevcAndMatroskaAreRemuxedWithTheirSamples()
{
var hevc = ElementaryStream.LoadHevc("INITQP_A_Sony_1");
using var mov = new MemoryStream(TestVideos.Mov(hevc));
Assert.AreEqual(RemuxRefusal.None, Mp4Remuxer.Check(mov, "clip.mov", out var plan, CancellationToken.None));
using (var output = new MemoryStream(Remux(plan!, mov)))
{
var after = Read(output);
Assert.AreEqual(VideoCodec.Hevc, after.Video!.Codec);
CollectionAssert.AreEqual(hevc.AvcC, after.Video.HevcConfiguration);
AssertSameSamples(Read(mov).Video!, mov, after.Video, output, "HEVC");
}
// Matroska block times are presentation times in milliseconds: the MP4 shows each sample at the same millisecond.
var es = ElementaryStream.Load("CABA3_SVA_B");
using var mkv = new MemoryStream(TestVideos.Matroska(es));
var before = Read(mkv).Video!;
Assert.AreEqual(RemuxRefusal.None, Mp4Remuxer.Check(mkv, "clip.mkv", out var mkvPlan, CancellationToken.None));
using var remuxed = new MemoryStream(Remux(mkvPlan!, mkv));
var after2 = Read(remuxed).Video!;
Assert.HasCount(before.Samples.Count, after2.Samples);
var buffer = new byte[1];
var other = new byte[1];
for (var i = 0; i < before.Samples.Count; i++)
{
CollectionAssert.AreEqual(ContainerReader.ReadSample(mkv, before.Samples[i], ref buffer).ToArray(), ContainerReader.ReadSample(remuxed, after2.Samples[i], ref other).ToArray(), $"campione {i}");
Assert.AreEqual(before.Samples[i].Key, after2.Samples[i].Key, $"sincronia {i}");
Assert.AreEqual(
Math.Round(before.Seconds(before.Samples[i].PresentationTime) * 1000),
Math.Round(after2.Seconds(after2.Samples[i].PresentationTime + after2.EmptyEditDuration) * 1000),
$"istante {i}");
}
}
[TestMethod]
public void WhatNeedsReEncodingIsRefusedWithItsReason()
{
var es = ElementaryStream.Load("BA1_Sony_D");
RemuxRefusal Check(byte[] data, string name)
{
using var stream = new MemoryStream(data);
var refusal = Mp4Remuxer.Check(stream, name, out var plan, CancellationToken.None);
Assert.AreEqual(refusal == RemuxRefusal.None, plan is not null);
return refusal;
}
Assert.AreEqual(RemuxRefusal.VideoCodec, Check(TestVideos.Matroska(es, codecId: "V_VP9"), "clip.webm"));
Assert.AreEqual(RemuxRefusal.ContainerNotRemuxable, Check(TestVideos.Avi(es), "clip.avi"));
Assert.AreEqual(RemuxRefusal.AlreadyMp4, Check(TestVideos.Mp4(es), "clip.mp4"));
Assert.AreEqual(RemuxRefusal.None, Check(TestVideos.Mp4(es), "clip.m4v"), "an MP4 with another name is remuxed into a true .mp4");
Assert.AreNotEqual(RemuxRefusal.None, Check(new byte[4096], "clip.mov"));
// A truncated MOV: its samples are past the end of the file.
var mov = TestVideos.Mov(es);
Assert.AreEqual(RemuxRefusal.Unreadable, Check(mov[..(mov.Length - 100)], "clip.mov"));
}
[TestMethod]
public void RemuxingTwiceGivesTheSameBytes()
{
var es = ElementaryStream.Load("CABA3_SVA_B");
var mov = TestVideos.Mov(es, new MovOptions(Audio: true, Language: "eng", Created: Created));
string Once()
{
using var source = new MemoryStream(mov);
Assert.AreEqual(RemuxRefusal.None, Mp4Remuxer.Check(source, "clip.mov", out var plan, CancellationToken.None));
return Convert.ToHexStringLower(SHA256.HashData(Remux(plan!, source)));
}
Assert.AreEqual(Once(), Once());
}
private static MediaContainer Read(Stream stream)
{
stream.Position = 0;
return ContainerReader.Read(stream, ContainerReader.AnyDate, samples: true)!;
}
private static byte[] Remux(RemuxPlan plan, Stream source)
{
using var output = new MemoryStream();
Mp4Remuxer.Write(plan, source, output, CancellationToken.None);
return output.ToArray();
}
private static void AssertSameSamples(MediaTrack before, Stream source, MediaTrack after, Stream output, string what)
{
Assert.HasCount(before.Samples.Count, after.Samples, what);
Assert.AreEqual(before.Timescale, after.Timescale, what);
var a = new byte[1];
var b = new byte[1];
for (var i = 0; i < before.Samples.Count; i++)
{
var (x, y) = (before.Samples[i], after.Samples[i]);
Assert.AreEqual((x.Size, x.DecodeTime, x.PresentationTime, x.Key), (y.Size, y.DecodeTime, y.PresentationTime, y.Key), $"{what} {i}");
CollectionAssert.AreEqual(ContainerReader.ReadSample(source, x, ref a).ToArray(), ContainerReader.ReadSample(output, y, ref b).ToArray(), $"{what} {i}");
}
}
}
@@ -308,6 +308,66 @@ internal static class TestVideos
return output.ToArray();
}
/// <summary>
/// A QuickTime file (major brand <c>qt </c>, as phones write MOV) of the stream and, with <see cref="MovOptions.Audio"/>,
/// an AAC track (or MP3) of fixed frames; with the options of a camera: track languages, rotation, both dates, the
/// AAC priming hidden by an edit, a delayed start (an empty edit) and a second audio track that the MP4 drops.
/// </summary>
public static byte[] Mov(ElementaryStream es, MovOptions? options = null)
{
var o = options ?? new MovOptions();
var samples = new List<Mp4OutputSample>();
var data = new List<byte[]>();
for (var i = 0; i < es.Count; i++)
{
var bytes = es.LengthPrefixed(i);
data.Add(bytes);
samples.Add(new Mp4OutputSample(bytes.Length, (long)i * FrameTicks, (long)es.Rank[i] * FrameTicks, es.Key[i]));
}
var tracks = new List<Mp4OutputTrack>
{
new()
{
IsVideo = true,
Timescale = Timescale,
Samples = samples,
WriteSample = (i, s) => s.Write(data[i]),
Width = es.Width,
Height = es.Height,
Rotation = o.Rotation,
AvcConfiguration = es.Hevc ? null : es.AvcC,
HevcConfiguration = es.Hevc ? es.AvcC : null,
Language = o.Language,
EmptyEditDuration = o.VideoEmptyEdit,
},
};
for (var track = 0; track < (o.Audio ? 1 : 0) + o.ExtraAudioTracks; track++)
{
var frames = (int)Math.Ceiling(es.Count / 30.0 * 44100 / 1024) + (o.AudioPriming > 0 ? 1 : 0);
var payload = new byte[] { 0x21, 0x10, 0x04, 0x60, 0x8C, 0x1C, (byte)track };
tracks.Add(new Mp4OutputTrack
{
IsVideo = false,
Timescale = 44100,
Samples = [.. Enumerable.Range(0, frames).Select(i => new Mp4OutputSample(payload.Length, i * 1024L, i * 1024L, true))],
WriteSample = (_, s) => s.Write(payload),
AacConfiguration = o.Mp3 ? null : [0x12, 0x10], // AAC LC, 44.1 kHz, stereo
IsMp3 = o.Mp3,
SampleRate = 44100,
Channels = 2,
Language = o.Language,
EditMediaTime = o.AudioPriming > 0 ? o.AudioPriming : null,
});
}
using var output = new MemoryStream();
Mp4Writer.Prepare(tracks, new Mp4MovieInfo(o.Created, o.Modified)).WriteTo(output);
var file = output.ToArray();
"qt "u8.CopyTo(file.AsSpan(8)); // the major brand of ftyp
return file;
}
/// <summary>
/// A fragmented MP4 (empty sample tables in moov, then moof+mdat pairs of <paramref name="perFragment"/> frames).
/// With <paramref name="defaults"/> the sample durations come from <c>trex</c>, each fragment has two runs that
@@ -400,7 +460,7 @@ internal static class TestVideos
/// A Matroska file with one video track of SimpleBlocks, in a single cluster; block times are in ticks of
/// <paramref name="timecodeScale"/> nanoseconds (milliseconds by default).
/// </summary>
public static byte[] Matroska(ElementaryStream es, DateTimeOffset? created = null, bool webm = false, uint timecodeScale = 1_000_000)
public static byte[] Matroska(ElementaryStream es, DateTimeOffset? created = null, bool webm = false, uint timecodeScale = 1_000_000, string? codecId = null)
{
var shift = 0;
for (var i = 0; i < es.Count; i++)
@@ -422,7 +482,7 @@ internal static class TestVideos
var video = Element(0xE0, Element(0xB0, U16((ushort)es.Width)), Element(0xBA, U16((ushort)es.Height)));
var track = Element(0xAE, Element(0xD7, [1]), Element(0x73C5, [7]), Element(0x83, [1]),
Element(0x86, es.Hevc ? "V_MPEGH/ISO/HEVC"u8.ToArray() : "V_MPEG4/ISO/AVC"u8.ToArray()), Element(0x63A2, es.AvcC), video);
Element(0x86, codecId is not null ? Encoding.ASCII.GetBytes(codecId) : es.Hevc ? "V_MPEGH/ISO/HEVC"u8.ToArray() : "V_MPEG4/ISO/AVC"u8.ToArray()), Element(0x63A2, es.AvcC), video);
var blocks = new List<byte[]> { Element(0xE7, [0]) };
for (var i = 0; i < es.Count; i++)
{
@@ -558,3 +618,19 @@ internal static class TestVideos
return b;
}
}
/// <summary>What <see cref="TestVideos.Mov"/> puts in a QuickTime file.</summary>
/// <param name="Audio">One audio track (AAC unless <paramref name="Mp3"/>).</param>
/// <param name="ExtraAudioTracks">Further audio tracks (an MP4 of Febe keeps one).</param>
/// <param name="AudioPriming">Samples of AAC priming hidden by the audio edit (media time of the edit); 0: no edit.</param>
/// <param name="VideoEmptyEdit">Ticks (of 30000 a second) before the video starts: an empty edit.</param>
internal sealed record MovOptions(
bool Audio = false,
bool Mp3 = false,
int ExtraAudioTracks = 0,
string? Language = null,
int Rotation = 0,
DateTimeOffset? Created = null,
DateTimeOffset? Modified = null,
long AudioPriming = 0,
long VideoEmptyEdit = 0);
@@ -140,6 +140,103 @@ public sealed class VideoFramesTests
Assert.AreEqual(RemuxRefusal.AlreadyMp4, Mp4Remuxer.Check(mp4, "video.mp4", out _, CancellationToken.None));
}
[TestMethod]
public void HevcFramesWork()
{
var es = ElementaryStream.LoadHevc("INITQP_A_Sony_1");
using var stream = new MemoryStream(TestVideos.Mp4(es));
using var reader = VideoFrameReader.Open(stream, out var info);
Assert.IsTrue(info.Available);
var target = reader.Locate([TimeSpan.FromMilliseconds(1010)]).Single();
Assert.AreEqual(TimeSpan.FromSeconds(1), target.Actual);
using var frame = reader.Decode([target], CancellationToken.None).Single();
var shown = new List<Febe.Core.Codecs.H265.H265Frame>();
var decoder = new Febe.Core.Codecs.H265.H265Decoder();
decoder.FrameOutput += shown.Add;
decoder.DecodeAnnexB(File.ReadAllBytes(Codecs.H265.H265ConformanceStream.Load(es.Name).BitstreamPath));
var expected = VideoFrameDecoder.ToImage(shown[30], 0, 0);
var pixels = frame.Image.ToArray();
for (var i = 0; i < expected.Width * expected.Height; i++)
{
Assert.AreEqual((expected.Rgb[i * 3], expected.Rgb[(i * 3) + 1], expected.Rgb[(i * 3) + 2]), (pixels[i * 4], pixels[(i * 4) + 1], pixels[(i * 4) + 2]), $"pixel {i}");
}
}
[TestMethod]
public void TheInstantFollowsTheEditList()
{
// The video starts half a second into the presentation (an empty edit): the browser shows nothing of it before.
var es = ElementaryStream.Load("BA1_Sony_D");
using var stream = new MemoryStream(TestVideos.Mov(es, new MovOptions(VideoEmptyEdit: TestVideos.Timescale / 2)));
using var reader = VideoFrameReader.Open(stream, out var info);
Assert.IsTrue(info.Available);
var targets = reader.Locate([TimeSpan.FromMilliseconds(200), TimeSpan.FromMilliseconds(510), TimeSpan.FromMilliseconds(1010)]);
Assert.AreEqual((Array.IndexOf(es.Rank, 0), TimeSpan.FromMilliseconds(500)), (targets[0].Sample, targets[0].Actual), "before the start: the first frame");
Assert.AreEqual(TimeSpan.FromMilliseconds(500), targets[1].Actual);
Assert.AreEqual((Array.IndexOf(es.Rank, 15), TimeSpan.FromSeconds(1)), (targets[2].Sample, targets[2].Actual), "frame 15 is shown at 0.5 + 0.5 s");
}
[TestMethod]
public void EveryKSecondsAndNInAllFindTheFramesShown()
{
var es = ElementaryStream.Load("BA1_Sony_D");
using var stream = new MemoryStream(TestVideos.Mp4(es));
using var reader = VideoFrameReader.Open(stream, out var info);
var every = reader.Locate(ExportFrames.Every(info.Duration, TimeSpan.FromMilliseconds(250)));
Assert.AreEqual(TimeSpan.Zero, every[0].Actual);
foreach (var t in every)
{
Assert.IsLessThanOrEqualTo(t.Requested, t.Actual, "the frame shown at an instant started at or before it");
Assert.IsLessThan(TimeSpan.FromMilliseconds(34), t.Requested - t.Actual, "and less than a frame before");
}
var spread = reader.Locate(ExportFrames.Spread(info.Duration, 4));
Assert.HasCount(4, spread.Select(t => t.Sample).Distinct().ToList(), "four different frames");
var frames = reader.Decode(spread, CancellationToken.None).ToList();
try
{
CollectionAssert.AreEquivalent(new[] { 0, 1, 2, 3 }, frames.Select(f => f.Index).ToArray(), "one picture per target");
}
finally
{
frames.ForEach(f => f.Dispose());
}
}
[TestMethod]
public void AnUnsupportedCodecSaysNotAvailable()
{
var es = ElementaryStream.Load("BA1_Sony_D");
using var stream = new MemoryStream(TestVideos.Matroska(es, webm: true, codecId: "V_VP9"));
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 ADamagedStreamGivesNoPicture()
{
// The container is fine, the pictures are noise: no frame comes out, nothing throws.
var es = ElementaryStream.Load("BA1_Sony_D");
var mp4 = TestVideos.Mp4(es);
var mdat = mp4.AsSpan().IndexOf("mdat"u8) + 4;
new Random(5).NextBytes(mp4.AsSpan(mdat + 64));
using var stream = new MemoryStream(mp4);
using var reader = VideoFrameReader.Open(stream, out var info);
Assert.IsTrue(info.Available, "the tables are readable");
var frames = reader.Decode(reader.Locate([TimeSpan.FromMilliseconds(900)]), CancellationToken.None).ToList();
frames.ForEach(f => f.Dispose());
Assert.IsEmpty(frames);
}
/// <summary>The frame shown at position <paramref name="rank"/>, decoded straight from the stream.</summary>
private static H264Frame ShownFrame(ElementaryStream es, int rank)
{