E4: analizzatore dei video fermi scritto in casa (algoritmo 1)
StillVideoAnalyzer sostituisce VideoFrameDecoder.AnalyseStillness, che confrontava solo con il primo fotogramma (una dissolvenza dal nero risultava in movimento) e diluiva un adesivo nella media. - Sette fotogrammi esatti, uno per settimo del video, spostati sul fotogramma chiave vicino (VideoFrameReader.LocateNearKey, nuovo). - Griglia 32x32 di blocchi; dissolvenze annullate quando i rapporti dei blocchi concordano; fotogrammi neri messi da parte solo all'inizio o alla fine. - Fermo se ogni fotogramma differisce dall'immagine ferma mediana per una media di al massimo 3 e per non più del 5 % dei blocchi (risposta 47: un piccolo adesivo o una scritta che si muove restano fermi; nota SmallMotion). - Tutto nero o di un solo colore: Non analizzabile (risposta 42); anche codec non decodificato, file illeggibile, tempo oltre il limite. - Il fotogramma scelto è il più nitido (varianza del laplaciano), mai uno scuro, con l'istante in millisecondi come le copie dei fotogrammi. Prove su video costruiti dalle prove (PcmVideos) e sui flussi di conformità; le prove della vecchia analisi sono spostate qui. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
0cd842a518
commit
e61da9be23
10 files changed
+1231
-227
No files matched your search
@@ -0,0 +1,569 @@
|
||||
using System.Buffers;
|
||||
using Febe.Core.Codecs.Containers;
|
||||
using Febe.Core.Codecs.Images;
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Core.Export;
|
||||
|
||||
namespace Febe.Core.Library;
|
||||
|
||||
/// <summary>What <see cref="StillVideoAnalyzer"/> found about a video (spec §4.10 «È un video fermo?», tappa E4).</summary>
|
||||
/// <param name="Outcome">«Fermo», «In movimento» or «Non analizzabile».</param>
|
||||
/// <param name="FrameAt">
|
||||
/// For <see cref="VideoAnalysisOutcome.Still"/> only: the shown instant, in whole milliseconds rounded up as the frame
|
||||
/// copies name them (<see cref="ExportFrames.ActualMs"/>), of the sharpest frame looked at that is not dark: the frame
|
||||
/// «Salva il fotogramma» saves.
|
||||
/// </param>
|
||||
/// <param name="Note">
|
||||
/// Codes of <see cref="VideoAnalysisNotes"/>: why the video is not analysable (always set then), or
|
||||
/// <see cref="VideoAnalysisNotes.SmallMotion"/> on a still video where a small part moves; null otherwise.
|
||||
/// </param>
|
||||
/// <param name="Sampled">Frames decoded and looked at.</param>
|
||||
/// <param name="Rotation">Clockwise rotation of the track (0, 90, 180, 270): the frames looked at are already upright.</param>
|
||||
/// <param name="HasAudio">Whether the container has an audio track (the saved frame never has it).</param>
|
||||
/// <param name="Difference">
|
||||
/// The largest mean block difference, 0–255, each block capped at <see cref="StillVideoAnalyzer.BlockThreshold"/>: of a
|
||||
/// frame from the still picture, or of the pair that showed the motion.
|
||||
/// </param>
|
||||
/// <param name="MovingArea">The largest fraction (0–1) of the picture that changed beyond the local threshold, likewise.</param>
|
||||
/// <param name="Sharpness">The sharpness of the chosen frame: the variance of the Laplacian of its luma (0 without one).</param>
|
||||
public sealed record StillVideoResult(
|
||||
VideoAnalysisOutcome Outcome,
|
||||
TimeSpan? FrameAt,
|
||||
string? Note,
|
||||
int Sampled,
|
||||
int Rotation,
|
||||
bool HasAudio,
|
||||
double Difference,
|
||||
double MovingArea,
|
||||
double Sharpness)
|
||||
{
|
||||
/// <summary>The algorithm that gave the result: <see cref="StillVideoAnalyzer.Algorithm"/>.</summary>
|
||||
public int Algorithm => StillVideoAnalyzer.Algorithm;
|
||||
|
||||
/// <summary><see cref="FrameAt"/> in milliseconds.</summary>
|
||||
public long? FrameAtMs => FrameAt is { } at ? (long)at.TotalMilliseconds : null;
|
||||
|
||||
/// <summary>The row of <c>video_analysis</c> for the file of <paramref name="sha256"/>, analysed at <paramref name="analyzedAt"/>.</summary>
|
||||
public VideoAnalysis ToAnalysis(string sha256, DateTimeOffset analyzedAt) =>
|
||||
new(sha256, Algorithm, Outcome, analyzedAt, FrameAt, Note);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Whether a video only shows one picture (a photo with music, for example), so that one frame stands for it (spec
|
||||
/// §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>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>
|
||||
/// <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>
|
||||
/// </list>
|
||||
/// Any change to the rule or to the thresholds raises <see cref="Algorithm"/>.
|
||||
/// </summary>
|
||||
public static class StillVideoAnalyzer
|
||||
{
|
||||
/// <summary>The algorithm number stored with each result (<c>video_analysis.algorithm</c>).</summary>
|
||||
public const int Algorithm = 1;
|
||||
|
||||
/// <summary>Frames looked at.</summary>
|
||||
public const int Samples = 7;
|
||||
|
||||
/// <summary>Blocks of the grid on each side.</summary>
|
||||
public const int GridSize = 32;
|
||||
|
||||
/// <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.
|
||||
/// </summary>
|
||||
public const double DarkLevel = 32;
|
||||
|
||||
/// <summary>
|
||||
/// A frame whose blocks spread less than this (standard deviation of luma and of each chroma difference, 0–255) is
|
||||
/// of a single colour.
|
||||
/// </summary>
|
||||
public const double UniformSpread = 2;
|
||||
|
||||
/// <summary>The local threshold: a block whose difference is larger has changed (0–255).</summary>
|
||||
public const double BlockThreshold = 12;
|
||||
|
||||
/// <summary>The largest mean block difference from the still picture (0–255), each block capped at <see cref="BlockThreshold"/>.</summary>
|
||||
public const double MeanThreshold = 3;
|
||||
|
||||
/// <summary>The largest fraction of the picture that may change in a still video (answer 47).</summary>
|
||||
public const double AreaThreshold = 0.05;
|
||||
|
||||
/// <summary>
|
||||
/// 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;
|
||||
|
||||
/// <summary>Blocks darker than this in both frames do not take part in the estimate of a fade.</summary>
|
||||
private 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;
|
||||
|
||||
/// <summary>The largest brightness ratio undone as a fade.</summary>
|
||||
private 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 scale with a fade.</summary>
|
||||
private const double ClippedShare = 0.1;
|
||||
|
||||
/// <summary>The weight of each chroma difference against the luma one.</summary>
|
||||
private const double ChromaWeight = 0.25;
|
||||
|
||||
/// <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.
|
||||
/// </summary>
|
||||
public static StillVideoResult Analyse(Stream seekable, TimeSpan budget, CancellationToken ct)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(seekable);
|
||||
using var limit = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
||||
if (budget <= TimeSpan.Zero)
|
||||
{
|
||||
limit.Cancel();
|
||||
}
|
||||
else if (budget < TimeSpan.FromDays(1))
|
||||
{
|
||||
limit.CancelAfter(budget);
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
return Run(seekable, limit.Token);
|
||||
}
|
||||
catch (OperationCanceledException) when (!ct.IsCancellationRequested)
|
||||
{
|
||||
return NotAnalyzable(VideoAnalysisNotes.TooSlow, 0, 0, false);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Analyses the video in <paramref name="seekable"/> with no limit but <paramref name="ct"/>.</summary>
|
||||
public static StillVideoResult Analyse(Stream seekable, CancellationToken ct) => Analyse(seekable, TimeSpan.MaxValue, ct);
|
||||
|
||||
/// <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"/>).
|
||||
/// </summary>
|
||||
public static Task<StillVideoResult> AnalyseAsync(string path, TimeSpan budget, CancellationToken ct = default)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(path);
|
||||
return Task.Run(
|
||||
() =>
|
||||
{
|
||||
FileStream stream;
|
||||
try
|
||||
{
|
||||
stream = ContainerReader.OpenRead(path);
|
||||
}
|
||||
catch (Exception ex) when (VideoFrameDecoder.IsUnreadableFile(ex))
|
||||
{
|
||||
return NotAnalyzable(VideoAnalysisNotes.Unreadable, 0, 0, false);
|
||||
}
|
||||
|
||||
using (stream)
|
||||
{
|
||||
return Analyse(stream, budget, ct);
|
||||
}
|
||||
},
|
||||
ct);
|
||||
}
|
||||
|
||||
private static StillVideoResult Run(Stream stream, CancellationToken ct)
|
||||
{
|
||||
ct.ThrowIfCancellationRequested();
|
||||
using var reader = VideoFrameReader.Open(stream, out var info);
|
||||
if (!info.Available)
|
||||
{
|
||||
return NotAnalyzable(VideoAnalysisNotes.FrameNotAvailable, 0, info.Rotation, info.HasAudio);
|
||||
}
|
||||
|
||||
if (info.SampleCount > 1 && info.Duration <= TimeSpan.Zero)
|
||||
{
|
||||
return NotAnalyzable(VideoAnalysisNotes.DurationUnknown, 0, info.Rotation, info.HasAudio);
|
||||
}
|
||||
|
||||
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 frames = new List<Signature>(targets.Count);
|
||||
try
|
||||
{
|
||||
foreach (var frame in reader.Decode(targets, ct))
|
||||
{
|
||||
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);
|
||||
}
|
||||
}
|
||||
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);
|
||||
}
|
||||
|
||||
// In the order they are shown: dark frames only at the start or the end (a fade), never between two pictures.
|
||||
frames.Sort((a, b) => a.Actual.CompareTo(b.Actual));
|
||||
var first = frames.FindIndex(f => !f.Dark);
|
||||
if (first < 0)
|
||||
{
|
||||
return NotAnalyzable(VideoAnalysisNotes.AllDark, frames.Count, info.Rotation, info.HasAudio);
|
||||
}
|
||||
|
||||
var last = frames.FindLastIndex(f => !f.Dark);
|
||||
if (frames.Skip(first).Take(last - first + 1).Any(f => f.Dark))
|
||||
{
|
||||
return Moving(frames.Count, info, 0, 0);
|
||||
}
|
||||
|
||||
var pictures = frames.Where(f => !f.Dark).ToList();
|
||||
var (difference, changed) = AgainstStillPicture(pictures);
|
||||
if (difference > MeanThreshold || changed > AreaThreshold)
|
||||
{
|
||||
return Moving(frames.Count, info, difference, changed);
|
||||
}
|
||||
|
||||
if (pictures.All(f => f.Uniform))
|
||||
{
|
||||
return NotAnalyzable(VideoAnalysisNotes.SingleColor, frames.Count, info.Rotation, info.HasAudio);
|
||||
}
|
||||
|
||||
// The sharpest picture (the first shown of equally sharp ones): never a dark frame, nor one dimmed by a fade.
|
||||
var chosen = pictures[0];
|
||||
foreach (var f in pictures.Skip(1))
|
||||
{
|
||||
if (f.Sharpness > chosen.Sharpness)
|
||||
{
|
||||
chosen = f;
|
||||
}
|
||||
}
|
||||
|
||||
return new StillVideoResult(VideoAnalysisOutcome.Still, TimeSpan.FromMilliseconds(ExportFrames.ActualMs(chosen.Actual)),
|
||||
changed > 0 ? VideoAnalysisNotes.SmallMotion : null, frames.Count, info.Rotation, info.HasAudio,
|
||||
Math.Round(difference, 2), Math.Round(changed, 4), Math.Round(chosen.Sharpness, 2));
|
||||
}
|
||||
|
||||
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>
|
||||
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));
|
||||
}
|
||||
|
||||
/// <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.
|
||||
/// </summary>
|
||||
private static (double Mean, double Area) AgainstStillPicture(List<Signature> pictures)
|
||||
{
|
||||
if (pictures.Count < 2)
|
||||
{
|
||||
return (0, 0);
|
||||
}
|
||||
|
||||
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++)
|
||||
{
|
||||
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]);
|
||||
}
|
||||
|
||||
// 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);
|
||||
double mean = 0, area = 0;
|
||||
for (var k = 0; k < pictures.Count; k++)
|
||||
{
|
||||
var (m, a) = Measure(pictures[k], luma, blue, red, gains[k], clipped, fade);
|
||||
mean = Math.Max(mean, m);
|
||||
area = Math.Max(area, a);
|
||||
}
|
||||
|
||||
return (mean, area);
|
||||
}
|
||||
|
||||
/// <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.
|
||||
/// </summary>
|
||||
private static double Median(double[] values, List<Signature> pictures, double[] gains, Func<Signature, double> value)
|
||||
{
|
||||
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;
|
||||
double sum = 0;
|
||||
var changed = 0;
|
||||
var compared = 0;
|
||||
for (var i = 0; i < Signature.Blocks; 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]))));
|
||||
if (d > BlockThreshold)
|
||||
{
|
||||
changed++;
|
||||
}
|
||||
|
||||
sum += Math.Min(d, BlockThreshold);
|
||||
compared++;
|
||||
}
|
||||
|
||||
return (sum / compared, (double)changed / compared);
|
||||
}
|
||||
|
||||
private static bool IsFade(double gain) => Math.Abs(gain - 1) > GainTolerance;
|
||||
|
||||
/// <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.
|
||||
/// </summary>
|
||||
private static double Gain(Signature a, Signature b)
|
||||
{
|
||||
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
|
||||
&& a.Clipped[i] <= ClippedShare && b.Clipped[i] <= ClippedShare)
|
||||
{
|
||||
ratios.Add(Math.Log(a.Luma[i] / b.Luma[i]));
|
||||
}
|
||||
}
|
||||
|
||||
if (ratios.Count < Signature.Blocks / 4)
|
||||
{
|
||||
return 1;
|
||||
}
|
||||
|
||||
ratios.Sort();
|
||||
return ratios[3 * ratios.Count / 4] - ratios[ratios.Count / 4] > GainAgreement
|
||||
? 1
|
||||
: 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 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)
|
||||
{
|
||||
Actual = actual;
|
||||
}
|
||||
|
||||
internal TimeSpan Actual { get; }
|
||||
|
||||
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 bool Dark { get; private set; }
|
||||
|
||||
internal bool Uniform { get; private set; }
|
||||
|
||||
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>
|
||||
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 brightest = 0.0;
|
||||
for (var gy = 0; gy < GridSize; gy++)
|
||||
{
|
||||
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 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)));
|
||||
}
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
private static double Spread(double[] values)
|
||||
{
|
||||
var mean = values.Average();
|
||||
var sum = 0.0;
|
||||
foreach (var v in values)
|
||||
{
|
||||
sum += (v - mean) * (v - mean);
|
||||
}
|
||||
|
||||
return Math.Sqrt(sum / values.Length);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The variance of the 4-neighbour Laplacian of the luma over the inner pixels: larger for a sharper picture,
|
||||
/// smaller for one blurred by the compression or dimmed by a fade (0 for a frame under 3 × 3 pixels).
|
||||
/// </summary>
|
||||
private static double LaplacianVariance(ReadOnlySpan<byte> pixels, int w, int h, int stride)
|
||||
{
|
||||
if (w < 3 || h < 3)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
var luma = ArrayPool<byte>.Shared.Rent(w * h);
|
||||
try
|
||||
{
|
||||
for (var y = 0; y < h; y++)
|
||||
{
|
||||
var row = pixels.Slice(y * stride, w * RgbaImage.BytesPerPixel);
|
||||
for (var x = 0; x < w; x++)
|
||||
{
|
||||
var p = x * RgbaImage.BytesPerPixel;
|
||||
luma[(y * w) + x] = (byte)(((54 * row[p]) + (183 * row[p + 1]) + (19 * row[p + 2]) + 128) >> 8);
|
||||
}
|
||||
}
|
||||
|
||||
double sum = 0, squares = 0;
|
||||
for (var y = 1; y < h - 1; y++)
|
||||
{
|
||||
var at = y * w;
|
||||
for (var x = 1; x < w - 1; x++)
|
||||
{
|
||||
var i = at + x;
|
||||
double lap = (4 * luma[i]) - luma[i - 1] - luma[i + 1] - luma[i - w] - luma[i + w];
|
||||
sum += lap;
|
||||
squares += lap * lap;
|
||||
}
|
||||
}
|
||||
|
||||
var n = (double)(w - 2) * (h - 2);
|
||||
var mean = sum / n;
|
||||
return Math.Max(0, (squares / n) - (mean * mean));
|
||||
}
|
||||
finally
|
||||
{
|
||||
ArrayPool<byte>.Shared.Return(luma);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user