E4: l'analisi non dice più «Fermo» di ciò che non ha visto

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 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-12-01 18:57:56 +01:00
1 parent 19119064f0
commit 9277e0a18c
6 files changed
+1008 -210

No files matched your search

+26 -4
View File
@@ -1,4 +1,5 @@
using System.Globalization; using System.Globalization;
using System.Text.RegularExpressions;
namespace Febe.Core.Export; 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 /// 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. /// a request asks for, the suffix a frame file gets, and how an instant is shown.
/// </summary> /// </summary>
public static class ExportFrames public static partial class ExportFrames
{ {
/// <summary>The shortest step of «Uno ogni k secondi».</summary> /// <summary>The shortest step of «Uno ogni k secondi».</summary>
public static readonly TimeSpan MinEvery = TimeSpan.FromMilliseconds(100); public static readonly TimeSpan MinEvery = TimeSpan.FromMilliseconds(100);
@@ -26,6 +27,16 @@ public static class ExportFrames
/// <summary>The suffix of the single frame of «Salva il fotogramma» (tappa E4).</summary> /// <summary>The suffix of the single frame of «Salva il fotogramma» (tappa E4).</summary>
public const string SingleSuffix = "_fotogramma"; public const string SingleSuffix = "_fotogramma";
/// <summary>
/// Whether the file of a frame copy has the name «Salva il fotogramma» gives (<see cref="SingleSuffix"/>, also with
/// « (2)» of a name already taken): the other ways end with <c>_t…</c> or <c>_f…</c>.
/// </summary>
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();
/// <summary>How many frames <paramref name="request"/> asks of a video of <paramref name="duration"/>.</summary> /// <summary>How many frames <paramref name="request"/> asks of a video of <paramref name="duration"/>.</summary>
public static long FrameCount(TimeSpan duration, ExportFramesRequest request) public static long FrameCount(TimeSpan duration, ExportFramesRequest request)
{ {
@@ -160,9 +171,20 @@ public static class ExportFrames
/// <summary>An instant rounded up to the whole millisecond (never before the instant computed).</summary> /// <summary>An instant rounded up to the whole millisecond (never before the instant computed).</summary>
private static TimeSpan WholeMs(TimeSpan at) => TimeSpan.FromMilliseconds(ActualMs(at)); private static TimeSpan WholeMs(TimeSpan at) => TimeSpan.FromMilliseconds(ActualMs(at));
/// <summary>The identity of a frame's instant: its shown time in milliseconds, rounded up.</summary> /// <summary>
public static long ActualMs(TimeSpan shown) => /// The identity of a frame's instant: its shown time in milliseconds, rounded up (a hostile time table reaches the
shown <= TimeSpan.Zero ? 0 : (shown.Ticks + TimeSpan.TicksPerMillisecond - 1) / TimeSpan.TicksPerMillisecond; /// end of what a TimeSpan holds: the whole milliseconds of it, then).
/// </summary>
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) private static long EveryCount(TimeSpan duration, TimeSpan step)
{ {
+533 -193
View File
@@ -1,4 +1,5 @@
using System.Buffers; using System.Buffers;
using System.Runtime.ExceptionServices;
using Febe.Core.Codecs.Containers; using Febe.Core.Codecs.Containers;
using Febe.Core.Codecs.Images; using Febe.Core.Codecs.Images;
using Febe.Core.Domain; using Febe.Core.Domain;
@@ -53,26 +54,35 @@ public sealed record StillVideoResult(
/// §4.10 «Video fermi», tappa E4, algorithm 1). Written in house on <see cref="VideoFrameReader"/>: exact frames at the /// §4.10 «Video fermi», tappa E4, algorithm 1). Written in house on <see cref="VideoFrameReader"/>: exact frames at the
/// shown times, edit lists included, upright. /// shown times, edit lists included, upright.
/// <list type="number"> /// <list type="number">
/// <item><see cref="Samples"/> frames, one near the centre of each of as many equal parts of the video (a key frame /// <item><see cref="Samples"/> frames spread over what the video track shows (not over the length the headers say), one
/// within a quarter of a part, which decodes alone, else the frame shown at the centre): never the very first or last /// in each of as many equal parts, at the uneven <see cref="Offsets"/> inside them: equal steps would fall on the same
/// frame, where fades and black frames sit. A video of one frame (or whose instants all fall on one) is that /// picture of a clip repeated over and over. Every other one may move to a key frame shown within a quarter of a part,
/// picture.</item> /// which decodes alone; the ones between are the frame shown at the instant, so that the pictures between key frames are
/// <item>Each frame is reduced to a grid of <see cref="GridSize"/> × <see cref="GridSize"/> blocks of mean luma and /// looked at too. Never the very first or last frame, where fades and black frames sit. A track of at most
/// chroma (BT.709); its sharpness is the variance of the Laplacian of its luma.</item> /// <see cref="Samples"/> pictures is looked at whole; when the instants fall on fewer pictures (some are held for long)
/// <item>A frame with no block as bright as <see cref="DarkLevel"/> in any colour is dark: dark frames at the start or /// others are added by their position.</item>
/// the end (a fade from or to black) are set aside; a dark frame between two that are not means the picture /// <item>Each frame is reduced to a grid of <see cref="GridSize"/> × <see cref="GridSize"/> blocks and to a finer one (of
/// changes.</item> /// up to <see cref="FineGridSize"/> cells a side, at least <see cref="FineCell"/> 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.</item>
/// <item>A frame with no block as bright as <see cref="DarkLevel"/> in any colour, and no detail as bright as
/// <see cref="BrightDetail"/>, 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.</item>
/// <item>A fade is undone before frames are compared: when the brightness ratios of the blocks agree (a fade scales /// <item>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.</item> /// 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.</item>
/// <item>The still picture is the median of the frames, block by block, so a part that moves does not belong to it. The /// <item>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 <see cref="MeanThreshold"/> (each block capped /// video is still when every frame differs from it by a mean of at most <see cref="MeanThreshold"/> (each block capped
/// at <see cref="BlockThreshold"/>) and the blocks that differ by more than <see cref="BlockThreshold"/> cover at most /// at <see cref="BlockThreshold"/>) and the blocks that differ by more than <see cref="BlockThreshold"/> cover at most
/// <see cref="AreaThreshold"/> of the picture: a small animated sticker or a moving caption leaves the video still /// <see cref="AreaThreshold"/> of the picture, on both grids (the finer one by its luma): a small animated sticker or a
/// (answer 47 of Alberto, 29 November 2026). While decoding, a pair of frames that differs over three times that area /// moving caption leaves the video still (answer 47 of Alberto, 29 November 2026), and snow or static, whose blocks
/// (a moving part changes the picture at its old and its new place, and the edges of the blocks add some) or by a /// average out, does not. While decoding, a pair of frames that differs over three times that area (a moving part
/// larger mean already says «In movimento», and the rest is not decoded.</item> /// changes the picture at its old and its new place, and the edges of the blocks add some) or by a larger mean already
/// <item>No frame that is not dark: «Non analizzabile» (<see cref="VideoAnalysisNotes.AllDark"/>); every one of a /// says «In movimento», and the rest is not decoded.</item>
/// single colour: «Non analizzabile» (<see cref="VideoAnalysisNotes.SingleColor"/>, answer 42).</item> /// <item>No frame that is not dark: «Non analizzabile» (<see cref="VideoAnalysisNotes.AllDark"/>); every one of the same
/// single colour: «Non analizzabile» (<see cref="VideoAnalysisNotes.SingleColor"/>, answer 42). A frame that should have
/// been looked at and gives no picture: «Non analizzabile» (<see cref="VideoAnalysisNotes.Unreadable"/>), unless the
/// others already show motion.</item>
/// </list> /// </list>
/// Any change to the rule or to the thresholds raises <see cref="Algorithm"/>. /// Any change to the rule or to the thresholds raises <see cref="Algorithm"/>.
/// </summary> /// </summary>
@@ -87,6 +97,18 @@ public static class StillVideoAnalyzer
/// <summary>Blocks of the grid on each side.</summary> /// <summary>Blocks of the grid on each side.</summary>
public const int GridSize = 32; public const int GridSize = 32;
/// <summary>Cells of the finer grid on each side, at most.</summary>
public const int FineGridSize = 128;
/// <summary>The smallest side of a cell of the finer grid, in pixels.</summary>
internal const int FineCell = 4;
/// <summary>
/// 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.
/// </summary>
internal static readonly double[] Offsets = [0.4173, 0.3611, 0.6237, 0.5, 0.6619, 0.3307, 0.5521];
/// <summary> /// <summary>
/// A frame none of whose blocks has a red, green or blue mean as bright as this (0–255) is dark: black or nearly /// 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. /// black.
@@ -112,31 +134,52 @@ public static class StillVideoAnalyzer
/// While decoding, a pair of frames differing over this many times <see cref="AreaThreshold"/> moves: a part of /// While decoding, a pair of frames differing over this many times <see cref="AreaThreshold"/> moves: a part of
/// that area changes it at its old and its new place, and the edges of the blocks add some. /// that area changes it at its old and its new place, and the edges of the blocks add some.
/// </summary> /// </summary>
private const double EarlyAreaFactor = 3; internal const double EarlyAreaFactor = 3;
/// <summary>Blocks darker than this in both frames do not take part in the estimate of a fade.</summary> /// <summary>Blocks darker than this in both frames do not take part in the estimate of a fade.</summary>
private const double GainFloor = 16; internal const double GainFloor = 16;
/// <summary>The largest spread (interquartile range of the natural logarithms) of block ratios read as a fade.</summary> /// <summary>The largest spread (interquartile range of the natural logarithms) of block ratios read as a fade.</summary>
private const double GainAgreement = 0.1; internal const double GainAgreement = 0.1;
/// <summary>The largest brightness ratio undone as a fade.</summary> /// <summary>The largest brightness ratio undone as a fade.</summary>
private const double GainRange = 8; internal const double GainRange = 8;
/// <summary>A gain this close to 1 is no fade: no block is left out for clipping.</summary> /// <summary>
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.
/// </summary>
internal const double ClippedShare = 0.1;
/// <summary>Blocks with more of their pixels clipped at white than this do not scale with a fade.</summary> /// <summary>A channel at least this bright (0–255) is taken as clipped at white.</summary>
private const double ClippedShare = 0.1; internal const int White = 250;
/// <summary>The weight of each chroma difference against the luma one.</summary> /// <summary>The weight of each chroma difference against the luma one.</summary>
private const double ChromaWeight = 0.25; internal const double ChromaWeight = 0.25;
/// <summary>A pixel with a channel at least this bright (0–255) is a detail that a dark frame does not have.</summary>
internal const int BrightDetail = 96;
/// <summary>The variance of the luma of the pixels from which a frame is not of a single colour.</summary>
internal const double UniformVariance = 64;
/// <summary>A pixel whose luma is further than this from the mean is a detail that a frame of a single colour does not have.</summary>
internal const double UniformDetail = 32;
/// <summary>The share of the pixels that may be such a detail in a dark frame or in one of a single colour.</summary>
internal const double DetailShare = 0.0002;
/// <summary>The latest instant a video may show (past it the time table is damaged or hostile).</summary>
internal static readonly TimeSpan LatestInstant = TimeSpan.FromSeconds(1e9);
/// <summary> /// <summary>
/// Analyses the video in <paramref name="seekable"/> (left open) in at most <paramref name="budget"/>: past it the /// Analyses the video in <paramref name="seekable"/> (left open) in at most <paramref name="budget"/>: past it the
/// result is «Non analizzabile» with <see cref="VideoAnalysisNotes.TooSlow"/> (a zero budget gives it at once). It /// result is «Non analizzabile» with <see cref="VideoAnalysisNotes.TooSlow"/> (a zero budget gives it at once). It
/// never throws for a video it cannot read; a cancellation of <paramref name="ct"/> 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 <paramref name="ct"/> stays a cancellation.
/// </summary> /// </summary>
/// <exception cref="IOException">The stream could not be read.</exception>
/// <exception cref="UnauthorizedAccessException">The stream could not be read.</exception>
public static StillVideoResult Analyse(Stream seekable, TimeSpan budget, CancellationToken ct) public static StillVideoResult Analyse(Stream seekable, TimeSpan budget, CancellationToken ct)
{ {
ArgumentNullException.ThrowIfNull(seekable); ArgumentNullException.ThrowIfNull(seekable);
@@ -150,14 +193,20 @@ public static class StillVideoAnalyzer
limit.CancelAfter(budget); 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 try
{ {
return Run(seekable, limit.Token); result = Run(watched, limit.Token);
} }
catch (OperationCanceledException) when (!ct.IsCancellationRequested) catch (OperationCanceledException) when (!ct.IsCancellationRequested)
{ {
return NotAnalyzable(VideoAnalysisNotes.TooSlow, 0, 0, false); result = NotAnalyzable(VideoAnalysisNotes.TooSlow, 0, 0, false);
} }
watched.Fault?.Throw();
return result;
} }
/// <summary>Analyses the video in <paramref name="seekable"/> with no limit but <paramref name="ct"/>.</summary> /// <summary>Analyses the video in <paramref name="seekable"/> with no limit but <paramref name="ct"/>.</summary>
@@ -165,7 +214,8 @@ public static class StillVideoAnalyzer
/// <summary> /// <summary>
/// Analyses the video file at <paramref name="path"/> on the thread pool, as <see cref="Analyse(Stream, TimeSpan, CancellationToken)"/>: /// Analyses the video file at <paramref name="path"/> on the thread pool, as <see cref="Analyse(Stream, TimeSpan, CancellationToken)"/>:
/// a file that cannot be opened is «Non analizzabile» (<see cref="VideoAnalysisNotes.Unreadable"/>). /// a file that cannot be opened is «Non analizzabile» (<see cref="VideoAnalysisNotes.Unreadable"/>); one that stops being
/// readable meanwhile throws.
/// </summary> /// </summary>
public static Task<StillVideoResult> AnalyseAsync(string path, TimeSpan budget, CancellationToken ct = default) public static Task<StillVideoResult> AnalyseAsync(string path, TimeSpan budget, CancellationToken ct = default)
{ {
@@ -194,66 +244,52 @@ public static class StillVideoAnalyzer
private static StillVideoResult Run(Stream stream, CancellationToken ct) private static StillVideoResult Run(Stream stream, CancellationToken ct)
{ {
ct.ThrowIfCancellationRequested(); ct.ThrowIfCancellationRequested();
using var reader = VideoFrameReader.Open(stream, out var info); using var reader = VideoFrameReader.Open(stream, out var info, ct);
if (!info.Available) 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 var targets = Targets(reader, shown);
? reader.LocateNearKey(ExportFrames.Spread(info.Duration, Samples), info.Duration / (4 * Samples))
: reader.Locate([TimeSpan.Zero]))
.DistinctBy(t => t.Sample)
.ToList();
var frames = new List<Signature>(targets.Count); var frames = new List<Signature>(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; return Moving(frames.Count, info, second.Mean, second.Area);
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);
} }
}
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)) if (frames.Count == expected && frames.Count(f => !f.Dark) == 1 && Around(shown, frames).Count > 1)
{ {
return NotAnalyzable(VideoAnalysisNotes.Unreadable, frames.Count, info.Rotation, info.HasAudio); 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. // 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)); frames.Sort((a, b) => a.Actual.CompareTo(b.Actual));
var complete = frames.Count == expected;
var first = frames.FindIndex(f => !f.Dark); var first = frames.FindIndex(f => !f.Dark);
if (first < 0) 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); var last = frames.FindLastIndex(f => !f.Dark);
@@ -263,15 +299,26 @@ public static class StillVideoAnalyzer
} }
var pictures = frames.Where(f => !f.Dark).ToList(); 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) if (difference > MeanThreshold || changed > AreaThreshold)
{ {
return Moving(frames.Count, info, difference, changed); 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. // 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)), 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)); Math.Round(difference, 2), Math.Round(changed, 4), Math.Round(chosen.Sharpness, 2));
} }
/// <summary>
/// The frames to look at among <paramref name="shown"/> (pictures in shown order): all of them when they are at most
/// <see cref="Samples"/>; otherwise one in each of as many equal parts of the time they cover, at the uneven
/// <see cref="Offsets"/>, every other one moved to a near key frame; then others by position when fewer than
/// <see cref="Samples"/> come out.
/// </summary>
private static List<VideoFrameTarget> Targets(VideoFrameReader reader, IReadOnlyList<VideoFrameTarget> 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<VideoFrameTarget>(Samples);
var taken = new HashSet<int>();
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;
}
/// <summary>The pictures shown between the dark frames nearest to the only one that is not dark.</summary>
private static List<VideoFrameTarget> Around(IReadOnlyList<VideoFrameTarget> shown, List<Signature> 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)];
}
/// <summary>
/// Decodes the targets and adds them to <paramref name="frames"/>: the difference of the first pair that moves, or
/// null when none does (or the stream is damaged: fewer frames than targets come out).
/// </summary>
private static (double Mean, double Area)? Look(VideoFrameReader reader, List<VideoFrameTarget> targets, List<Signature> 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) => private static StillVideoResult NotAnalyzable(string note, int sampled, int rotation, bool hasAudio) =>
new(VideoAnalysisOutcome.NotAnalyzable, null, note, sampled, rotation, hasAudio, 0, 0, 0); new(VideoAnalysisOutcome.NotAnalyzable, null, note, sampled, rotation, hasAudio, 0, 0, 0);
private static StillVideoResult Moving(int sampled, VideoFrameInfo info, double difference, double area) => 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); new(VideoAnalysisOutcome.Moving, null, null, sampled, info.Rotation, info.HasAudio, Math.Round(difference, 2), Math.Round(area, 4), 0);
/// <summary>The difference of two frames, after a fade between them is undone.</summary> /// <summary>Whether the pictures, each of a single colour, all show the same colour, fades undone on its largest channel.</summary>
private static bool SameColour(List<Signature> 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;
});
}
/// <summary>The difference of two frames on the blocks, after a fade between them is undone: the darker one against the brighter.</summary>
private static (double Mean, double Area) Compare(Signature a, Signature b) private static (double Mean, double Area) Compare(Signature a, Signature b)
{ {
var gain = Gain(a, 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);
} }
/// <summary> /// <summary>
/// The largest difference of a frame from the still picture: the median of the frames block by block, each frame /// The largest difference of a frame from the still picture, on the blocks and on the finer cells (luma only): the
/// first brought to the brightness of the brightest one. /// 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.
/// </summary> /// </summary>
private static (double Mean, double Area) AgainstStillPicture(List<Signature> pictures) private static (double Mean, double Area, bool Small) AgainstStillPicture(List<Signature> pictures)
{ {
if (pictures.Count < 2) if (pictures.Count < 2)
{ {
return (0, 0); return (0, 0, false);
} }
var reference = pictures.MaxBy(p => p.Luma.Sum())!; var reference = pictures.MaxBy(p => p.Luma.Sum())!;
var gains = pictures.Select(p => Gain(p, reference)).ToArray(); var gains = pictures.Select(p => Gain(p, reference)).ToArray();
var luma = new double[Signature.Blocks]; var (mean, area) = AgainstStillPicture([.. pictures.Select(p => p.Coarse)], gains, ChromaWeight);
var blue = new double[Signature.Blocks]; var (fineMean, fineArea) = pictures.All(p => p.Fine.Columns == reference.Fine.Columns && p.Fine.Rows == reference.Fine.Rows)
var red = new double[Signature.Blocks]; ? AgainstStillPicture([.. pictures.Select(p => p.Fine)], gains, 0)
var clipped = new double[Signature.Blocks]; : (0, 0); // a stream that changes size: the cells are not the same places
var values = new double[pictures.Count]; return (Math.Max(mean, fineMean), Math.Max(area, fineArea), area > 0 || fineArea >= 1.0 / Signature.Blocks);
for (var i = 0; i < Signature.Blocks; i++) }
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]); for (var i = 0; i < still.Count; i++)
blue[i] = Median(values, pictures, gains, p => p.BlueDifference[i]); {
red[i] = Median(values, pictures, gains, p => p.RedDifference[i]); // The lower median: with an even count the lower of the two middle values, so that of two frames neither
clipped[i] = pictures.Max(p => p.Clipped[i]); // 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 var lowest = gains.Min();
// not what the brightest frame shows.
var fade = gains.Any(IsFade);
double mean = 0, area = 0; 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); mean = Math.Max(mean, m);
area = Math.Max(area, a); area = Math.Max(area, a);
} }
@@ -343,74 +516,62 @@ public static class StillVideoAnalyzer
} }
/// <summary> /// <summary>
/// The lower median, block by block, of the pictures brought to the reference brightness: with an even count the /// The mean difference of the cells (each capped at <see cref="BlockThreshold"/>) and the fraction of them over it,
/// lower of the two middle values, so that of two frames neither is averaged away. /// between <paramref name="frame"/> and <paramref name="picture"/> brought to its brightness (<paramref name="gain"/>
/// 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
/// <paramref name="lowest"/>) has; that much of the difference does not count.
/// </summary> /// </summary>
private static double Median(double[] values, List<Signature> pictures, double[] gains, Func<Signature, double> 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++) var above = 255 * Math.Max(0, 1 - gain);
{ var below = 255 * Math.Max(0, (gain / lowest) - 1);
values[k] = value(pictures[k]) / gains[k]; var scale = 1 / Math.Max(1, gain);
}
Array.Sort(values);
return values[(values.Length - 1) / 2];
}
/// <summary>
/// The mean block difference (each capped at <see cref="BlockThreshold"/>) and the fraction of blocks over it between
/// frame <paramref name="a"/> and the blocks of <paramref name="lumaB"/>, where <paramref name="gain"/> is a's
/// brightness against them: the brighter side is scaled down. Under a <paramref name="fade"/>, blocks clipped at
/// white in either (<paramref name="clippedB"/>) are left out, unless that leaves fewer than half.
/// </summary>
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;
double sum = 0; double sum = 0;
var changed = 0; var changed = 0;
var compared = 0; for (var i = 0; i < frame.Count; i++)
for (var i = 0; i < Signature.Blocks; i++)
{ {
if (skip && (a.Clipped[i] > ClippedShare || clippedB[i] > ClippedShare)) var d = scale * Difference(Channel(0, i), Channel(1, i), Channel(2, i), chroma);
{
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]))));
if (d > BlockThreshold) if (d > BlockThreshold)
{ {
changed++; changed++;
} }
sum += Math.Min(d, BlockThreshold); 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; /// <summary>The difference of two colours: of luma, and of B − Y and R − Y by the weight <paramref name="chroma"/>.</summary>
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);
/// <summary> /// <summary>
/// The brightness of <paramref name="a"/> against <paramref name="b"/> when it is a fade of it: the median ratio of /// The brightness of <paramref name="a"/> against <paramref name="b"/> when it is a fade of it: the median ratio of
/// the blocks, provided the middle half of the ratios agree within <see cref="GainAgreement"/> (a different picture /// the blocks, provided the middle half of the ratios agree within <see cref="GainAgreement"/> (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.
/// </summary> /// </summary>
private static double Gain(Signature a, Signature b) private static double Gain(Signature a, Signature b)
{ {
var ratios = new List<double>(Signature.Blocks); var ratios = Ratios(a, b, clippedToo: false);
for (var i = 0; i < Signature.Blocks; i++) 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 ratios = Ratios(a, b, clippedToo: true);
&& a.Clipped[i] <= ClippedShare && b.Clipped[i] <= ClippedShare)
{
ratios.Add(Math.Log(a.Luma[i] / b.Luma[i]));
}
} }
if (ratios.Count < Signature.Blocks / 4) 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); : Math.Clamp(Math.Exp(ratios[ratios.Count / 2]), 1 / GainRange, GainRange);
} }
/// <summary>What is kept of a frame looked at: its grid of blocks, whether it is dark or of one colour, its sharpness.</summary> private static List<double> Ratios(Signature a, Signature b, bool clippedToo)
{
var ratios = new List<double>(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;
}
/// <summary>The picture in cells: for each channel the mean of the cell and the share of it clipped at white.</summary>
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;
/// <summary>The means of each cell, by channel: red, green and blue.</summary>
internal float[][] Mean { get; } = new float[Channels][];
/// <summary>The shares of each cell clipped at white, by channel.</summary>
internal float[][] Clipped { get; } = new float[Channels][];
/// <summary>
/// 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. <paramref name="clippedAny"/>, when given, gets the share of the
/// pixels of each cell with any channel clipped.
/// </summary>
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<byte> 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;
}
}
/// <summary>What is kept of a frame looked at: its grids, whether it is dark or of one colour, its sharpness.</summary>
private sealed class Signature private sealed class Signature
{ {
internal const int Blocks = GridSize * GridSize; internal const int Blocks = GridSize * GridSize;
/// <summary>A channel at least this bright is taken as clipped at white.</summary> private Signature(TimeSpan actual, Grid coarse, Grid fine, double[] clipped)
private const int White = 250;
private Signature(TimeSpan actual)
{ {
Actual = actual; (Actual, Coarse, Fine, Clipped) = (actual, coarse, fine, clipped);
} }
internal TimeSpan Actual { get; } internal TimeSpan Actual { get; }
internal Grid Coarse { get; }
internal Grid Fine { get; }
/// <summary>The luma of each block.</summary>
internal double[] Luma { get; } = new double[Blocks]; internal double[] Luma { get; } = new double[Blocks];
/// <summary>B − Y of each block.</summary>
internal double[] BlueDifference { get; } = new double[Blocks];
/// <summary>R − Y of each block.</summary>
internal double[] RedDifference { get; } = new double[Blocks];
/// <summary>The share of the pixels of each block with a channel clipped at white.</summary> /// <summary>The share of the pixels of each block with a channel clipped at white.</summary>
internal double[] Clipped { get; } = new double[Blocks]; internal double[] Clipped { get; }
/// <summary>The mean colour of the frame, and the largest of its channels.</summary>
internal (double R, double G, double B, double Largest) Colour { get; private set; }
internal bool Dark { get; private set; } internal bool Dark { get; private set; }
@@ -456,55 +712,68 @@ public static class StillVideoAnalyzer
internal double Sharpness { get; private set; } internal double Sharpness { get; private set; }
/// <summary> /// <summary>The signature of an upright RGBA frame.</summary>
/// 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.
/// </summary>
internal static Signature Of(RgbaImage image, TimeSpan actual) internal static Signature Of(RgbaImage image, TimeSpan actual)
{ {
var s = new Signature(actual);
var (w, h) = (image.Width, image.Height); var (w, h) = (image.Width, image.Height);
ReadOnlySpan<byte> pixels = image.Pixels; var clipped = new double[Blocks];
var stride = image.Stride; 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; var brightest = 0.0;
for (var gy = 0; gy < GridSize; gy++) for (var i = 0; i < Blocks; i++)
{ {
var y0 = gy * h / GridSize; double r = coarse.Mean[0][i], g = coarse.Mean[1][i], b = coarse.Mean[2][i];
var y1 = Math.Max(y0 + 1, (gy + 1) * h / GridSize); var luma = Bt709(r, g, b);
for (var gx = 0; gx < GridSize; gx++) (s.Luma[i], blue[i], red[i]) = (luma, b - luma, r - luma);
{ brightest = Math.Max(brightest, Math.Max(r, Math.Max(g, b)));
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 count = (long)(y1 - y0) * (x1 - x0); 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));
var (mr, mg, mb) = (r / count, g / count, b / count); s.Colour = (cr, cg, cb, Math.Max(cr, Math.Max(cg, cb)));
var luma = (0.2126 * mr) + (0.7152 * mg) + (0.0722 * mb); ReadOnlySpan<byte> pixels = image.Pixels;
var cell = (gy * GridSize) + gx; s.Dark = brightest < DarkLevel && !HasBrightDetail(pixels, w, h, image.Stride);
s.Luma[cell] = luma; s.Uniform = Spread(s.Luma) < UniformSpread && Spread(blue) < UniformSpread && Spread(red) < UniformSpread
s.BlueDifference[cell] = mb - luma; && !HasDetail(pixels, w, h, image.Stride, Bt709(cr, cg, cb));
s.RedDifference[cell] = mr - luma; s.Sharpness = LaplacianVariance(pixels, w, h, image.Stride);
s.Clipped[cell] = white / count; return s;
brightest = Math.Max(brightest, Math.Max(mr, Math.Max(mg, mb))); }
/// <summary>Whether some pixels are bright: a small text on black, lost in the means of the blocks.</summary>
private static bool HasBrightDetail(ReadOnlySpan<byte> 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; return bright > DetailShare * w * h;
s.Uniform = Spread(s.Luma) < UniformSpread && Spread(s.BlueDifference) < UniformSpread && Spread(s.RedDifference) < UniformSpread; }
s.Sharpness = LaplacianVariance(pixels, w, h, stride);
return s; /// <summary>Whether the pixels vary, though the blocks do not: a small text, a fine texture.</summary>
private static bool HasDetail(ReadOnlySpan<byte> 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) private static double Spread(double[] values)
@@ -566,4 +835,75 @@ public static class StillVideoAnalyzer
} }
} }
} }
/// <summary>
/// The stream, remembering the first error of its own: an <see cref="IOException"/> or an
/// <see cref="UnauthorizedAccessException"/> thrown by it, not the ones the readers raise above it for a file cut
/// short or damaged.
/// </summary>
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<byte> 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);
}
}
}
} }
+7 -5
View File
@@ -151,7 +151,7 @@ public sealed partial class VideoFrameDecoder
var target = SampleAt(video, at); var target = SampleAt(video, at);
// Too far from where decoding can start: the frame there stands for it, so the work stays bounded. // 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) if (target - start > maxRun)
{ {
target = start; 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 /// 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. /// pictures after it may refer to earlier ones); otherwise the exact start further back, or the first sample.
/// </summary> /// </summary>
internal int RunStart(int index) internal int RunStart(int index, CancellationToken ct)
{ {
if (exact) if (exact)
{ {
return ExactStart(index); return ExactStart(index, ct);
} }
var position = Array.BinarySearch(keys, index); var position = Array.BinarySearch(keys, index);
@@ -367,6 +367,7 @@ public sealed partial class VideoFrameDecoder
var candidate = keys[position]; var candidate = keys[position];
if (!accessPoints.TryGetValue(candidate, out var point)) if (!accessPoints.TryGetValue(candidate, out var point))
{ {
ct.ThrowIfCancellationRequested(); // each one reads a whole sample
point = AccessPointOf(candidate); point = AccessPointOf(candidate);
accessPoints[candidate] = point; accessPoints[candidate] = point;
} }
@@ -395,7 +396,7 @@ public sealed partial class VideoFrameDecoder
/// The nearest start from which <paramref name="index"/> comes out exact, however far: an IDR picture, or a /// The nearest start from which <paramref name="index"/> comes out exact, however far: an IDR picture, or a
/// recovery point shown no later than it; otherwise the first sample. /// recovery point shown no later than it; otherwise the first sample.
/// </summary> /// </summary>
private int ExactStart(int index) private int ExactStart(int index, CancellationToken ct)
{ {
var position = Array.BinarySearch(keys, index); var position = Array.BinarySearch(keys, index);
position = position >= 0 ? position : Math.Max(0, ~position - 1); position = position >= 0 ? position : Math.Max(0, ~position - 1);
@@ -405,6 +406,7 @@ public sealed partial class VideoFrameDecoder
var candidate = keys[position]; var candidate = keys[position];
if (!accessPoints.TryGetValue(candidate, out var point)) if (!accessPoints.TryGetValue(candidate, out var point))
{ {
ct.ThrowIfCancellationRequested(); // each one reads a whole sample
point = AccessPointOf(candidate); point = AccessPointOf(candidate);
accessPoints[candidate] = point; accessPoints[candidate] = point;
} }
@@ -477,7 +479,7 @@ public sealed partial class VideoFrameDecoder
var next = 0; var next = 0;
foreach (var target in targets) foreach (var target in targets)
{ {
var key = RunStart(target); var key = RunStart(target, ct);
if (runner is null || next > target || key >= next) if (runner is null || next > target || key >= next)
{ {
runner = null; runner = null;
+20 -3
View File
@@ -93,9 +93,10 @@ public sealed class VideoFrameReader : IDisposable
/// <summary> /// <summary>
/// Opens the video in <paramref name="seekable"/> (left open: the caller disposes it after the reader). Never /// Opens the video in <paramref name="seekable"/> (left open: the caller disposes it after the reader). Never
/// throws for a video it cannot read: <paramref name="info"/> is then not available, and the reader gives no frame. /// throws for a video it cannot read: <paramref name="info"/> is then not available, and the reader gives no frame. A
/// cancellation of <paramref name="ct"/> while the container is read is thrown.
/// </summary> /// </summary>
public static VideoFrameReader Open(Stream seekable, out VideoFrameInfo info) public static VideoFrameReader Open(Stream seekable, out VideoFrameInfo info, CancellationToken ct = default)
{ {
ArgumentNullException.ThrowIfNull(seekable); ArgumentNullException.ThrowIfNull(seekable);
MediaContainer? container; MediaContainer? container;
@@ -103,7 +104,7 @@ public sealed class VideoFrameReader : IDisposable
try try
{ {
seekable.Position = 0; 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); video = container is null ? null : VideoFrameDecoder.FrameTrack(container);
} }
catch (Exception ex) when (VideoFrameDecoder.IsUnreadableFile(ex)) catch (Exception ex) when (VideoFrameDecoder.IsUnreadableFile(ex))
@@ -164,6 +165,22 @@ public sealed class VideoFrameReader : IDisposable
return targets; return targets;
} }
/// <summary>
/// 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.
/// </summary>
internal IReadOnlyList<VideoFrameTarget> 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;
}
/// <summary> /// <summary>
/// As <see cref="Locate"/>, but each instant moves to the key sample (a sync sample: a frame decoding can start from) /// As <see cref="Locate"/>, 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 <paramref name="reach"/> of it (the earlier of two as near): a frame /// shown nearest to it, when one is shown within <paramref name="reach"/> of it (the earlier of two as near): a frame
@@ -41,6 +41,53 @@ internal static class PcmVideos
public static byte[] Mp4(int count, Func<int, H264PcmPicture> picture, int rotation = 0, bool audio = false) => public static byte[] Mp4(int count, Func<int, H264PcmPicture> picture, int rotation = 0, bool audio = false) =>
TestVideos.Mp4(Stream("pcm", count, picture), rotation: rotation, audio: audio); TestVideos.Mp4(Stream("pcm", count, picture), rotation: rotation, audio: audio);
/// <summary>
/// An MP4 of <paramref name="count"/> pictures of <paramref name="width"/> × <paramref name="height"/> (multiples of
/// 16), one a second: for what depends on the size of the picture.
/// </summary>
public static byte[] Large(int width, int height, int count, Func<int, H264PcmPicture> picture)
{
using var output = new MemoryStream();
H264PcmWriter.WriteMp4(output, width, height, count, 1, picture);
return output.ToArray();
}
/// <summary>A grey picture of any size (multiples of 16) whose luma at (x, y) is given, clamped to 16–235.</summary>
public static H264PcmPicture Grey(int width, int height, Func<int, int, double> 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;
}
/// <summary>A poster: one colour, and a photo on the bottom <paramref name="share"/> of it.</summary>
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;
}
/// <summary> /// <summary>
/// A photo-like picture: a diagonal gradient, a few coloured shapes and a fine texture (so it has detail to be sharp /// 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. /// with). Luma 16–235, chroma 16–240.
@@ -1,3 +1,4 @@
using System.Buffers.Binary;
using Febe.Core.Codecs.Containers; using Febe.Core.Codecs.Containers;
using Febe.Core.Codecs.H264; using Febe.Core.Codecs.H264;
using Febe.Core.Domain; using Febe.Core.Domain;
@@ -192,10 +193,20 @@ public sealed class StillVideoAnalyzerTests
Assert.AreEqual(VideoAnalysisOutcome.NotAnalyzable, single.Outcome, Describe(single)); Assert.AreEqual(VideoAnalysisOutcome.NotAnalyzable, single.Outcome, Describe(single));
Assert.AreEqual(VideoAnalysisNotes.SingleColor, single.Note); 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 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))); 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)); 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<int, double>[] { 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. // One colour after another: the picture changes.
var blue = PcmVideos.Flat(41, 240, 110); var blue = PcmVideos.Flat(41, 240, 110);
@@ -293,14 +304,36 @@ public sealed class StillVideoAnalyzerTests
Assert.AreEqual(VideoAnalysisOutcome.NotAnalyzable, vp9.Outcome); Assert.AreEqual(VideoAnalysisOutcome.NotAnalyzable, vp9.Outcome);
Assert.AreEqual(VideoAnalysisNotes.FrameNotAvailable, vp9.Note); 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)); 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]); var cut = Analyse(whole[..(whole.Length * tenths / 10)]);
Assert.AreNotEqual(VideoAnalysisOutcome.Moving, cut.Outcome, $"{length}: {Describe(cut)}"); 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"); using var temp = new TempFolder("fermo-illeggibile");
var missing = await StillVideoAnalyzer.AnalyseAsync(temp.Combine("non-esiste.mp4"), TimeSpan.FromSeconds(30)); var missing = await StillVideoAnalyzer.AnalyseAsync(temp.Combine("non-esiste.mp4"), TimeSpan.FromSeconds(30));
Assert.AreEqual(VideoAnalysisNotes.Unreadable, missing.Note); 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), (1, 7, 32, 32.0, 2.0, 12.0, 3.0, 0.05),
(StillVideoAnalyzer.Algorithm, StillVideoAnalyzer.Samples, StillVideoAnalyzer.GridSize, StillVideoAnalyzer.DarkLevel, (StillVideoAnalyzer.Algorithm, StillVideoAnalyzer.Samples, StillVideoAnalyzer.GridSize, StillVideoAnalyzer.DarkLevel,
StillVideoAnalyzer.UniformSpread, StillVideoAnalyzer.BlockThreshold, StillVideoAnalyzer.MeanThreshold, StillVideoAnalyzer.AreaThreshold)); 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<int, int, int, bool> 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<int, H264PcmPicture>)[]
{
("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<IOException>(() => StillVideoAnalyzer.Analyse(failing, CancellationToken.None), $"{from}");
Assert.AreEqual("rete", error.Message);
using var denied = new FailingStream(data, from, new UnauthorizedAccessException("negato"));
Assert.ThrowsExactly<UnauthorizedAccessException>(() => 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<OperationCanceledException>(() => 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<OperationCanceledException>(() => 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)));
}
/// <summary>An MP4 of pictures held for as long as each says, in seconds.</summary>
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();
}
/// <summary>The MP4 with the length its movie header says replaced.</summary>
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;
}
/// <summary>A stream that cannot be read past a point, as a file on a share that went.</summary>
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) private static StillVideoResult Analyse(byte[] video)