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:
1 parent
19119064f0
commit
9277e0a18c
6 files changed
+1008
-210
No files matched your search
@@ -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 <see cref="VideoFrameReader"/>: exact frames at the
|
||||
/// shown times, edit lists included, upright.
|
||||
/// <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
|
||||
/// 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.</item>
|
||||
/// <item>Each frame is reduced to a grid of <see cref="GridSize"/> × <see cref="GridSize"/> blocks of mean luma and
|
||||
/// chroma (BT.709); 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 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.</item>
|
||||
/// <item><see cref="Samples"/> 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 <see cref="Offsets"/> 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
|
||||
/// <see cref="Samples"/> pictures is looked at whole; when the instants fall on fewer pictures (some are held for long)
|
||||
/// others are added by their position.</item>
|
||||
/// <item>Each frame is reduced to a grid of <see cref="GridSize"/> × <see cref="GridSize"/> blocks and to a finer one (of
|
||||
/// 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
|
||||
/// 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
|
||||
/// 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
|
||||
/// <see cref="AreaThreshold"/> 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.</item>
|
||||
/// <item>No frame that is not dark: «Non analizzabile» (<see cref="VideoAnalysisNotes.AllDark"/>); every one of a
|
||||
/// single colour: «Non analizzabile» (<see cref="VideoAnalysisNotes.SingleColor"/>, answer 42).</item>
|
||||
/// <see cref="AreaThreshold"/> 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.</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>
|
||||
/// Any change to the rule or to the thresholds raises <see cref="Algorithm"/>.
|
||||
/// </summary>
|
||||
@@ -87,6 +97,18 @@ public static class StillVideoAnalyzer
|
||||
/// <summary>Blocks of the grid on each side.</summary>
|
||||
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>
|
||||
/// 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 <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.
|
||||
/// </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>
|
||||
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>
|
||||
private const double GainAgreement = 0.1;
|
||||
internal const double GainAgreement = 0.1;
|
||||
|
||||
/// <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>
|
||||
private const double GainTolerance = 0.02;
|
||||
/// <summary>
|
||||
/// 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>
|
||||
private const double ClippedShare = 0.1;
|
||||
/// <summary>A channel at least this bright (0–255) is taken as clipped at white.</summary>
|
||||
internal const int White = 250;
|
||||
|
||||
/// <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>
|
||||
/// 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
|
||||
/// 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>
|
||||
/// <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)
|
||||
{
|
||||
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;
|
||||
}
|
||||
|
||||
/// <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>
|
||||
/// 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>
|
||||
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)
|
||||
{
|
||||
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<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;
|
||||
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));
|
||||
}
|
||||
|
||||
/// <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) =>
|
||||
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);
|
||||
|
||||
/// <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)
|
||||
{
|
||||
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>
|
||||
/// 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.
|
||||
/// </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)
|
||||
{
|
||||
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
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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 <see cref="BlockThreshold"/>) and the fraction of them over it,
|
||||
/// 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>
|
||||
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++)
|
||||
{
|
||||
values[k] = value(pictures[k]) / gains[k];
|
||||
}
|
||||
|
||||
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;
|
||||
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;
|
||||
/// <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>
|
||||
/// 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
|
||||
/// 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>
|
||||
private static double Gain(Signature a, Signature b)
|
||||
{
|
||||
var ratios = new List<double>(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);
|
||||
}
|
||||
|
||||
/// <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
|
||||
{
|
||||
internal const int Blocks = GridSize * GridSize;
|
||||
|
||||
/// <summary>A channel at least this bright is taken as clipped at white.</summary>
|
||||
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; }
|
||||
|
||||
/// <summary>The luma of each block.</summary>
|
||||
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>
|
||||
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; }
|
||||
|
||||
@@ -456,55 +712,68 @@ public static class StillVideoAnalyzer
|
||||
|
||||
internal double Sharpness { get; private set; }
|
||||
|
||||
/// <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>
|
||||
/// <summary>The signature of an upright RGBA frame.</summary>
|
||||
internal static Signature Of(RgbaImage image, TimeSpan actual)
|
||||
{
|
||||
var s = new Signature(actual);
|
||||
var (w, h) = (image.Width, image.Height);
|
||||
ReadOnlySpan<byte> 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<byte> 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;
|
||||
}
|
||||
|
||||
/// <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;
|
||||
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;
|
||||
}
|
||||
|
||||
/// <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)
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user