Le quattro osservazioni confermate della seconda revisione, ognuna con la sua prova (ciascuna cade sul codice di prima): - Rimuxaggio con fotogrammi B: l'MP4 misura la fine della presentazione in tempo di composizione, non con la somma delle durate di decodifica. Prima nascondeva gli ultimi fotogrammi mostrati (2 in un iPhone) e durava altrettanto meno in elst, tkhd e mvhd. Per le tracce senza scarti di composizione i byte restano gli stessi. - Conversione della libreria: il lavoro ricorda il file che l'ha messo in pausa per spazio e quanto serve al suo convertito. Finché il disco non ha posto anche per quello, non rilegge l'originale a ogni risveglio (anche quando lo spazio libero sta appena sopra la soglia). - Impostazioni dell'esportazione: formati, chiavi «dal» e coda del formato sostituito si salvano in una transazione sola; «Anche i N» dopo il salvataggio non dipende più dalla richiesta. Il gancio della libreria legge formati e chiavi «dal» in una lettura. Una scheda chiusa o un arresto non lasciano più un formato senza la sua chiave né «Non riuscito» che «Riprova» non tocca. - Zip dei fotogrammi: i tempi del blocco passano da un TimeProvider della BCL, e la prova del lettore lento non dipende più dal carico della macchina. Decisioni in docs/decisioni.md (28/11). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
305 lines
16 KiB
C#
305 lines
16 KiB
C#
using System.Buffers.Binary;
|
|
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]
|
|
public void TheLastReorderedFramesStayShownInTheMp4()
|
|
{
|
|
// B frames, as iPhones and High profile encoders write them: the edit starts at the first composition offset
|
|
// and shows the whole presentation (N frames). The MP4 must show as much, never 2 frames less.
|
|
var es = ElementaryStream.Load("CABA3_SVA_B");
|
|
var n = es.Count;
|
|
Assert.IsTrue(Enumerable.Range(0, n).Any(i => es.Rank[i] < i), "the stream has reordered frames");
|
|
var presentation = (long)n * TestVideos.FrameTicks;
|
|
var mov = TestVideos.Mov(es, new MovOptions(VideoTrim: presentation));
|
|
using var source = new MemoryStream(mov);
|
|
var before = Read(source);
|
|
Assert.IsGreaterThan(0L, before.Video!.EditMediaTime ?? 0, "the edit starts at the first composition offset");
|
|
AssertAbout(presentation, before.Video.EditSegmentDuration, "the source shows all N frames");
|
|
|
|
Assert.AreEqual(RemuxRefusal.None, Mp4Remuxer.Check(source, "clip.mov", out var plan, CancellationToken.None));
|
|
var mp4 = Remux(plan!, source);
|
|
using var output = new MemoryStream(mp4);
|
|
var after = Read(output);
|
|
|
|
Assert.AreEqual(before.Video.EditMediaTime, after.Video!.EditMediaTime);
|
|
Assert.AreEqual(before.Video.EditSegmentDuration, after.Video.EditSegmentDuration, "the segment is the source's");
|
|
AssertAbout(presentation, after.Video.EditSegmentDuration, "the MP4 shows all N frames");
|
|
Assert.AreEqual(before.Duration, after.Duration);
|
|
var shownMs = (long)Math.Ceiling(n * 1000.0 / 30);
|
|
Assert.AreEqual((shownMs, shownMs), (HeaderDuration(mp4, "mvhd"u8), HeaderDuration(mp4, "tkhd"u8)), "mvhd and tkhd last N frames");
|
|
Assert.AreEqual((HeaderDuration(mov, "mvhd"u8), HeaderDuration(mov, "tkhd"u8)), (HeaderDuration(mp4, "mvhd"u8), HeaderDuration(mp4, "tkhd"u8)));
|
|
AssertSameSamples(before.Video, source, after.Video, output, "video");
|
|
|
|
// A frame «oltre la fine» is the one presented last, not one that decodes last.
|
|
var lastShown = Enumerable.Range(0, n).MaxBy(i => es.Rank[i]);
|
|
using var reader = Febe.Core.Library.VideoFrameReader.Open(output, out var info);
|
|
Assert.IsTrue(info.Available);
|
|
Assert.AreEqual(lastShown, reader.Locate([TimeSpan.FromHours(1)]).Single().Sample);
|
|
}
|
|
|
|
/// <summary>A segment read back from the movie timescale (milliseconds, rounded up) is within a millisecond.</summary>
|
|
private static void AssertAbout(long expected, long? actual, string what)
|
|
{
|
|
Assert.IsNotNull(actual, what);
|
|
Assert.IsLessThanOrEqualTo(TestVideos.Timescale / 1000, Math.Abs(actual.Value - expected), $"{what}: {actual} for {expected}");
|
|
}
|
|
|
|
/// <summary>The duration of the first <c>mvhd</c> or <c>tkhd</c> of a file (movie units), of either version.</summary>
|
|
private static long HeaderDuration(byte[] file, ReadOnlySpan<byte> type)
|
|
{
|
|
var at = file.AsSpan().IndexOf(type);
|
|
Assert.IsGreaterThan(0, at);
|
|
var body = file.AsSpan(at + 4);
|
|
var wide = body[0] == 1;
|
|
var isTrack = type[0] == (byte)'t';
|
|
// version and flags, the dates, then the timescale (mvhd) or the track id and a reserved word (tkhd).
|
|
var offset = 4 + (wide ? 16 : 8) + (isTrack ? 8 : 4);
|
|
return wide ? (long)BinaryPrimitives.ReadUInt64BigEndian(body[offset..]) : BinaryPrimitives.ReadUInt32BigEndian(body[offset..]);
|
|
}
|
|
|
|
[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}");
|
|
}
|
|
}
|
|
}
|