From 9277e0a18c113a6473ecf07c18a195db35c8f7c7 Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Tue, 1 Dec 2026 18:57:56 +0100 Subject: [PATCH] =?UTF-8?q?E4:=20l'analisi=20non=20dice=20pi=C3=B9=20?= =?UTF-8?q?=C2=ABFermo=C2=BB=20di=20ci=C3=B2=20che=20non=20ha=20visto?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Filmati ripetuti, video tagliati o rovinati, neve e scritte piccole risultavano fermi; una scheda bianca in dissolvenza in movimento; una scritta sul nero «tutto nero». Istanti a punti diversi, griglia fitta, bianco bruciato per canale, fotogrammi mancanti e un solo fotogramma chiaro trattati a parte, errori del disco rilanciati. Co-Authored-By: Claude Opus 5.5 --- src/Febe.Core/Export/ExportFrames.cs | 30 +- src/Febe.Core/Library/StillVideoAnalyzer.cs | 726 +++++++++++++----- src/Febe.Core/Library/VideoFrameDecoder.cs | 12 +- src/Febe.Core/Library/VideoFrames.cs | 23 +- .../Febe.Tests/Media/Containers/PcmVideos.cs | 47 ++ .../Containers/StillVideoAnalyzerTests.cs | 380 ++++++++- 6 files changed, 1008 insertions(+), 210 deletions(-) diff --git a/src/Febe.Core/Export/ExportFrames.cs b/src/Febe.Core/Export/ExportFrames.cs index 1bbe94b..3e68259 100644 --- a/src/Febe.Core/Export/ExportFrames.cs +++ b/src/Febe.Core/Export/ExportFrames.cs @@ -1,4 +1,5 @@ using System.Globalization; +using System.Text.RegularExpressions; namespace Febe.Core.Export; @@ -6,7 +7,7 @@ namespace Febe.Core.Export; /// 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. /// -public static class ExportFrames +public static partial class ExportFrames { /// The shortest step of «Uno ogni k secondi». public static readonly TimeSpan MinEvery = TimeSpan.FromMilliseconds(100); @@ -26,6 +27,16 @@ public static class ExportFrames /// The suffix of the single frame of «Salva il fotogramma» (tappa E4). public const string SingleSuffix = "_fotogramma"; + /// + /// Whether the file of a frame copy has the name «Salva il fotogramma» gives (, also with + /// « (2)» of a name already taken): the other ways end with _t… or _f…. + /// + public static bool IsSingleName(string? relativePath) => + relativePath is not null && SingleName().IsMatch(Path.GetFileNameWithoutExtension(relativePath)); + + [GeneratedRegex("_fotogramma( \\(\\d+\\))?$", RegexOptions.CultureInvariant)] + private static partial Regex SingleName(); + /// How many frames asks of a video of . public static long FrameCount(TimeSpan duration, ExportFramesRequest request) { @@ -160,9 +171,20 @@ public static class ExportFrames /// An instant rounded up to the whole millisecond (never before the instant computed). private static TimeSpan WholeMs(TimeSpan at) => TimeSpan.FromMilliseconds(ActualMs(at)); - /// The identity of a frame's instant: its shown time in milliseconds, rounded up. - public static long ActualMs(TimeSpan shown) => - shown <= TimeSpan.Zero ? 0 : (shown.Ticks + TimeSpan.TicksPerMillisecond - 1) / TimeSpan.TicksPerMillisecond; + /// + /// The identity of a frame's instant: its shown time in milliseconds, rounded up (a hostile time table reaches the + /// end of what a TimeSpan holds: the whole milliseconds of it, then). + /// + public static long ActualMs(TimeSpan shown) + { + if (shown <= TimeSpan.Zero) + { + return 0; + } + + var (ms, rest) = Math.DivRem(shown.Ticks, TimeSpan.TicksPerMillisecond); + return Math.Min(ms + (rest > 0 ? 1 : 0), TimeSpan.MaxValue.Ticks / TimeSpan.TicksPerMillisecond); + } private static long EveryCount(TimeSpan duration, TimeSpan step) { diff --git a/src/Febe.Core/Library/StillVideoAnalyzer.cs b/src/Febe.Core/Library/StillVideoAnalyzer.cs index 971a09a..6116963 100644 --- a/src/Febe.Core/Library/StillVideoAnalyzer.cs +++ b/src/Febe.Core/Library/StillVideoAnalyzer.cs @@ -1,4 +1,5 @@ using System.Buffers; +using System.Runtime.ExceptionServices; using Febe.Core.Codecs.Containers; using Febe.Core.Codecs.Images; using Febe.Core.Domain; @@ -53,26 +54,35 @@ public sealed record StillVideoResult( /// §4.10 «Video fermi», tappa E4, algorithm 1). Written in house on : exact frames at the /// shown times, edit lists included, upright. /// -/// frames, one near the centre of each of as many equal parts of the video (a key frame -/// within a quarter of a part, which decodes alone, else the frame shown at the centre): never the very first or last -/// frame, where fades and black frames sit. A video of one frame (or whose instants all fall on one) is that -/// picture. -/// Each frame is reduced to a grid of × blocks of mean luma and -/// chroma (BT.709); its sharpness is the variance of the Laplacian of its luma. -/// A frame with no block as bright as in any colour is dark: dark frames at the start or -/// the end (a fade from or to black) are set aside; a dark frame between two that are not means the picture -/// changes. +/// frames spread over what the video track shows (not over the length the headers say), one +/// in each of as many equal parts, at the uneven inside them: equal steps would fall on the same +/// picture of a clip repeated over and over. Every other one may move to a key frame shown within a quarter of a part, +/// which decodes alone; the ones between are the frame shown at the instant, so that the pictures between key frames are +/// looked at too. Never the very first or last frame, where fades and black frames sit. A track of at most +/// pictures is looked at whole; when the instants fall on fewer pictures (some are held for long) +/// others are added by their position. +/// Each frame is reduced to a grid of × blocks and to a finer one (of +/// up to cells a side, at least pixels each), with the mean of each +/// channel and the share of it clipped at white; its sharpness is the variance of the Laplacian of its luma. +/// A frame with no block as bright as in any colour, and no detail as bright as +/// , is dark: dark frames at the start or the end (a fade from or to black) are set aside; a +/// dark frame between two that are not means the picture changes. A single frame that is not dark says nothing of the +/// video: more are then looked at between the dark ones around it. /// A fade is undone before frames are compared: when the brightness ratios of the blocks agree (a fade scales -/// them all alike) the brighter one is scaled down to the darker, leaving out the blocks clipped at white. +/// them all alike) the picture is scaled to the frame's brightness; what clipping at white may hide is bounded, channel +/// by channel, and never taken for a change. /// The still picture is the median of the frames, block by block, so a part that moves does not belong to it. The /// video is still when every frame differs from it by a mean of at most (each block capped /// at ) and the blocks that differ by more than cover at most -/// of the picture: a small animated sticker or a moving caption leaves the video still -/// (answer 47 of Alberto, 29 November 2026). While decoding, a pair of frames that differs over three times that area -/// (a moving part changes the picture at its old and its new place, and the edges of the blocks add some) or by a -/// larger mean already says «In movimento», and the rest is not decoded. -/// No frame that is not dark: «Non analizzabile» (); every one of a -/// single colour: «Non analizzabile» (, answer 42). +/// of the picture, on both grids (the finer one by its luma): a small animated sticker or a +/// moving caption leaves the video still (answer 47 of Alberto, 29 November 2026), and snow or static, whose blocks +/// average out, does not. While decoding, a pair of frames that differs over three times that area (a moving part +/// changes the picture at its old and its new place, and the edges of the blocks add some) or by a larger mean already +/// says «In movimento», and the rest is not decoded. +/// No frame that is not dark: «Non analizzabile» (); every one of the same +/// single colour: «Non analizzabile» (, answer 42). A frame that should have +/// been looked at and gives no picture: «Non analizzabile» (), unless the +/// others already show motion. /// /// Any change to the rule or to the thresholds raises . /// @@ -87,6 +97,18 @@ public static class StillVideoAnalyzer /// Blocks of the grid on each side. public const int GridSize = 32; + /// Cells of the finer grid on each side, at most. + public const int FineGridSize = 128; + + /// The smallest side of a cell of the finer grid, in pixels. + internal const int FineCell = 4; + + /// + /// Where each frame looked at sits inside its part of the video (0–1): uneven, so that no number of repetitions of a + /// short clip puts them all on the same picture of it. + /// + internal static readonly double[] Offsets = [0.4173, 0.3611, 0.6237, 0.5, 0.6619, 0.3307, 0.5521]; + /// /// A frame none of whose blocks has a red, green or blue mean as bright as this (0–255) is dark: black or nearly /// black. @@ -112,31 +134,52 @@ public static class StillVideoAnalyzer /// While decoding, a pair of frames differing over this many times moves: a part of /// that area changes it at its old and its new place, and the edges of the blocks add some. /// - private const double EarlyAreaFactor = 3; + internal const double EarlyAreaFactor = 3; /// Blocks darker than this in both frames do not take part in the estimate of a fade. - private const double GainFloor = 16; + internal const double GainFloor = 16; /// The largest spread (interquartile range of the natural logarithms) of block ratios read as a fade. - private const double GainAgreement = 0.1; + internal const double GainAgreement = 0.1; /// The largest brightness ratio undone as a fade. - private const double GainRange = 8; + internal const double GainRange = 8; - /// A gain this close to 1 is no fade: no block is left out for clipping. - private const double GainTolerance = 0.02; + /// + /// Blocks with more of their pixels clipped at white than this do not take part in the estimate of a fade, unless + /// too few are left. + /// + internal const double ClippedShare = 0.1; - /// Blocks with more of their pixels clipped at white than this do not scale with a fade. - private const double ClippedShare = 0.1; + /// A channel at least this bright (0–255) is taken as clipped at white. + internal const int White = 250; /// The weight of each chroma difference against the luma one. - private const double ChromaWeight = 0.25; + internal const double ChromaWeight = 0.25; + + /// A pixel with a channel at least this bright (0–255) is a detail that a dark frame does not have. + internal const int BrightDetail = 96; + + /// The variance of the luma of the pixels from which a frame is not of a single colour. + internal const double UniformVariance = 64; + + /// A pixel whose luma is further than this from the mean is a detail that a frame of a single colour does not have. + internal const double UniformDetail = 32; + + /// The share of the pixels that may be such a detail in a dark frame or in one of a single colour. + internal const double DetailShare = 0.0002; + + /// The latest instant a video may show (past it the time table is damaged or hostile). + internal static readonly TimeSpan LatestInstant = TimeSpan.FromSeconds(1e9); /// /// Analyses the video in (left open) in at most : past it the /// result is «Non analizzabile» with (a zero budget gives it at once). It - /// never throws for a video it cannot read; a cancellation of stays a cancellation. + /// never throws for a video it cannot read, but an error of the stream itself (a disk or a share that went) is thrown: + /// it says nothing of the video. A cancellation of stays a cancellation. /// + /// The stream could not be read. + /// The stream could not be read. public static StillVideoResult Analyse(Stream seekable, TimeSpan budget, CancellationToken ct) { ArgumentNullException.ThrowIfNull(seekable); @@ -150,14 +193,20 @@ public static class StillVideoAnalyzer limit.CancelAfter(budget); } + // The readers take an IOException for a damaged file and go on: the watched stream remembers the real ones. + var watched = new WatchedStream(seekable); + StillVideoResult result; try { - return Run(seekable, limit.Token); + result = Run(watched, limit.Token); } catch (OperationCanceledException) when (!ct.IsCancellationRequested) { - return NotAnalyzable(VideoAnalysisNotes.TooSlow, 0, 0, false); + result = NotAnalyzable(VideoAnalysisNotes.TooSlow, 0, 0, false); } + + watched.Fault?.Throw(); + return result; } /// Analyses the video in with no limit but . @@ -165,7 +214,8 @@ public static class StillVideoAnalyzer /// /// Analyses the video file at on the thread pool, as : - /// a file that cannot be opened is «Non analizzabile» (). + /// a file that cannot be opened is «Non analizzabile» (); one that stops being + /// readable meanwhile throws. /// public static Task AnalyseAsync(string path, TimeSpan budget, CancellationToken ct = default) { @@ -194,66 +244,52 @@ public static class StillVideoAnalyzer private static StillVideoResult Run(Stream stream, CancellationToken ct) { ct.ThrowIfCancellationRequested(); - using var reader = VideoFrameReader.Open(stream, out var info); + using var reader = VideoFrameReader.Open(stream, out var info, ct); if (!info.Available) { - return NotAnalyzable(VideoAnalysisNotes.FrameNotAvailable, 0, info.Rotation, info.HasAudio); + return NotAnalyzable(VideoAnalysisNotes.FrameNotAvailable, 0, info); } - if (info.SampleCount > 1 && info.Duration <= TimeSpan.Zero) + var shown = reader.Shown(); + if (shown.Count == 0 || (info.SampleCount > 1 && info.Duration <= TimeSpan.Zero) || shown[^1].Actual > LatestInstant) { - return NotAnalyzable(VideoAnalysisNotes.DurationUnknown, 0, info.Rotation, info.HasAudio); + return NotAnalyzable(VideoAnalysisNotes.DurationUnknown, 0, info); } - var targets = (info.SampleCount > 1 - ? reader.LocateNearKey(ExportFrames.Spread(info.Duration, Samples), info.Duration / (4 * Samples)) - : reader.Locate([TimeSpan.Zero])) - .DistinctBy(t => t.Sample) - .ToList(); + var targets = Targets(reader, shown); var frames = new List(targets.Count); - try + if (Look(reader, targets, frames, ct) is { } pair) { - foreach (var frame in reader.Decode(targets, ct)) + return Moving(frames.Count, info, pair.Mean, pair.Area); + } + + var expected = targets.Count; + if (frames.Count == expected && expected > 1 && frames.Count(f => !f.Dark) == 1) + { + // One picture alone among dark frames: the others between the dark frames around it are looked at too. + var between = Around(shown, frames); + var seen = targets.Select(t => t.Sample).ToHashSet(); + var more = Targets(reader, between).Where(t => !seen.Contains(t.Sample)).ToList(); + expected += more.Count; + if (Look(reader, more, frames, ct) is { } second) { - Signature signature; - using (frame) - { - signature = Signature.Of(frame.Image, frame.Actual); - } - - ct.ThrowIfCancellationRequested(); - if (!signature.Dark) - { - foreach (var other in frames.Where(f => !f.Dark)) - { - var (mean, area) = Compare(signature, other); - if (mean > MeanThreshold || area > EarlyAreaFactor * AreaThreshold) - { - // One pair that moves is enough: the rest of the video is not decoded. - return Moving(frames.Count + 1, info, mean, area); - } - } - } - - frames.Add(signature); + return Moving(frames.Count, info, second.Mean, second.Area); } - } - catch (Exception ex) when (VideoFrameDecoder.IsUnreadableFile(ex)) - { - // A damaged stream past the frames read so far: they stand, as for a run the decoder skips. - } - if (frames.Count == 0 || (targets.Count >= 2 && frames.Count < 2)) - { - return NotAnalyzable(VideoAnalysisNotes.Unreadable, frames.Count, info.Rotation, info.HasAudio); + if (frames.Count == expected && frames.Count(f => !f.Dark) == 1 && Around(shown, frames).Count > 1) + { + return NotAnalyzable(VideoAnalysisNotes.AllDark, frames.Count, info); + } } // In the order they are shown: dark frames only at the start or the end (a fade), never between two pictures. + // Motion proved by the frames there are stands; with a frame missing nothing else can be said. frames.Sort((a, b) => a.Actual.CompareTo(b.Actual)); + var complete = frames.Count == expected; var first = frames.FindIndex(f => !f.Dark); if (first < 0) { - return NotAnalyzable(VideoAnalysisNotes.AllDark, frames.Count, info.Rotation, info.HasAudio); + return NotAnalyzable(complete ? VideoAnalysisNotes.AllDark : VideoAnalysisNotes.Unreadable, frames.Count, info); } var last = frames.FindLastIndex(f => !f.Dark); @@ -263,15 +299,26 @@ public static class StillVideoAnalyzer } var pictures = frames.Where(f => !f.Dark).ToList(); - var (difference, changed) = AgainstStillPicture(pictures); + if (pictures.All(f => f.Uniform)) + { + // Before the comparison of the blocks, which cannot undo a fade of a colour that clips or of a dark one. + if (!SameColour(pictures)) + { + return Moving(frames.Count, info, 0, 0); + } + + return NotAnalyzable(complete ? VideoAnalysisNotes.SingleColor : VideoAnalysisNotes.Unreadable, frames.Count, info); + } + + var (difference, changed, small) = AgainstStillPicture(pictures); if (difference > MeanThreshold || changed > AreaThreshold) { return Moving(frames.Count, info, difference, changed); } - if (pictures.All(f => f.Uniform)) + if (!complete) { - return NotAnalyzable(VideoAnalysisNotes.SingleColor, frames.Count, info.Rotation, info.HasAudio); + return NotAnalyzable(VideoAnalysisNotes.Unreadable, frames.Count, info); } // The sharpest picture (the first shown of equally sharp ones): never a dark frame, nor one dimmed by a fade. @@ -285,56 +332,182 @@ public static class StillVideoAnalyzer } return new StillVideoResult(VideoAnalysisOutcome.Still, TimeSpan.FromMilliseconds(ExportFrames.ActualMs(chosen.Actual)), - changed > 0 ? VideoAnalysisNotes.SmallMotion : null, frames.Count, info.Rotation, info.HasAudio, + small ? VideoAnalysisNotes.SmallMotion : null, frames.Count, info.Rotation, info.HasAudio, Math.Round(difference, 2), Math.Round(changed, 4), Math.Round(chosen.Sharpness, 2)); } + /// + /// The frames to look at among (pictures in shown order): all of them when they are at most + /// ; otherwise one in each of as many equal parts of the time they cover, at the uneven + /// , every other one moved to a near key frame; then others by position when fewer than + /// come out. + /// + private static List Targets(VideoFrameReader reader, IReadOnlyList shown) + { + if (shown.Count <= Samples) + { + return [.. shown]; + } + + var (from, last) = (shown[0].Actual, shown[^1].Actual); + var length = last - from + ((last - from) / (shown.Count - 1)); + var instants = Offsets.Select((o, i) => from + TimeSpan.FromTicks((long)(length.Ticks * ((i + o) / Samples)))).ToList(); + var exact = reader.Locate(instants); + var near = reader.LocateNearKey(instants, length / (4 * Samples)); + var targets = new List(Samples); + var taken = new HashSet(); + for (var i = 0; i < Samples; i++) + { + var target = i % 2 == 0 && near[i].Actual >= from && near[i].Actual <= last ? near[i] : exact[i]; + if (taken.Add(target.Sample)) + { + targets.Add(target); + } + } + + // Pictures held for long take several instants: the others are looked at by their position. + for (var i = 0; i < Samples && targets.Count < Samples; i++) + { + var target = shown[(int)(shown.Count * ((i + Offsets[i]) / Samples))]; + if (taken.Add(target.Sample)) + { + targets.Add(target); + } + } + + return targets; + } + + /// The pictures shown between the dark frames nearest to the only one that is not dark. + private static List Around(IReadOnlyList shown, List frames) + { + var lit = frames.Single(f => !f.Dark).Actual; + var before = frames.Where(f => f.Dark && f.Actual < lit).Select(f => f.Actual).DefaultIfEmpty(TimeSpan.MinValue).Max(); + var after = frames.Where(f => f.Dark && f.Actual > lit).Select(f => f.Actual).DefaultIfEmpty(TimeSpan.MaxValue).Min(); + return [.. shown.Where(t => t.Actual > before && t.Actual < after)]; + } + + /// + /// Decodes the targets and adds them to : the difference of the first pair that moves, or + /// null when none does (or the stream is damaged: fewer frames than targets come out). + /// + private static (double Mean, double Area)? Look(VideoFrameReader reader, List targets, List frames, CancellationToken ct) + { + try + { + foreach (var frame in reader.Decode(targets, ct)) + { + Signature signature; + using (frame) + { + signature = Signature.Of(frame.Image, frame.Actual); + } + + ct.ThrowIfCancellationRequested(); + frames.Add(signature); + if (signature.Dark) + { + continue; + } + + foreach (var other in frames.Where(f => !f.Dark && f != signature && !(f.Uniform && signature.Uniform))) + { + var (mean, area) = Compare(signature, other); + if (mean > MeanThreshold || area > EarlyAreaFactor * AreaThreshold) + { + // One pair that moves is enough: the rest of the video is not decoded. + return (mean, area); + } + } + } + } + catch (Exception ex) when (VideoFrameDecoder.IsUnreadableFile(ex)) + { + // A damaged stream past the frames read so far: the caller sees that some are missing. + } + + return null; + } + + private static StillVideoResult NotAnalyzable(string note, int sampled, VideoFrameInfo info) => + NotAnalyzable(note, sampled, info.Rotation, info.HasAudio); + private static StillVideoResult NotAnalyzable(string note, int sampled, int rotation, bool hasAudio) => new(VideoAnalysisOutcome.NotAnalyzable, null, note, sampled, rotation, hasAudio, 0, 0, 0); private static StillVideoResult Moving(int sampled, VideoFrameInfo info, double difference, double area) => new(VideoAnalysisOutcome.Moving, null, null, sampled, info.Rotation, info.HasAudio, Math.Round(difference, 2), Math.Round(area, 4), 0); - /// The difference of two frames, after a fade between them is undone. + /// Whether the pictures, each of a single colour, all show the same colour, fades undone on its largest channel. + private static bool SameColour(List pictures) + { + var brightest = pictures.MaxBy(p => p.Colour.Largest)!.Colour; + return pictures.All(p => + { + var gain = p.Colour.Largest / Math.Max(1, brightest.Largest); + return Difference(p.Colour.R - (gain * brightest.R), p.Colour.G - (gain * brightest.G), p.Colour.B - (gain * brightest.B), ChromaWeight) + <= BlockThreshold; + }); + } + + /// The difference of two frames on the blocks, after a fade between them is undone: the darker one against the brighter. private static (double Mean, double Area) Compare(Signature a, Signature b) { var gain = Gain(a, b); - return Measure(a, b.Luma, b.BlueDifference, b.RedDifference, gain, b.Clipped, IsFade(gain)); + return gain <= 1 + ? Measure(a.Coarse, b.Coarse, gain, gain, ChromaWeight) + : Measure(b.Coarse, a.Coarse, 1 / gain, 1 / gain, ChromaWeight); } /// - /// The largest difference of a frame from the still picture: the median of the frames block by block, each frame - /// first brought to the brightness of the brightest one. + /// The largest difference of a frame from the still picture, on the blocks and on the finer cells (luma only): the + /// median of the frames, each first brought to the brightness of the brightest one. «Small» tells that at least the + /// area of a block changed. /// - private static (double Mean, double Area) AgainstStillPicture(List pictures) + private static (double Mean, double Area, bool Small) AgainstStillPicture(List pictures) { if (pictures.Count < 2) { - return (0, 0); + return (0, 0, false); } var reference = pictures.MaxBy(p => p.Luma.Sum())!; var gains = pictures.Select(p => Gain(p, reference)).ToArray(); - var luma = new double[Signature.Blocks]; - var blue = new double[Signature.Blocks]; - var red = new double[Signature.Blocks]; - var clipped = new double[Signature.Blocks]; - var values = new double[pictures.Count]; - for (var i = 0; i < Signature.Blocks; i++) + var (mean, area) = AgainstStillPicture([.. pictures.Select(p => p.Coarse)], gains, ChromaWeight); + var (fineMean, fineArea) = pictures.All(p => p.Fine.Columns == reference.Fine.Columns && p.Fine.Rows == reference.Fine.Rows) + ? AgainstStillPicture([.. pictures.Select(p => p.Fine)], gains, 0) + : (0, 0); // a stream that changes size: the cells are not the same places + return (Math.Max(mean, fineMean), Math.Max(area, fineArea), area > 0 || fineArea >= 1.0 / Signature.Blocks); + } + + private static (double Mean, double Area) AgainstStillPicture(Grid[] frames, double[] gains, double chroma) + { + var still = new Grid(frames[0].Columns, frames[0].Rows); + var values = new double[frames.Length]; + for (var channel = 0; channel < Grid.Channels; channel++) { - luma[i] = Median(values, pictures, gains, p => p.Luma[i]); - blue[i] = Median(values, pictures, gains, p => p.BlueDifference[i]); - red[i] = Median(values, pictures, gains, p => p.RedDifference[i]); - clipped[i] = pictures.Max(p => p.Clipped[i]); + for (var i = 0; i < still.Count; i++) + { + // The lower median: with an even count the lower of the two middle values, so that of two frames neither + // is averaged away. + float clipped = 0; + for (var k = 0; k < frames.Length; k++) + { + values[k] = frames[k].Mean[channel][i] / gains[k]; + clipped = Math.Max(clipped, frames[k].Clipped[channel][i]); + } + + Array.Sort(values); + still.Mean[channel][i] = (float)values[(values.Length - 1) / 2]; + still.Clipped[channel][i] = clipped; + } } - // Under a fade a block clipped at white in any frame is left out of every one: the still picture there is - // not what the brightest frame shows. - var fade = gains.Any(IsFade); + var lowest = gains.Min(); double mean = 0, area = 0; - for (var k = 0; k < pictures.Count; k++) + for (var k = 0; k < frames.Length; k++) { - var (m, a) = Measure(pictures[k], luma, blue, red, gains[k], clipped, fade); + var (m, a) = Measure(frames[k], still, gains[k], lowest, chroma); mean = Math.Max(mean, m); area = Math.Max(area, a); } @@ -343,74 +516,62 @@ public static class StillVideoAnalyzer } /// - /// The lower median, block by block, of the pictures brought to the reference brightness: with an even count the - /// lower of the two middle values, so that of two frames neither is averaged away. + /// The mean difference of the cells (each capped at ) and the fraction of them over it, + /// between and brought to its brightness ( + /// times its own). A cell clipped at white may hide brightness: a frame darker than the picture may show there up to + /// what the picture lost, a brighter one less than the picture (measured on frames as dark as + /// ) has; that much of the difference does not count. /// - private static double Median(double[] values, List pictures, double[] gains, Func value) + private static (double Mean, double Area) Measure(Grid frame, Grid picture, double gain, double lowest, double chroma) { - for (var k = 0; k < pictures.Count; k++) - { - values[k] = value(pictures[k]) / gains[k]; - } - - Array.Sort(values); - return values[(values.Length - 1) / 2]; - } - - /// - /// The mean block difference (each capped at ) and the fraction of blocks over it between - /// frame and the blocks of , where is a's - /// brightness against them: the brighter side is scaled down. Under a , blocks clipped at - /// white in either () are left out, unless that leaves fewer than half. - /// - private static (double Mean, double Area) Measure(Signature a, double[] lumaB, double[] blueB, double[] redB, double gain, - double[] clippedB, bool fade) - { - var (scaleA, scaleB) = gain > 1 ? (1 / gain, 1.0) : (1.0, gain); - var usable = fade ? Enumerable.Range(0, Signature.Blocks).Count(i => a.Clipped[i] <= ClippedShare && clippedB[i] <= ClippedShare) : Signature.Blocks; - var skip = fade && usable >= Signature.Blocks / 2; + var above = 255 * Math.Max(0, 1 - gain); + var below = 255 * Math.Max(0, (gain / lowest) - 1); + var scale = 1 / Math.Max(1, gain); double sum = 0; var changed = 0; - var compared = 0; - for (var i = 0; i < Signature.Blocks; i++) + for (var i = 0; i < frame.Count; i++) { - if (skip && (a.Clipped[i] > ClippedShare || clippedB[i] > ClippedShare)) - { - continue; - } - - var d = Math.Abs((scaleA * a.Luma[i]) - (scaleB * lumaB[i])) - + (ChromaWeight * (Math.Abs((scaleA * a.BlueDifference[i]) - (scaleB * blueB[i])) - + Math.Abs((scaleA * a.RedDifference[i]) - (scaleB * redB[i])))); + var d = scale * Difference(Channel(0, i), Channel(1, i), Channel(2, i), chroma); if (d > BlockThreshold) { changed++; } sum += Math.Min(d, BlockThreshold); - compared++; } - return (sum / compared, (double)changed / compared); + return (sum / frame.Count, (double)changed / frame.Count); + + double Channel(int c, int i) + { + var d = frame.Mean[c][i] - Math.Min(255, gain * picture.Mean[c][i]); + return d > 0 + ? Math.Max(0, d - (picture.Clipped[c][i] * above)) + : Math.Min(0, d + (frame.Clipped[c][i] * below)); + } } - private static bool IsFade(double gain) => Math.Abs(gain - 1) > GainTolerance; + /// The difference of two colours: of luma, and of B − Y and R − Y by the weight . + private static double Difference(double red, double green, double blue, double chroma) + { + var luma = Bt709(red, green, blue); + return Math.Abs(luma) + (chroma * (Math.Abs(blue - luma) + Math.Abs(red - luma))); + } + + private static double Bt709(double red, double green, double blue) => (0.2126 * red) + (0.7152 * green) + (0.0722 * blue); /// /// The brightness of against when it is a fade of it: the median ratio of /// the blocks, provided the middle half of the ratios agree within (a different picture - /// gives ratios all over); 1 otherwise. Dark blocks and blocks clipped at white do not count. + /// gives ratios all over); 1 otherwise. Dark blocks do not count, nor blocks clipped at white, unless fewer than a + /// quarter of the blocks are left (a white card, a saturated poster): then the clipped ones count too. /// private static double Gain(Signature a, Signature b) { - var ratios = new List(Signature.Blocks); - for (var i = 0; i < Signature.Blocks; i++) + var ratios = Ratios(a, b, clippedToo: false); + if (ratios.Count < Signature.Blocks / 4) { - if (Math.Max(a.Luma[i], b.Luma[i]) >= GainFloor && a.Luma[i] > 0.5 && b.Luma[i] > 0.5 - && a.Clipped[i] <= ClippedShare && b.Clipped[i] <= ClippedShare) - { - ratios.Add(Math.Log(a.Luma[i] / b.Luma[i])); - } + ratios = Ratios(a, b, clippedToo: true); } if (ratios.Count < Signature.Blocks / 4) @@ -424,31 +585,126 @@ public static class StillVideoAnalyzer : Math.Clamp(Math.Exp(ratios[ratios.Count / 2]), 1 / GainRange, GainRange); } - /// What is kept of a frame looked at: its grid of blocks, whether it is dark or of one colour, its sharpness. + private static List Ratios(Signature a, Signature b, bool clippedToo) + { + var ratios = new List(Signature.Blocks); + for (var i = 0; i < Signature.Blocks; i++) + { + if (Math.Max(a.Luma[i], b.Luma[i]) >= GainFloor && a.Luma[i] > 0.5 && b.Luma[i] > 0.5 + && (clippedToo || (a.Clipped[i] <= ClippedShare && b.Clipped[i] <= ClippedShare))) + { + ratios.Add(Math.Log(a.Luma[i] / b.Luma[i])); + } + } + + return ratios; + } + + /// The picture in cells: for each channel the mean of the cell and the share of it clipped at white. + private sealed class Grid + { + internal const int Channels = 3; + + internal Grid(int columns, int rows) + { + (Columns, Rows) = (columns, rows); + for (var c = 0; c < Channels; c++) + { + (Mean[c], Clipped[c]) = (new float[Count], new float[Count]); + } + } + + internal int Columns { get; } + + internal int Rows { get; } + + internal int Count => Columns * Rows; + + /// The means of each cell, by channel: red, green and blue. + internal float[][] Mean { get; } = new float[Channels][]; + + /// The shares of each cell clipped at white, by channel. + internal float[][] Clipped { get; } = new float[Channels][]; + + /// + /// The grid of an RGBA frame. Each cell covers at least one pixel, so a frame narrower than the grid (or a stream + /// that changes size) still gives a full grid. , when given, gets the share of the + /// pixels of each cell with any channel clipped. + /// + internal static Grid Of(RgbaImage image, int columns, int rows, double[]? clippedAny = null) + { + var grid = new Grid(columns, rows); + var (w, h) = (image.Width, image.Height); + ReadOnlySpan pixels = image.Pixels; + var stride = image.Stride; + for (var gy = 0; gy < rows; gy++) + { + var y0 = gy * h / rows; + var y1 = Math.Max(y0 + 1, (gy + 1) * h / rows); + for (var gx = 0; gx < columns; gx++) + { + var x0 = gx * w / columns; + var x1 = Math.Max(x0 + 1, (gx + 1) * w / columns); + long r = 0, g = 0, b = 0; + int wr = 0, wg = 0, wb = 0, any = 0; + for (var y = y0; y < y1; y++) + { + var row = pixels.Slice((y * stride) + (x0 * RgbaImage.BytesPerPixel), (x1 - x0) * RgbaImage.BytesPerPixel); + for (var i = 0; i < row.Length; i += RgbaImage.BytesPerPixel) + { + var (pr, pg, pb) = (row[i], row[i + 1], row[i + 2]); + r += pr; + g += pg; + b += pb; + if (pr >= White || pg >= White || pb >= White) + { + any++; + wr += pr >= White ? 1 : 0; + wg += pg >= White ? 1 : 0; + wb += pb >= White ? 1 : 0; + } + } + } + + float count = (long)(y1 - y0) * (x1 - x0); + var cell = (gy * columns) + gx; + (grid.Mean[0][cell], grid.Mean[1][cell], grid.Mean[2][cell]) = (r / count, g / count, b / count); + (grid.Clipped[0][cell], grid.Clipped[1][cell], grid.Clipped[2][cell]) = (wr / count, wg / count, wb / count); + if (clippedAny is not null) + { + clippedAny[cell] = any / count; + } + } + } + + return grid; + } + } + + /// What is kept of a frame looked at: its grids, whether it is dark or of one colour, its sharpness. private sealed class Signature { internal const int Blocks = GridSize * GridSize; - /// A channel at least this bright is taken as clipped at white. - private const int White = 250; - - private Signature(TimeSpan actual) + private Signature(TimeSpan actual, Grid coarse, Grid fine, double[] clipped) { - Actual = actual; + (Actual, Coarse, Fine, Clipped) = (actual, coarse, fine, clipped); } internal TimeSpan Actual { get; } + internal Grid Coarse { get; } + + internal Grid Fine { get; } + + /// The luma of each block. internal double[] Luma { get; } = new double[Blocks]; - /// B − Y of each block. - internal double[] BlueDifference { get; } = new double[Blocks]; - - /// R − Y of each block. - internal double[] RedDifference { get; } = new double[Blocks]; - /// The share of the pixels of each block with a channel clipped at white. - internal double[] Clipped { get; } = new double[Blocks]; + internal double[] Clipped { get; } + + /// The mean colour of the frame, and the largest of its channels. + internal (double R, double G, double B, double Largest) Colour { get; private set; } internal bool Dark { get; private set; } @@ -456,55 +712,68 @@ public static class StillVideoAnalyzer internal double Sharpness { get; private set; } - /// - /// The signature of an upright RGBA frame. Each block covers at least one pixel, so a frame narrower than the grid - /// (or a stream that changes size) still gives a full grid. - /// + /// The signature of an upright RGBA frame. internal static Signature Of(RgbaImage image, TimeSpan actual) { - var s = new Signature(actual); var (w, h) = (image.Width, image.Height); - ReadOnlySpan pixels = image.Pixels; - var stride = image.Stride; + var clipped = new double[Blocks]; + var coarse = Grid.Of(image, GridSize, GridSize, clipped); + var fine = Grid.Of(image, Math.Clamp(w / FineCell, 1, FineGridSize), Math.Clamp(h / FineCell, 1, FineGridSize)); + var s = new Signature(actual, coarse, fine, clipped); + var blue = new double[Blocks]; + var red = new double[Blocks]; var brightest = 0.0; - for (var gy = 0; gy < GridSize; gy++) + for (var i = 0; i < Blocks; i++) { - var y0 = gy * h / GridSize; - var y1 = Math.Max(y0 + 1, (gy + 1) * h / GridSize); - for (var gx = 0; gx < GridSize; gx++) - { - var x0 = gx * w / GridSize; - var x1 = Math.Max(x0 + 1, (gx + 1) * w / GridSize); - long r = 0, g = 0, b = 0; - var white = 0; - for (var y = y0; y < y1; y++) - { - var row = pixels.Slice((y * stride) + (x0 * RgbaImage.BytesPerPixel), (x1 - x0) * RgbaImage.BytesPerPixel); - for (var i = 0; i < row.Length; i += RgbaImage.BytesPerPixel) - { - r += row[i]; - g += row[i + 1]; - b += row[i + 2]; - white += row[i] >= White || row[i + 1] >= White || row[i + 2] >= White ? 1 : 0; - } - } + double r = coarse.Mean[0][i], g = coarse.Mean[1][i], b = coarse.Mean[2][i]; + var luma = Bt709(r, g, b); + (s.Luma[i], blue[i], red[i]) = (luma, b - luma, r - luma); + brightest = Math.Max(brightest, Math.Max(r, Math.Max(g, b))); + } - double count = (long)(y1 - y0) * (x1 - x0); - var (mr, mg, mb) = (r / count, g / count, b / count); - var luma = (0.2126 * mr) + (0.7152 * mg) + (0.0722 * mb); - var cell = (gy * GridSize) + gx; - s.Luma[cell] = luma; - s.BlueDifference[cell] = mb - luma; - s.RedDifference[cell] = mr - luma; - s.Clipped[cell] = white / count; - brightest = Math.Max(brightest, Math.Max(mr, Math.Max(mg, mb))); + var (cr, cg, cb) = (coarse.Mean[0].Average(v => (double)v), coarse.Mean[1].Average(v => (double)v), coarse.Mean[2].Average(v => (double)v)); + s.Colour = (cr, cg, cb, Math.Max(cr, Math.Max(cg, cb))); + ReadOnlySpan pixels = image.Pixels; + s.Dark = brightest < DarkLevel && !HasBrightDetail(pixels, w, h, image.Stride); + s.Uniform = Spread(s.Luma) < UniformSpread && Spread(blue) < UniformSpread && Spread(red) < UniformSpread + && !HasDetail(pixels, w, h, image.Stride, Bt709(cr, cg, cb)); + s.Sharpness = LaplacianVariance(pixels, w, h, image.Stride); + return s; + } + + /// Whether some pixels are bright: a small text on black, lost in the means of the blocks. + private static bool HasBrightDetail(ReadOnlySpan pixels, int w, int h, int stride) + { + long bright = 0; + for (var y = 0; y < h; y++) + { + var row = pixels.Slice(y * stride, w * RgbaImage.BytesPerPixel); + for (var i = 0; i < row.Length; i += RgbaImage.BytesPerPixel) + { + bright += Math.Max(row[i], Math.Max(row[i + 1], row[i + 2])) >= BrightDetail ? 1 : 0; } } - s.Dark = brightest < DarkLevel; - s.Uniform = Spread(s.Luma) < UniformSpread && Spread(s.BlueDifference) < UniformSpread && Spread(s.RedDifference) < UniformSpread; - s.Sharpness = LaplacianVariance(pixels, w, h, stride); - return s; + return bright > DetailShare * w * h; + } + + /// Whether the pixels vary, though the blocks do not: a small text, a fine texture. + private static bool HasDetail(ReadOnlySpan pixels, int w, int h, int stride, double mean) + { + double squares = 0; + long far = 0; + for (var y = 0; y < h; y++) + { + var row = pixels.Slice(y * stride, w * RgbaImage.BytesPerPixel); + for (var i = 0; i < row.Length; i += RgbaImage.BytesPerPixel) + { + var d = Bt709(row[i], row[i + 1], row[i + 2]) - mean; + squares += d * d; + far += Math.Abs(d) > UniformDetail ? 1 : 0; + } + } + + return squares >= UniformVariance * w * h || far > DetailShare * w * h; } private static double Spread(double[] values) @@ -566,4 +835,75 @@ public static class StillVideoAnalyzer } } } + + /// + /// The stream, remembering the first error of its own: an or an + /// thrown by it, not the ones the readers raise above it for a file cut + /// short or damaged. + /// + private sealed class WatchedStream(Stream inner) : Stream + { + internal ExceptionDispatchInfo? Fault { get; private set; } + + public override bool CanRead => true; + + public override bool CanSeek => true; + + public override bool CanWrite => false; + + public override long Length + { + get + { + try + { + return inner.Length; + } + catch (Exception ex) + { + Remember(ex); + throw; + } + } + } + + public override long Position + { + get => inner.Position; + set => inner.Position = value; // reads nothing: an error comes from a damaged table + } + + public override int Read(byte[] buffer, int offset, int count) => Read(buffer.AsSpan(offset, count)); + + public override int Read(Span buffer) + { + try + { + return inner.Read(buffer); + } + catch (Exception ex) + { + Remember(ex); + throw; + } + } + + public override long Seek(long offset, SeekOrigin origin) => inner.Seek(offset, origin); + + public override void Flush() + { + } + + public override void SetLength(long value) => throw new NotSupportedException(); + + public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException(); + + private void Remember(Exception ex) + { + if (ex is UnauthorizedAccessException or (IOException and not EndOfStreamException)) + { + Fault ??= ExceptionDispatchInfo.Capture(ex); + } + } + } } diff --git a/src/Febe.Core/Library/VideoFrameDecoder.cs b/src/Febe.Core/Library/VideoFrameDecoder.cs index 03c160c..9fa04a1 100644 --- a/src/Febe.Core/Library/VideoFrameDecoder.cs +++ b/src/Febe.Core/Library/VideoFrameDecoder.cs @@ -151,7 +151,7 @@ public sealed partial class VideoFrameDecoder var target = SampleAt(video, at); // Too far from where decoding can start: the frame there stands for it, so the work stays bounded. - var start = decoding.RunStart(target); + var start = decoding.RunStart(target, ct); if (target - start > maxRun) { target = start; @@ -352,11 +352,11 @@ public sealed partial class VideoFrameDecoder /// out exact); otherwise the nearest close one (an H.264 picture of I slices, an HEVC CRA picture: close, though /// pictures after it may refer to earlier ones); otherwise the exact start further back, or the first sample. /// - internal int RunStart(int index) + internal int RunStart(int index, CancellationToken ct) { if (exact) { - return ExactStart(index); + return ExactStart(index, ct); } var position = Array.BinarySearch(keys, index); @@ -367,6 +367,7 @@ public sealed partial class VideoFrameDecoder var candidate = keys[position]; if (!accessPoints.TryGetValue(candidate, out var point)) { + ct.ThrowIfCancellationRequested(); // each one reads a whole sample point = AccessPointOf(candidate); accessPoints[candidate] = point; } @@ -395,7 +396,7 @@ public sealed partial class VideoFrameDecoder /// The nearest start from which comes out exact, however far: an IDR picture, or a /// recovery point shown no later than it; otherwise the first sample. /// - private int ExactStart(int index) + private int ExactStart(int index, CancellationToken ct) { var position = Array.BinarySearch(keys, index); position = position >= 0 ? position : Math.Max(0, ~position - 1); @@ -405,6 +406,7 @@ public sealed partial class VideoFrameDecoder var candidate = keys[position]; if (!accessPoints.TryGetValue(candidate, out var point)) { + ct.ThrowIfCancellationRequested(); // each one reads a whole sample point = AccessPointOf(candidate); accessPoints[candidate] = point; } @@ -477,7 +479,7 @@ public sealed partial class VideoFrameDecoder var next = 0; foreach (var target in targets) { - var key = RunStart(target); + var key = RunStart(target, ct); if (runner is null || next > target || key >= next) { runner = null; diff --git a/src/Febe.Core/Library/VideoFrames.cs b/src/Febe.Core/Library/VideoFrames.cs index 5449139..32e9828 100644 --- a/src/Febe.Core/Library/VideoFrames.cs +++ b/src/Febe.Core/Library/VideoFrames.cs @@ -93,9 +93,10 @@ public sealed class VideoFrameReader : IDisposable /// /// Opens the video in (left open: the caller disposes it after the reader). Never - /// throws for a video it cannot read: is then not available, and the reader gives no frame. + /// throws for a video it cannot read: is then not available, and the reader gives no frame. A + /// cancellation of while the container is read is thrown. /// - public static VideoFrameReader Open(Stream seekable, out VideoFrameInfo info) + public static VideoFrameReader Open(Stream seekable, out VideoFrameInfo info, CancellationToken ct = default) { ArgumentNullException.ThrowIfNull(seekable); MediaContainer? container; @@ -103,7 +104,7 @@ public sealed class VideoFrameReader : IDisposable try { seekable.Position = 0; - container = ContainerReader.Read(seekable, ContainerReader.AnyDate, samples: true); + container = ContainerReader.Read(seekable, ContainerReader.AnyDate, samples: true, ct); video = container is null ? null : VideoFrameDecoder.FrameTrack(container); } catch (Exception ex) when (VideoFrameDecoder.IsUnreadableFile(ex)) @@ -164,6 +165,22 @@ public sealed class VideoFrameReader : IDisposable return targets; } + /// + /// Every picture the video shows, in shown order (edit lists applied): the still-video analysis chooses among them + /// (tappa E4). Empty when the video is not available. + /// + internal IReadOnlyList Shown() + { + var targets = new VideoFrameTarget[order.Length]; + for (var i = 0; i < targets.Length; i++) + { + var at = ShownAt(order[i]); + targets[i] = new VideoFrameTarget(i, at, at, order[i]); + } + + return targets; + } + /// /// As , but each instant moves to the key sample (a sync sample: a frame decoding can start from) /// shown nearest to it, when one is shown within of it (the earlier of two as near): a frame diff --git a/tests/Febe.Tests/Media/Containers/PcmVideos.cs b/tests/Febe.Tests/Media/Containers/PcmVideos.cs index a068604..dde5f1d 100644 --- a/tests/Febe.Tests/Media/Containers/PcmVideos.cs +++ b/tests/Febe.Tests/Media/Containers/PcmVideos.cs @@ -41,6 +41,53 @@ internal static class PcmVideos public static byte[] Mp4(int count, Func picture, int rotation = 0, bool audio = false) => TestVideos.Mp4(Stream("pcm", count, picture), rotation: rotation, audio: audio); + /// + /// An MP4 of pictures of × (multiples of + /// 16), one a second: for what depends on the size of the picture. + /// + public static byte[] Large(int width, int height, int count, Func picture) + { + using var output = new MemoryStream(); + H264PcmWriter.WriteMp4(output, width, height, count, 1, picture); + return output.ToArray(); + } + + /// A grey picture of any size (multiples of 16) whose luma at (x, y) is given, clamped to 16–235. + public static H264PcmPicture Grey(int width, int height, Func luma) + { + var p = new H264PcmPicture(width, height); + for (var y = 0; y < height; y++) + { + for (var x = 0; x < width; x++) + { + p.Y[(y * width) + x] = Luma((int)Math.Round(luma(x, y))); + } + } + + Array.Fill(p.Cb, (byte)128); + Array.Fill(p.Cr, (byte)128); + return p; + } + + /// A poster: one colour, and a photo on the bottom of it. + public static H264PcmPicture Poster(byte luma, byte cb, byte cr, double share) + { + var p = Flat(luma, cb, cr); + var photo = Photo(4); + var top = Height - ((int)(Height * share) / 2 * 2); + for (var i = top * Width; i < p.Y.Length; i++) + { + p.Y[i] = (byte)(photo.Y[i] * 0.8); + } + + for (var i = top / 2 * (Width / 2); i < p.Cb.Length; i++) + { + (p.Cb[i], p.Cr[i]) = (photo.Cb[i], photo.Cr[i]); + } + + return p; + } + /// /// A photo-like picture: a diagonal gradient, a few coloured shapes and a fine texture (so it has detail to be sharp /// with). Luma 16–235, chroma 16–240. diff --git a/tests/Febe.Tests/Media/Containers/StillVideoAnalyzerTests.cs b/tests/Febe.Tests/Media/Containers/StillVideoAnalyzerTests.cs index 3fc61ab..b618971 100644 --- a/tests/Febe.Tests/Media/Containers/StillVideoAnalyzerTests.cs +++ b/tests/Febe.Tests/Media/Containers/StillVideoAnalyzerTests.cs @@ -1,3 +1,4 @@ +using System.Buffers.Binary; using Febe.Core.Codecs.Containers; using Febe.Core.Codecs.H264; using Febe.Core.Domain; @@ -192,10 +193,20 @@ public sealed class StillVideoAnalyzerTests Assert.AreEqual(VideoAnalysisOutcome.NotAnalyzable, single.Outcome, Describe(single)); Assert.AreEqual(VideoAnalysisNotes.SingleColor, single.Note); - // A muted colour (a saturated one clips at white, and a fade of it cannot be undone). + // Fading too, from black and to black: a muted colour, and white, near white, red, blue, green and yellow, which + // clip or are too dark for a fade to be undone block by block. var brick = PcmVideos.Flat(110, 110, 170); var fading = Analyse(PcmVideos.Mp4(30, i => i < 9 ? PcmVideos.Fade(brick, i / 9.0) : PcmVideos.Noise(brick, 2, i))); Assert.AreEqual(VideoAnalysisNotes.SingleColor, fading.Note, Describe(fading)); + foreach (var (y, cb, cr) in new (byte, byte, byte)[] { (235, 128, 128), (235, 120, 136), (81, 90, 240), (41, 240, 110), (145, 54, 34), (210, 16, 146) }) + { + var colour = PcmVideos.Flat(y, cb, cr); + foreach (var light in new Func[] { i => Math.Min(1, i / 9.0), i => Math.Min(1, i / 20.0), i => Math.Min(1, (29 - i) / 9.0) }) + { + var faded = Analyse(PcmVideos.Mp4(30, i => PcmVideos.Fade(colour, light(i)))); + Assert.AreEqual(VideoAnalysisNotes.SingleColor, faded.Note, $"{y},{cb},{cr}: {Describe(faded)}"); + } + } // One colour after another: the picture changes. var blue = PcmVideos.Flat(41, 240, 110); @@ -293,14 +304,36 @@ public sealed class StillVideoAnalyzerTests Assert.AreEqual(VideoAnalysisOutcome.NotAnalyzable, vp9.Outcome); Assert.AreEqual(VideoAnalysisNotes.FrameNotAvailable, vp9.Note); - // Cut short anywhere: never an exception, and never «Fermo» from frames that are not there. + // Cut short anywhere: never an exception, and never «Fermo» from frames that are not there. Past the last frame + // looked at nothing is missing. var whole = PcmVideos.Mp4(30, _ => PcmVideos.Photo(18)); - foreach (var length in new[] { whole.Length / 10, whole.Length / 2, whole.Length - 1000 }) + foreach (var tenths in new[] { 1, 3, 5, 9 }) { - var cut = Analyse(whole[..length]); - Assert.AreNotEqual(VideoAnalysisOutcome.Moving, cut.Outcome, $"{length}: {Describe(cut)}"); + var cut = Analyse(whole[..(whole.Length * tenths / 10)]); + Assert.AreEqual((VideoAnalysisOutcome.NotAnalyzable, VideoAnalysisNotes.Unreadable), (cut.Outcome, cut.Note), $"{tenths}/10: {Describe(cut)}"); + Assert.IsNull(cut.FrameAt); } + var nearlyWhole = Analyse(whole[..^1000]); + Assert.AreEqual(VideoAnalysisOutcome.Still, nearlyWhole.Outcome, Describe(nearlyWhole)); + + // A video that changes at picture 14: «Fermo» from its first part would be false. Motion already seen stands. + var before = PcmVideos.Photo(18); + var after = PcmVideos.Photo(27); + var changing = PcmVideos.Stream("pcm", 30, i => i < 14 ? before : after); + var full = TestVideos.Mp4(changing); + Assert.AreEqual(VideoAnalysisOutcome.Moving, Analyse(full).Outcome); + var half = Analyse(full[..(full.Length * 4 / 10)]); + Assert.AreEqual(VideoAnalysisNotes.Unreadable, half.Note, Describe(half)); + Assert.AreEqual(VideoAnalysisOutcome.Moving, Analyse(full[..(full.Length * 8 / 10)]).Outcome); + for (var i = 12; i < changing.Count; i++) + { + changing.Units[i] = [.. changing.Units[i].Select(n => n[..Math.Min(n.Length, 6)])]; + } + + var damaged = Analyse(TestVideos.Mp4(changing)); + Assert.AreEqual(VideoAnalysisNotes.Unreadable, damaged.Note, Describe(damaged)); + using var temp = new TempFolder("fermo-illeggibile"); var missing = await StillVideoAnalyzer.AnalyseAsync(temp.Combine("non-esiste.mp4"), TimeSpan.FromSeconds(30)); Assert.AreEqual(VideoAnalysisNotes.Unreadable, missing.Note); @@ -475,6 +508,343 @@ public sealed class StillVideoAnalyzerTests (1, 7, 32, 32.0, 2.0, 12.0, 3.0, 0.05), (StillVideoAnalyzer.Algorithm, StillVideoAnalyzer.Samples, StillVideoAnalyzer.GridSize, StillVideoAnalyzer.DarkLevel, StillVideoAnalyzer.UniformSpread, StillVideoAnalyzer.BlockThreshold, StillVideoAnalyzer.MeanThreshold, StillVideoAnalyzer.AreaThreshold)); + Assert.AreEqual( + (128, 4, 3.0, 16.0, 0.1, 8.0, 0.1), + (StillVideoAnalyzer.FineGridSize, StillVideoAnalyzer.FineCell, StillVideoAnalyzer.EarlyAreaFactor, StillVideoAnalyzer.GainFloor, + StillVideoAnalyzer.GainAgreement, StillVideoAnalyzer.GainRange, StillVideoAnalyzer.ClippedShare)); + Assert.AreEqual( + (250, 0.25, 96, 64.0, 32.0, 0.0002, TimeSpan.FromSeconds(1e9)), + (StillVideoAnalyzer.White, StillVideoAnalyzer.ChromaWeight, StillVideoAnalyzer.BrightDetail, StillVideoAnalyzer.UniformVariance, + StillVideoAnalyzer.UniformDetail, StillVideoAnalyzer.DetailShare, StillVideoAnalyzer.LatestInstant)); + CollectionAssert.AreEqual(new[] { 0.4173, 0.3611, 0.6237, 0.5, 0.6619, 0.3307, 0.5521 }, StillVideoAnalyzer.Offsets); + } + + [TestMethod] + public void TheColourCountsToo() + { + // Half of the photo turns from bluish to reddish with the same luma. + var photo = PcmVideos.Photo(28); + var tinted = PcmVideos.Copy(photo); + for (var i = 0; i < tinted.Cb.Length / 2; i++) + { + (tinted.Cb[i], tinted.Cr[i]) = (90, 190); + } + + var result = Analyse(PcmVideos.Mp4(30, i => i < 15 ? photo : tinted)); + Assert.AreEqual(VideoAnalysisOutcome.Moving, result.Outcome, Describe(result)); + } + + [TestMethod] + [DataRow(7)] + [DataRow(14)] + [DataRow(16)] + public void AClipRepeatedManyTimesIsMotion(int times) + { + // A GIF or a boomerang repeated: its key frames come back at every repetition, and equal steps fall on the same + // picture of it when the number of repetitions is a multiple of the frames looked at. + var clip = ElementaryStream.AnnexB("CABA3_SVA_B"); + var loop = Analyse(TestVideos.Mp4(ElementaryStream.FromAnnexB("ripetuto", [.. Enumerable.Repeat(clip, times).SelectMany(b => b)]))); + Assert.AreEqual(VideoAnalysisOutcome.Moving, loop.Outcome, Describe(loop)); + + var photo = PcmVideos.Photo(29); + var boomerang = Analyse(PcmVideos.Mp4(20 * times, i => PcmVideos.Shift(photo, 4 * (i % 20 < 10 ? i % 20 : 19 - (i % 20))))); + Assert.AreEqual(VideoAnalysisOutcome.Moving, boomerang.Outcome, Describe(boomerang)); + } + + [TestMethod] + [DataRow(0.0)] + [DataRow(0.015)] + [DataRow(0.025)] + public void MotionOverAWhiteAreaIsSeenWhileTheLightDrifts(double step) + { + // The upper half is burnt out (a sky, a wall), the ground below brightens a little at each frame as the exposure + // adjusts itself: what moves over the white is still motion. + byte[] Video(Func over, int luma) => PcmVideos.Large(256, 256, 7, k => PcmVideos.Grey(256, 256, (x, y) => + y >= 120 ? 16 + ((1 + (step * k)) * (40 + (x * 60.0 / 256) + ((y - 120) * 60.0 / 256))) : over(k, x, y) ? luma : 235)); + + foreach (var luma in new[] { 40, 120 }) + { + var crossing = Analyse(Video((k, x, y) => x >= k * 20 && x < (k * 20) + 100 && y is >= 8 and < 108, luma)); + Assert.AreEqual(VideoAnalysisOutcome.Moving, crossing.Outcome, Describe(crossing)); + } + + var covered = Analyse(Video((k, x, _) => k == 3 && x < 220, 40)); + Assert.AreEqual(VideoAnalysisOutcome.Moving, covered.Outcome, Describe(covered)); + + // Nothing moves over it: the drift alone is no motion. + var still = Analyse(Video((_, x, y) => x is >= 60 and < 160 && y is >= 8 and < 108, 40)); + Assert.AreEqual(VideoAnalysisOutcome.Still, still.Outcome, Describe(still)); + } + + [TestMethod] + public void AWhiteOrSaturatedCardWithAFadeIsStill() + { + foreach (var (y, cb, cr) in new (byte, byte, byte)[] { (235, 128, 128), (81, 90, 240), (225, 128, 128) }) + { + foreach (var share in new[] { 0.1, 0.15, 0.3 }) + { + var poster = PcmVideos.Poster(y, cb, cr, share); + foreach (var pictures in new[] { 4.0, 9.0 }) + { + var faded = Analyse(PcmVideos.Mp4(30, i => PcmVideos.Fade(poster, Math.Min(1, i / pictures)))); + Assert.AreEqual(VideoAnalysisOutcome.Still, faded.Outcome, $"{y},{cb},{cr}, {share}, {pictures}: {Describe(faded)}"); + Assert.IsNull(faded.Note, Describe(faded)); + } + } + } + + // A white card with black text, five seconds. + var card = PcmVideos.Grey(PcmVideos.Width, PcmVideos.Height, (x, y) => + y is > 80 and < 170 && y / 6 % 2 == 0 && x is > 20 and < 124 && x / 5 % 2 == 0 ? 20 : 235); + var text = Analyse(PcmVideos.Mp4(150, i => PcmVideos.Fade(card, Math.Min(1, i / 30.0)))); + Assert.AreEqual(VideoAnalysisOutcome.Still, text.Outcome, Describe(text)); + } + + [TestMethod] + public void OnePictureAmongDarkFramesSaysNothingOfTheVideo() + { + // Only one of the seven frames is not dark, but the lit part is full of different pictures. + foreach (var (name, picture) in new (string, Func)[] + { + ("nero, poi foto", i => i < 60 ? PcmVideos.Black() : PcmVideos.Photo(i + 1)), + ("foto, poi nero", i => i >= 10 ? PcmVideos.Black() : PcmVideos.Photo(i + 1)), + ("notte, poi luce", i => PcmVideos.Fade(PcmVideos.Photo(i + 1), i < 60 ? 0.06 : 1)), + }) + { + var moving = Analyse(PcmVideos.Mp4(70, picture)); + Assert.AreEqual(VideoAnalysisOutcome.Moving, moving.Outcome, $"{name}: {Describe(moving)}"); + Assert.IsGreaterThan(StillVideoAnalyzer.Samples, moving.Sampled, "guardati anche quelli intorno"); + } + + // The same lit part with one picture is still; one picture only, alone among black ones, is not. + var photo = PcmVideos.Photo(30); + var still = Analyse(PcmVideos.Mp4(70, i => i < 60 ? PcmVideos.Black() : photo)); + Assert.AreEqual(VideoAnalysisOutcome.Still, still.Outcome, Describe(still)); + Assert.IsGreaterThanOrEqualTo(Ms(60), still.FrameAtMs!.Value); + var flash = Analyse(PcmVideos.Mp4(70, i => i == 35 ? photo : PcmVideos.Black())); + Assert.AreEqual(VideoAnalysisNotes.AllDark, flash.Note, Describe(flash)); + + // Unless it is all the video shows there: a picture held for ten seconds between two black ones. + var held = Analyse(Timed([(PcmVideos.Black(), 0.1), (photo, 10), (PcmVideos.Black(), 0.1)])); + Assert.AreEqual(VideoAnalysisOutcome.Still, held.Outcome, Describe(held)); + Assert.AreEqual(100L, held.FrameAtMs); + } + + [TestMethod] + public void PicturesShownForAMomentAfterAHeldOneAreLookedAtToo() + { + // A picture held for a minute, then 20 different ones in two thirds of a second: every instant falls on the first. + var pictures = Enumerable.Range(0, 20).Select(i => (PcmVideos.Photo(40 + i), 1.0 / PcmVideos.Fps)); + var result = Analyse(Timed([(PcmVideos.Photo(31), 60), .. pictures])); + Assert.AreEqual(VideoAnalysisOutcome.Moving, result.Outcome, Describe(result)); + } + + [TestMethod] + public void TheInstantsAreSpreadOverWhatTheVideoTrackShows() + { + // Two seconds of motion in a file that says half a minute or more (a longer audio track, a wrong header). + var two = TestVideos.Mp4(PcmVideos.Stream("pcm", 60, i => PcmVideos.Photo(i + 1)), audio: true); + foreach (var seconds in new[] { 29, 40 }) + { + var longer = Analyse(WithMovieDuration(two, seconds)); + Assert.AreEqual(VideoAnalysisOutcome.Moving, longer.Outcome, $"{seconds}: {Describe(longer)}"); + } + + // And in one that says half a second only. + var late = PcmVideos.Photo(32); + var early = PcmVideos.Photo(33); + var shorter = Analyse(WithMovieDuration(TestVideos.Mp4(PcmVideos.Stream("pcm", 60, i => i < 30 ? early : late)), 0.5)); + Assert.AreEqual(VideoAnalysisOutcome.Moving, shorter.Outcome, Describe(shorter)); + + // Ten seconds of motion trimmed by the edit list to half a second, with ten seconds of audio. + var ten = PcmVideos.Stream("pcm", 300, i => PcmVideos.Photo((i % 60) + 1)); + var trimmed = Analyse(TestVideos.Mov(ten, new MovOptions(VideoTrim: TestVideos.Timescale / 2, Audio: true))); + Assert.AreEqual(VideoAnalysisOutcome.Moving, trimmed.Outcome, Describe(trimmed)); + } + + [TestMethod] + public void AnErrorOfTheDiskIsThrownNeverAnOutcome() + { + // 25 equal pictures, then motion: whole it moves. Read past a point the disk (or the share) gives an error. + var data = PcmVideos.Mp4(60, i => PcmVideos.Photo(i < 25 ? 1 : i)); + Assert.AreEqual(VideoAnalysisOutcome.Moving, Analyse(data).Outcome); + foreach (var from in new[] { 100, data.Length / 5, data.Length * 3 / 10, data.Length * 4 / 10 }) + { + using var failing = new FailingStream(data, from); + var error = Assert.ThrowsExactly(() => StillVideoAnalyzer.Analyse(failing, CancellationToken.None), $"{from}"); + Assert.AreEqual("rete", error.Message); + using var denied = new FailingStream(data, from, new UnauthorizedAccessException("negato")); + Assert.ThrowsExactly(() => StillVideoAnalyzer.Analyse(denied, CancellationToken.None), $"{from}"); + } + } + + [TestMethod] + public void FineMotionOverTheWholePictureIsMotion() + { + // At 720 × 1280 a block averages about 900 pixels: static and snow leave its mean as it is. + const int w = 720, h = 1280; + var noise = Analyse(PcmVideos.Large(w, h, 7, i => + { + var random = new Random(i); + return PcmVideos.Grey(w, h, (_, _) => random.Next(16, 236)); + })); + Assert.AreEqual(VideoAnalysisOutcome.Moving, noise.Outcome, Describe(noise)); + + byte[] Snow(int flakes) => PcmVideos.Large(w, h, 7, i => + { + var random = new Random(i); + var p = PcmVideos.Grey(w, h, (_, y) => 90 + (y * 60.0 / h)); + for (var flake = 0; flake < flakes; flake++) + { + var at = (random.Next(h - 4) * w) + random.Next(w - 4); + for (var row = 0; row < 4; row++) + { + p.Y.AsSpan(at + (row * w), 4).Fill(230); + } + } + + return p; + }); + var thick = Analyse(Snow(1000)); + Assert.AreEqual(VideoAnalysisOutcome.Moving, thick.Outcome, Describe(thick)); + + // Sparse flakes change less than 5 % of the picture (answer 47): still, and the note says so. + var sparse = Analyse(Snow(300)); + Assert.AreEqual((VideoAnalysisOutcome.Still, VideoAnalysisNotes.SmallMotion), (sparse.Outcome, sparse.Note), Describe(sparse)); + + // Grain, even strong, is not motion at this size either. + var grain = Analyse(PcmVideos.Large(w, h, 7, i => + { + var random = new Random(i); + return PcmVideos.Grey(w, h, (x, y) => 60 + (x * 80.0 / w) + (y * 60.0 / h) + (((x / 40) + (y / 40)) % 2 * 20) + random.Next(-12, 13)); + })); + Assert.AreEqual((VideoAnalysisOutcome.Still, null), (grain.Outcome, grain.Note), Describe(grain)); + } + + [TestMethod] + public void ASmallTextOrAFineTextureIsAPicture() + { + const int w = 720, h = 1280, size = 14; + H264PcmPicture Text(int ground, int ink) => PcmVideos.Grey(w, h, (x, y) => + { + var (line, column) = (y - (h / 2), x - 150); + var letter = line is >= 0 and < size && column is >= 0 and < 160 && (column % 8 < 2 || (line < 2 && column % 8 < 6)); + return letter ? ink : ground; + }); + foreach (var (name, picture) in new[] { ("bianca su nero", Text(16, 235)), ("nera su bianco", Text(235, 16)) }) + { + var writing = Analyse(PcmVideos.Large(w, h, 7, _ => picture)); + Assert.AreEqual(VideoAnalysisOutcome.Still, writing.Outcome, $"{name}: {Describe(writing)}"); + } + + // A texture of two pixels: fixed it is a picture, panning it moves. + const int columns = (w + 300) / 2; + var random = new Random(3); + var grains = Enumerable.Range(0, columns * (h / 2)).Select(_ => random.Next(-40, 41)).ToArray(); + H264PcmPicture Texture(int shift) => PcmVideos.Grey(w, h, (x, y) => 120 + grains[(y / 2 * columns) + ((x + shift) / 2)]); + var texture = Texture(0); + var still = Analyse(PcmVideos.Large(w, h, 7, _ => texture)); + Assert.AreEqual(VideoAnalysisOutcome.Still, still.Outcome, Describe(still)); + var panning = Analyse(PcmVideos.Large(w, h, 7, i => Texture(37 * i))); + Assert.AreEqual(VideoAnalysisOutcome.Moving, panning.Outcome, Describe(panning)); + } + + [TestMethod] + public void ACancellationIsSeenWhileTheStartOfDecodingIsLookedFor() + { + // Every sample says it is a key one and only the first is: each is read to find that out. + var es = ElementaryStream.Load("HPCVMOLQ_BRCM_B"); + Array.Fill(es.Key, true); + var data = TestVideos.Mp4(es); + using var source = new CancellationTokenSource(); + using var stream = new FailingStream(data, data.Length + 1); + using var reader = VideoFrameReader.Open(stream, out var info); + Assert.IsTrue(info.Available); + var target = reader.Locate([info.Duration]); + var reads = 0; + stream.OnRead = () => + { + if (++reads == 3) + { + source.Cancel(); + } + }; + Assert.ThrowsExactly(() => reader.Decode(target, source.Token).ToList()); + Assert.AreEqual(3, reads, "nessun altro campione letto dopo l'annullamento"); + + // And while the container is read. + using var again = new MemoryStream(data); + Assert.ThrowsExactly(() => VideoFrameReader.Open(again, out _, source.Token)); + } + + [TestMethod] + public void AHostileStartTimeIsNotAnInstant() + { + // One picture after an empty edit of 2^40 seconds: its shown time is past what a TimeSpan holds. + var data = TestVideos.Mov(PcmVideos.Stream("pcm", 1, _ => PcmVideos.Photo()), new MovOptions(VideoEmptyEdit: TestVideos.Timescale)); + var movie = data.AsSpan().IndexOf("mvhd"u8) + 4; + BinaryPrimitives.WriteUInt32BigEndian(data.AsSpan(movie + (data[movie] == 1 ? 20 : 12)), 1); + var edits = data.AsSpan().IndexOf("elst"u8) + 4; + Assert.AreEqual(1, data[edits], "la versione a 64 bit, come la scrive TestVideos.Mov"); + BinaryPrimitives.WriteUInt64BigEndian(data.AsSpan(edits + 8), 1UL << 40); + + var result = Analyse(data); + Assert.AreEqual((VideoAnalysisOutcome.NotAnalyzable, VideoAnalysisNotes.DurationUnknown), (result.Outcome, result.Note), Describe(result)); + Assert.IsNull(result.FrameAt); + Assert.AreEqual(TimeSpan.MaxValue.Ticks / TimeSpan.TicksPerMillisecond, ExportFrames.ActualMs(TimeSpan.MaxValue)); + Assert.AreEqual(1L, ExportFrames.ActualMs(TimeSpan.FromTicks(1))); + } + + /// An MP4 of pictures held for as long as each says, in seconds. + private static byte[] Timed((H264PcmPicture Picture, double Seconds)[] pictures) + { + var es = PcmVideos.Stream("pcm", pictures.Length, i => pictures[i].Picture); + var times = pictures.Select((_, i) => (long)Math.Round(pictures.Take(i).Sum(p => p.Seconds) * TestVideos.Timescale)).ToArray(); + var track = new Mp4OutputTrack + { + IsVideo = true, + Timescale = TestVideos.Timescale, + Samples = [.. times.Select((at, i) => new Mp4OutputSample(es.LengthPrefixed(i).Length, at, at, true))], + WriteSample = (i, s) => s.Write(es.LengthPrefixed(i)), + Width = es.Width, + Height = es.Height, + AvcConfiguration = es.AvcC, + }; + using var output = new MemoryStream(); + Mp4Writer.Write(output, [track]); + return output.ToArray(); + } + + /// The MP4 with the length its movie header says replaced. + private static byte[] WithMovieDuration(byte[] mp4, double seconds) + { + var data = (byte[])mp4.Clone(); + var body = data.AsSpan().IndexOf("mvhd"u8) + 4; + var at = body + (data[body] == 1 ? 20 : 12); + var length = (ulong)(BinaryPrimitives.ReadUInt32BigEndian(data.AsSpan(at)) * seconds); + if (data[body] == 1) + { + BinaryPrimitives.WriteUInt64BigEndian(data.AsSpan(at + 4), length); + } + else + { + BinaryPrimitives.WriteUInt32BigEndian(data.AsSpan(at + 4), (uint)length); + } + + return data; + } + + /// A stream that cannot be read past a point, as a file on a share that went. + private sealed class FailingStream(byte[] data, long from, Exception? error = null) : MemoryStream(data) + { + public Action? OnRead { get; set; } + + // A MemoryStream that is extended reads spans through here too. + public override int Read(byte[] buffer, int offset, int count) + { + OnRead?.Invoke(); + return Position + count > from ? throw error ?? new IOException("rete") : base.Read(buffer, offset, count); + } } private static StillVideoResult Analyse(byte[] video)