using Febe.Core.Codecs.H264; using Febe.Core.Library; namespace Febe.Tests.Codecs.H264; /// /// The small H.264 video the demo shows (tappa E3): PCM macroblocks only, so its frames decode to the samples written, /// through the same reader «Fotogramma» uses. /// [TestClass] public sealed class H264PcmWriterTests { [TestMethod] public void TheDemoVideoIsTheSameEveryTime() => CollectionAssert.AreEqual(H264PcmWriter.DemoVideo(), H264PcmWriter.DemoVideo()); [TestMethod] public void TheDemoVideoGivesItsFramesAtTheirInstants() { using var stream = new MemoryStream(H264PcmWriter.DemoVideo()); using var reader = VideoFrameReader.Open(stream, out var info); Assert.IsTrue(info.Available, info.Unavailable); Assert.AreEqual((H264PcmWriter.DemoWidth, H264PcmWriter.DemoHeight), (info.Width, info.Height)); Assert.AreEqual(H264PcmWriter.DemoPictures, info.SampleCount); Assert.AreEqual(TimeSpan.FromSeconds(2), info.Duration); Assert.IsFalse(info.HasAudio); // 8 pictures per second: 1.234 s shows picture 9 (shown from 1.125 s). var targets = reader.Locate([TimeSpan.FromMilliseconds(1234), TimeSpan.Zero]); Assert.AreEqual(TimeSpan.FromMilliseconds(1125), targets[0].Actual); Assert.AreEqual(9, targets[0].Sample); var frames = reader.Decode(targets, CancellationToken.None).ToList(); try { Assert.HasCount(2, frames); foreach (var frame in frames) { var expected = H264PcmWriter.DemoPicture(frame.Index == 0 ? 9 : 0); var pixels = frame.Image.ToArray(); var width = H264PcmWriter.DemoWidth; foreach (var (x, y) in new[] { (0, 0), (17, 33), (width - 1, H264PcmWriter.DemoHeight - 1), (120, 200) }) { var (r, g, b) = Bt601(expected.Y[(y * width) + x], expected.Cb[((y / 2) * (width / 2)) + (x / 2)], expected.Cr[((y / 2) * (width / 2)) + (x / 2)]); var at = ((y * width) + x) * 4; Assert.IsLessThanOrEqualTo(3, Math.Abs(pixels[at] - r), $"R at {x},{y}"); Assert.IsLessThanOrEqualTo(3, Math.Abs(pixels[at + 1] - g), $"G at {x},{y}"); Assert.IsLessThanOrEqualTo(3, Math.Abs(pixels[at + 2] - b), $"B at {x},{y}"); Assert.AreEqual((byte)255, pixels[at + 3]); } } } finally { frames.ForEach(f => f.Dispose()); } } [TestMethod] public void TheSamplesNeverContainAStartCode() { var nal = H264PcmWriter.Idr(H264PcmWriter.DemoPicture(3), 1); for (var i = 0; i + 2 < nal.Length; i++) { Assert.IsFalse(nal[i] == 0 && nal[i + 1] == 0 && nal[i + 2] <= 3 && nal[i + 2] != 3, $"Start code at {i}"); } } private static (int R, int G, int B) Bt601(byte y, byte cb, byte cr) { var c = 1.164 * (y - 16); var d = cb - 128; var e = cr - 128; static int Clamp(double v) => (int)Math.Clamp(Math.Round(v), 0, 255); return (Clamp(c + (1.596 * e)), Clamp(c - (0.392 * d) - (0.813 * e)), Clamp(c + (2.017 * d))); } }