Files
Febe/tests/Febe.Tests/Media/Containers/Mp4RemuxerTests.cs
T
Alby96andClaude Opus 5.5 958cb71cd6 E3: correzioni della revisione di formati e fotogrammi
Le 16 osservazioni confermate della revisione, ognuna con la sua prova:

- JPEG: il controllo stima la memoria di lavoro del decodificatore
  (progressivo), così un file che non si decodifica esce «troppo
  grande» e non «illeggibile».
- Un EXIF che non si tiene lascia un EXIF minimo con l'orientamento,
  perché la foto convertita non esca girata.
- Fotogrammi: istanti in millisecondi interi; la copia trova l'indice
  del nome dall'istante, non dall'ordine delle righe.
- Video di durata sconosciuta misurati prima di registrare: contano
  nei limiti di 500 per richiesta e 5000 per video.
- Rimuxaggio: la durata del segmento di elst passa nell'MP4, la fine
  tagliata resta nascosta (anche nei fotogrammi).
- H.264: il punto di recupero vale come IDR solo con exact_match_flag.
- MP3 in MP4: objectTypeIndication 0x69 fino a 24 kHz, 0x6B oltre.
- Conversione della libreria: il lavoro toglie le righe di un formato
  spento o cambiato; spegnere toglie anche i «Non riuscito»; «Riprova»
  solo i formati di adesso; pausa per spazio prima di rileggere
  l'originale.
- «Anche i N» conta e mette in coda solo il tipo che si cambia; le
  impostazioni dell'esportazione si salvano una per volta.
- Eliminazione e «Tieni il più grande» scelgono i convertiti nella
  stessa transazione: nessun convertito orfano.
- Un file arrivato tardi in un elemento vecchio mette in coda solo sé
  (file nuovo = salvato da quando il formato è scelto).
- Zip dei fotogrammi a pezzi di 64 KB: un browser lento che legge non
  si interrompe, uno fermo sì.

Decisioni in docs/decisioni.md (28/11), §4.10 della specifica precisato.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 13:30:33 +01:00

248 lines
13 KiB
C#

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 ATrimmedEndStaysHiddenInTheMp4()
{
// A passthrough trim: the edits show 0,3 s of video and of audio, the rest of the media is hidden.
var es = ElementaryStream.Load("BA1_Sony_D");
const int ShownFrames = 9; // 0,3 s: a whole number of milliseconds, as the movie timescale keeps the edit
Assert.IsGreaterThan(ShownFrames + 3, es.Count);
var shownVideo = (long)ShownFrames * TestVideos.FrameTicks;
var mov = TestVideos.Mov(es, new MovOptions(Audio: true, AudioPriming: 1024, VideoTrim: shownVideo, AudioTrim: 13230));
using var source = new MemoryStream(mov);
var before = Read(source);
Assert.AreEqual(shownVideo, before.Video!.EditSegmentDuration);
Assert.AreEqual(13230L, before.Audio!.EditSegmentDuration);
Assert.AreEqual(TimeSpan.FromSeconds((double)shownVideo / TestVideos.Timescale), before.Duration);
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(shownVideo, after.Video!.EditSegmentDuration, "the edits are carried over");
Assert.AreEqual(13230L, after.Audio!.EditSegmentDuration);
Assert.AreEqual((before.Audio.EditMediaTime, before.Video.EditMediaTime ?? 0), (after.Audio.EditMediaTime, after.Video.EditMediaTime ?? 0));
Assert.AreEqual(before.Duration, after.Duration, "the MP4 lasts what the source shows");
AssertSameSamples(before.Video, source, after.Video, output, "video");
AssertSameSamples(before.Audio, source, after.Audio, output, "audio");
// A frame «oltre la fine» is the last one shown, never one the edit hides.
using var reader = Febe.Core.Library.VideoFrameReader.Open(output, out var info);
Assert.IsTrue(info.Available);
var last = reader.Locate([TimeSpan.FromHours(1)]).Single();
Assert.IsLessThan(TimeSpan.FromSeconds((double)shownVideo / TestVideos.Timescale), last.Actual);
Assert.AreEqual(ShownFrames - 1, last.Sample);
}
[TestMethod]
[DataRow(44100, 0x6B)]
[DataRow(32000, 0x6B)]
[DataRow(24000, 0x69)]
[DataRow(22050, 0x69)]
[DataRow(16000, 0x69)]
public void Mp3IsLabelledMpeg1OrMpeg2AudioByItsRate(int rate, int objectType)
{
// ISO/IEC 14496-1 Table 5: 0x6B is ISO/IEC 11172-3 (MPEG-1, 32-48 kHz), 0x69 ISO/IEC 13818-3 (the lower rates).
var mov = TestVideos.Mov(ElementaryStream.Load("BA1_Sony_D"), new MovOptions(Audio: true, Mp3: true, AudioRate: rate));
using var source = new MemoryStream(mov);
Assert.AreEqual(RemuxRefusal.None, Mp4Remuxer.Check(source, "clip.mov", out var plan, CancellationToken.None));
var mp4 = Remux(plan!, source);
Assert.AreEqual(objectType, ObjectTypeIndication(mp4));
using var output = new MemoryStream(mp4);
Assert.AreEqual((AudioCodec.Mp3, rate), (Read(output).Audio!.Codec, Read(output).Audio!.SampleRate));
}
/// <summary>The objectTypeIndication of the DecoderConfigDescriptor (tag 4) in the <c>esds</c> of a file.</summary>
private static int ObjectTypeIndication(byte[] file)
{
var esds = file.AsSpan().IndexOf("esds"u8);
Assert.IsGreaterThan(0, esds);
var config = file.AsSpan(esds).IndexOf((ReadOnlySpan<byte>)[0x04, 0x80, 0x80, 0x80]);
Assert.IsGreaterThan(0, config);
return file[esds + config + 5];
}
[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}");
}
}
}