using System.Buffers;
using System.Runtime.ExceptionServices;
using Febe.Core.Codecs.Containers;
using Febe.Core.Codecs.Images;
using Febe.Core.Domain;
using Febe.Core.Export;
namespace Febe.Core.Library;
/// What found about a video (spec §4.10 «È un video fermo?», tappa E4).
/// «Fermo», «In movimento» or «Non analizzabile».
///
/// For only: the shown instant, in whole milliseconds rounded up as the frame
/// copies name them (), of the sharpest frame looked at that is not dark: the frame
/// «Salva il fotogramma» saves.
///
///
/// Codes of : why the video is not analysable (always set then), or
/// on a still video where a small part moves; null otherwise.
///
/// Frames decoded and looked at.
/// Clockwise rotation of the track (0, 90, 180, 270): the frames looked at are already upright.
/// Whether the container has an audio track (the saved frame never has it).
///
/// The largest mean block difference, 0–255, each block capped at : of a
/// frame from the still picture, or of the pair that showed the motion.
///
/// The largest fraction (0–1) of the picture that changed beyond the local threshold, likewise.
/// The sharpness of the chosen frame: the variance of the Laplacian of its luma (0 without one).
public sealed record StillVideoResult(
VideoAnalysisOutcome Outcome,
TimeSpan? FrameAt,
string? Note,
int Sampled,
int Rotation,
bool HasAudio,
double Difference,
double MovingArea,
double Sharpness)
{
/// The algorithm that gave the result: .
public int Algorithm => StillVideoAnalyzer.Algorithm;
/// in milliseconds.
public long? FrameAtMs => FrameAt is { } at ? (long)at.TotalMilliseconds : null;
/// The row of video_analysis for the file of , analysed at .
public VideoAnalysis ToAnalysis(string sha256, DateTimeOffset analyzedAt) =>
new(sha256, Algorithm, Outcome, analyzedAt, FrameAt, Note);
}
///
/// 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 : exact frames at the
/// shown times, edit lists included, upright.
///
/// - frames spread over what the video track shows (not over the length the headers say), one
/// in each of as many equal parts, at the uneven inside them: equal steps would fall on the same
/// picture of a clip repeated over and over. Every other one may move to a key frame shown within a quarter of a part,
/// which decodes alone; the ones between are the frame shown at the instant, so that the pictures between key frames are
/// looked at too. Never the very first or last frame, where fades and black frames sit. A track of at most
/// pictures is looked at whole; when the instants fall on fewer pictures (some are held for long)
/// others are added by their position.
/// - Each frame is reduced to a grid of × blocks and to a finer one (of
/// up to cells a side, at least pixels each), with the mean of each
/// channel and the share of it clipped at white; its sharpness is the variance of the Laplacian of its luma.
/// - A frame with no block as bright as in any colour, and no detail as bright as
/// , is dark: dark frames at the start or the end (a fade from or to black) are set aside; a
/// dark frame between two that are not is compared like any other (a dim picture whose grain crosses the threshold is
/// still; black between two pictures is not), and is never the one chosen. A single frame that is not dark says nothing
/// of the video: more are then looked at between the dark ones around it.
/// - A fade is undone before frames are compared: when the brightness ratios of the blocks agree (a fade scales
/// them all alike), each counted by its light so that a card on black or a dark photo tells its fade too, the picture is
/// scaled to the frame's brightness; what clipping at white may hide is bounded, channel by channel, and never taken for
/// a change.
/// - The still picture is the median of the frames, block by block, so a part that moves does not belong to it. The
/// video is still when every frame differs from it by a mean of at most (each block capped
/// at ) and the blocks that differ by more than cover at most
/// of the picture, on both grids (the finer one by its luma): a small animated sticker or a
/// moving caption leaves the video still (answer 47 of Alberto, 29 November 2026), and snow or static, whose blocks
/// average out, does not. While decoding, a pair of frames that differs over three times that area (a moving part
/// changes the picture at its old and its new place, and the edges of the blocks add some) or by a larger mean already
/// says «In movimento», and the rest is not decoded.
/// - No frame that is not dark: «Non analizzabile» (); every one of the same
/// single colour: «Non analizzabile» (, answer 42). A frame that should have
/// been looked at and gives no picture: «Non analizzabile» (), unless the
/// others already show motion.
///
/// Any change to the rule or to the thresholds raises .
///
public static class StillVideoAnalyzer
{
/// The algorithm number stored with each result (video_analysis.algorithm).
public const int Algorithm = 1;
/// Frames looked at.
public const int Samples = 7;
/// Blocks of the grid on each side.
public const int GridSize = 32;
/// Cells of the finer grid on each side, at most.
public const int FineGridSize = 128;
/// The smallest side of a cell of the finer grid, in pixels.
internal const int FineCell = 4;
///
/// Where each frame looked at sits inside its part of the video (0–1): the first and the last far from the ends, the
/// others uneven (found by a search), so that for a clip repeated 2 to 40 times, also not a whole number, the seven
/// frames never fall within less than 48 % of it. A picture shown for less than half of the clip can still be missed.
///
internal static readonly double[] Offsets = [0.54, 0.865, 0.417, 0.253, 0.432, 0.45, 0.46];
///
/// 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.
///
public const double DarkLevel = 32;
///
/// A frame whose blocks spread less than this (standard deviation of luma and of each chroma difference, 0–255) is
/// of a single colour.
///
public const double UniformSpread = 2;
/// The local threshold: a block whose difference is larger has changed (0–255).
public const double BlockThreshold = 12;
/// The largest mean block difference from the still picture (0–255), each block capped at .
public const double MeanThreshold = 3;
/// The largest fraction of the picture that may change in a still video (answer 47).
public const double AreaThreshold = 0.05;
///
/// While decoding, a pair of frames differing over this many times moves: a part of
/// that area changes it at its old and its new place, and the edges of the blocks add some.
///
internal const double EarlyAreaFactor = 3;
/// Blocks darker than this (their largest channel) in both frames do not take part in the estimate of a fade.
internal const double GainFloor = 8;
/// The fewest blocks that can tell a fade.
internal const int GainBlocks = 10;
/// A block this near (0–255) to what the fade makes of it follows it: the rounding of a dim frame.
internal const double GainNoise = 1.5;
/// The width of the band, as a share of the ratio, in which the blocks holding half of the light must be for it to be a fade.
internal const double GainAgreement = 0.1;
/// The largest brightness ratio undone as a fade.
internal const double GainRange = 16;
///
/// A channel of a block with more of its pixels clipped at white than this does not take part in the estimate of a
/// fade, unless the others tell none.
///
internal const double ClippedShare = 0.1;
/// A channel at least this bright (0–255) is taken as clipped at white.
internal const int White = 250;
/// The weight of each chroma difference against the luma one.
internal const double ChromaWeight = 0.25;
/// A pixel with a channel at least this bright (0–255) is a detail that a dark frame does not have.
internal const int BrightDetail = 96;
/// The variance of the luma of the pixels from which a frame is not of a single colour.
internal const double UniformVariance = 64;
/// A pixel whose luma is further than this from the mean is a detail that a frame of a single colour does not have.
internal const double UniformDetail = 32;
/// The share of the pixels that may be such a detail in a dark frame or in one of a single colour.
internal const double DetailShare = 0.0002;
/// The latest instant a video may show (past it the time table is damaged or hostile).
internal static readonly TimeSpan LatestInstant = TimeSpan.FromSeconds(1e9);
///
/// Analyses the video in (left open) in at most : past it the
/// result is «Non analizzabile» with (a zero budget gives it at once). It
/// never throws for a video it cannot read, but an error of the stream itself (a disk or a share that went) is thrown:
/// it says nothing of the video. A cancellation of stays a cancellation.
///
/// The stream could not be read.
/// The stream could not be read.
public static StillVideoResult Analyse(Stream seekable, TimeSpan budget, CancellationToken ct)
{
ArgumentNullException.ThrowIfNull(seekable);
using var limit = CancellationTokenSource.CreateLinkedTokenSource(ct);
if (budget <= TimeSpan.Zero)
{
limit.Cancel();
}
else if (budget < TimeSpan.FromDays(1))
{
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
{
result = Run(watched, limit.Token);
}
catch (OperationCanceledException) when (!ct.IsCancellationRequested)
{
result = NotAnalyzable(VideoAnalysisNotes.TooSlow, 0, 0, false);
}
watched.Fault?.Throw();
return result;
}
/// Analyses the video in with no limit but .
public static StillVideoResult Analyse(Stream seekable, CancellationToken ct) => Analyse(seekable, TimeSpan.MaxValue, ct);
///
/// Analyses the video file at on the thread pool, as :
/// a file that cannot be opened is «Non analizzabile» (); one that stops being
/// readable meanwhile throws.
///
public static Task AnalyseAsync(string path, TimeSpan budget, CancellationToken ct = default)
{
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, ct);
if (!info.Available)
{
return NotAnalyzable(VideoAnalysisNotes.FrameNotAvailable, 0, info);
}
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);
}
var targets = Targets(reader, shown);
var frames = new List(targets.Count);
if (Look(reader, targets, frames, ct) is { } pair)
{
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)
{
return Moving(frames.Count, info, second.Mean, second.Area);
}
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 at the start or the end are a fade; between two that are not, the
// picture changes unless they are its like (a dim picture around the threshold).
// 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(complete ? VideoAnalysisNotes.AllDark : VideoAnalysisNotes.Unreadable, frames.Count, info);
}
var last = frames.FindLastIndex(f => !f.Dark);
var pictures = frames.GetRange(first, last - first + 1);
foreach (var i in Enumerable.Range(0, pictures.Count).Where(i => pictures[i].Dark))
{
var (mean, area) = Compare(pictures[i], pictures.Take(i).Last(f => !f.Dark));
if (mean > MeanThreshold || area > EarlyAreaFactor * AreaThreshold)
{
return Moving(frames.Count, info, mean, area);
}
}
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 (!complete)
{
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.
var chosen = pictures[0];
foreach (var f in pictures.Skip(1).Where(f => !f.Dark))
{
if (f.Sharpness > chosen.Sharpness)
{
chosen = f;
}
}
return new StillVideoResult(VideoAnalysisOutcome.Still, TimeSpan.FromMilliseconds(ExportFrames.ActualMs(chosen.Actual)),
small ? VideoAnalysisNotes.SmallMotion : null, frames.Count, info.Rotation, info.HasAudio,
Math.Round(difference, 2), Math.Round(changed, 4), Math.Round(chosen.Sharpness, 2));
}
///
/// The frames to look at among (pictures in shown order): all of them when they are at most
/// ; otherwise one in each of as many equal parts of the time they cover, at the uneven
/// , every other one moved to a near key frame; then others by position when fewer than
/// come out.
///
private static List Targets(VideoFrameReader reader, IReadOnlyList shown)
{
if (shown.Count <= Samples)
{
return [.. shown];
}
var (from, last) = (shown[0].Actual, shown[^1].Actual);
var length = last - from + ((last - from) / (shown.Count - 1));
var instants = Offsets.Select((o, i) => from + TimeSpan.FromTicks((long)(length.Ticks * ((i + o) / Samples)))).ToList();
var exact = reader.Locate(instants);
var near = reader.LocateNearKey(instants, length / (4 * Samples));
var targets = new List(Samples);
var taken = new HashSet();
for (var i = 0; i < Samples; i++)
{
var target = i % 2 == 0 && near[i].Actual >= from && near[i].Actual <= last ? near[i] : exact[i];
if (taken.Add(target.Sample))
{
targets.Add(target);
}
}
// Pictures held for long take several instants: the others are looked at by their position.
for (var i = 0; i < Samples && targets.Count < Samples; i++)
{
var target = shown[(int)(shown.Count * ((i + Offsets[i]) / Samples))];
if (taken.Add(target.Sample))
{
targets.Add(target);
}
}
return targets;
}
/// The pictures shown between the dark frames nearest to the only one that is not dark.
private static List Around(IReadOnlyList shown, List frames)
{
var lit = frames.Single(f => !f.Dark).Actual;
var before = frames.Where(f => f.Dark && f.Actual < lit).Select(f => f.Actual).DefaultIfEmpty(TimeSpan.MinValue).Max();
var after = frames.Where(f => f.Dark && f.Actual > lit).Select(f => f.Actual).DefaultIfEmpty(TimeSpan.MaxValue).Min();
return [.. shown.Where(t => t.Actual > before && t.Actual < after)];
}
///
/// Decodes the targets and adds them to : the difference of the first pair that moves, or
/// null when none does (or the stream is damaged: fewer frames than targets come out).
///
private static (double Mean, double Area)? Look(VideoFrameReader reader, List targets, List frames, CancellationToken ct)
{
try
{
foreach (var frame in reader.Decode(targets, ct))
{
Signature signature;
using (frame)
{
signature = Signature.Of(frame.Image, frame.Actual);
}
ct.ThrowIfCancellationRequested();
frames.Add(signature);
if (signature.Dark)
{
continue;
}
foreach (var other in frames.Where(f => !f.Dark && f != signature && !(f.Uniform && signature.Uniform)))
{
var (mean, area) = Compare(signature, other);
if (mean > MeanThreshold || area > EarlyAreaFactor * AreaThreshold)
{
// One pair that moves is enough: the rest of the video is not decoded.
return (mean, area);
}
}
}
}
catch (Exception ex) when (VideoFrameDecoder.IsUnreadableFile(ex))
{
// A damaged stream past the frames read so far: the caller sees that some are missing.
}
return null;
}
private static StillVideoResult NotAnalyzable(string note, int sampled, VideoFrameInfo info) =>
NotAnalyzable(note, sampled, info.Rotation, info.HasAudio);
private static StillVideoResult NotAnalyzable(string note, int sampled, int rotation, bool hasAudio) =>
new(VideoAnalysisOutcome.NotAnalyzable, null, note, sampled, rotation, hasAudio, 0, 0, 0);
private static StillVideoResult Moving(int sampled, VideoFrameInfo info, double difference, double area) =>
new(VideoAnalysisOutcome.Moving, null, null, sampled, info.Rotation, info.HasAudio, Math.Round(difference, 2), Math.Round(area, 4), 0);
///
/// Whether the pictures, each of a single colour, all show the same colour, fades undone on its largest channel that
/// is not clipped at white.
///
private static bool SameColour(List pictures)
{
var brightest = pictures.MaxBy(p => p.Luma.Sum())!.Whole;
var channel = Enumerable.Range(0, Grid.Channels)
.OrderBy(c => brightest.Clipped[c][0] > ClippedShare || brightest.Mean[c][0] < GainFloor)
.ThenByDescending(c => brightest.Mean[c][0])
.First();
return pictures.All(p =>
{
var gain = Math.Clamp(p.Whole.Mean[channel][0] / Math.Max(1.0, brightest.Mean[channel][0]), 1 / GainRange, GainRange);
return Measure(p.Whole, brightest, gain, gain, ChromaWeight).Area == 0;
});
}
/// The difference of two frames on the blocks, after a fade between them is undone: the darker one against the brighter.
private static (double Mean, double Area) Compare(Signature a, Signature b)
{
var gain = Gain(a, b);
return gain <= 1
? Measure(a.Coarse, b.Coarse, gain, gain, ChromaWeight)
: Measure(b.Coarse, a.Coarse, 1 / gain, 1 / gain, ChromaWeight);
}
///
/// The largest difference of a frame from the still picture, on the blocks and on the finer cells (luma only): the
/// median of the frames, each first brought to the brightness of the brightest one. «Small» tells that at least the
/// area of a block changed.
///
private static (double Mean, double Area, bool Small) AgainstStillPicture(List pictures)
{
if (pictures.Count < 2)
{
return (0, 0, false);
}
var reference = pictures.MaxBy(p => p.Luma.Sum())!;
var gains = pictures.Select(p => Gain(p, reference)).ToArray();
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++)
{
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;
}
}
var lowest = gains.Min();
double mean = 0, area = 0;
for (var k = 0; k < frames.Length; k++)
{
var (m, a) = Measure(frames[k], still, gains[k], lowest, chroma);
mean = Math.Max(mean, m);
area = Math.Max(area, a);
}
return (mean, area);
}
///
/// The mean difference of the cells (each capped at ) and the fraction of them over it,
/// between and brought to its brightness (
/// times its own). A cell clipped at white may hide brightness: a frame darker than the picture may show there up to
/// what the picture lost, a brighter one less than the picture (measured on frames as dark as
/// ) has; that much of the difference does not count.
///
private static (double Mean, double Area) Measure(Grid frame, Grid picture, double gain, double lowest, double chroma)
{
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;
for (var i = 0; i < frame.Count; i++)
{
var d = scale * Difference(Channel(0, i), Channel(1, i), Channel(2, i), chroma);
if (d > BlockThreshold)
{
changed++;
}
sum += Math.Min(d, BlockThreshold);
}
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));
}
}
/// The difference of two colours: of luma, and of B − Y and R − Y by the weight .
private static double Difference(double red, double green, double blue, double chroma)
{
var luma = Bt709(red, green, blue);
return Math.Abs(luma) + (chroma * (Math.Abs(blue - luma) + Math.Abs(red - luma)));
}
private static double Bt709(double red, double green, double blue) => (0.2126 * red) + (0.7152 * green) + (0.0722 * blue);
///
/// The brightness of against when it is a fade of it, 1 otherwise: from the
/// blocks not clipped at white or, when they are too few or do not agree, from all of them (a white card).
///
private static double Gain(Signature a, Signature b) => Fade(a, b, clippedToo: false) ?? Fade(a, b, clippedToo: true) ?? 1;
///
/// The ratio between two frames that the blocks agree on, or null. Each block counts by its brightness: the median
/// of the ratios, provided at least half of the light is in blocks that follow it within
/// (a different picture gives ratios all over), and the blocks are at least ; then the ratio
/// of the light of those blocks. The largest channel of a block that is not clipped is measured, so that a saturated
/// or dark picture takes part too; a block under in both frames does not.
///
private static double? Fade(Signature a, Signature b, bool clippedToo)
{
var blocks = new List<(float A, float B, double Ratio)>(Signature.Blocks);
double light = 0;
for (var i = 0; i < Signature.Blocks; i++)
{
float largest = 0, va = 0, vb = 0;
for (var c = 0; c < Grid.Channels; c++)
{
var (ca, cb) = (a.Coarse.Mean[c][i], b.Coarse.Mean[c][i]);
if (Math.Max(ca, cb) > largest
&& (clippedToo || (a.Coarse.Clipped[c][i] <= ClippedShare && b.Coarse.Clipped[c][i] <= ClippedShare)))
{
(largest, va, vb) = (Math.Max(ca, cb), ca, cb);
}
}
if (largest >= GainFloor)
{
blocks.Add((va, vb, Math.Max(va, 0.5) / Math.Max(vb, 0.5)));
light += largest;
}
}
if (blocks.Count < GainBlocks)
{
return null;
}
blocks.Sort((x, y) => x.Ratio.CompareTo(y.Ratio));
double median = 1, passed = 0;
foreach (var (va, vb, ratio) in blocks)
{
(median, passed) = (ratio, passed + Math.Max(va, vb));
if (passed >= light / 2)
{
break;
}
}
double agreeing = 0, lightA = 0, lightB = 0;
foreach (var (va, vb, _) in blocks)
{
// Measured on the darker frame, where one level of rounding weighs the most.
var (darker, expected) = median <= 1 ? (va, vb * median) : (vb, va / median);
if (Math.Abs(darker - expected) <= Math.Max(GainNoise, GainAgreement / 2 * expected))
{
agreeing += Math.Max(va, vb);
(lightA, lightB) = (lightA + va, lightB + vb);
}
}
var gain = lightA / Math.Max(lightB, 0.5);
return agreeing >= light / 2 && gain is >= 1 / GainRange and <= GainRange ? gain : null;
}
/// The picture in cells: for each channel the mean of the cell and the share of it clipped at white.
private sealed class Grid
{
internal const int Channels = 3;
internal Grid(int columns, int rows)
{
(Columns, Rows) = (columns, rows);
for (var c = 0; c < Channels; c++)
{
(Mean[c], Clipped[c]) = (new float[Count], new float[Count]);
}
}
internal int Columns { get; }
internal int Rows { get; }
internal int Count => Columns * Rows;
/// The means of each cell, by channel: red, green and blue.
internal float[][] Mean { get; } = new float[Channels][];
/// The shares of each cell clipped at white, by channel.
internal float[][] Clipped { get; } = new float[Channels][];
///
/// The grid of an RGBA frame. Each cell covers at least one pixel, so a frame narrower than the grid (or a stream
/// that changes size) still gives a full grid.
///
internal static Grid Of(RgbaImage image, int columns, int rows)
{
var grid = new Grid(columns, rows);
var (w, h) = (image.Width, image.Height);
ReadOnlySpan pixels = image.Pixels;
var stride = image.Stride;
for (var gy = 0; gy < rows; gy++)
{
var y0 = gy * h / rows;
var y1 = Math.Max(y0 + 1, (gy + 1) * h / rows);
for (var gx = 0; gx < columns; gx++)
{
var x0 = gx * w / columns;
var x1 = Math.Max(x0 + 1, (gx + 1) * w / columns);
long r = 0, g = 0, b = 0;
int wr = 0, wg = 0, wb = 0;
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;
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);
}
}
return grid;
}
}
/// What is kept of a frame looked at: its grids, whether it is dark or of one colour, its sharpness.
private sealed class Signature
{
internal const int Blocks = GridSize * GridSize;
private Signature(TimeSpan actual, Grid whole, Grid coarse, Grid fine)
{
(Actual, Whole, Coarse, Fine) = (actual, whole, coarse, fine);
}
internal TimeSpan Actual { get; }
internal Grid Coarse { get; }
internal Grid Fine { get; }
/// The luma of each block.
internal double[] Luma { get; } = new double[Blocks];
/// The frame as one cell: its mean colour.
internal Grid Whole { get; }
internal bool Dark { get; private set; }
internal bool Uniform { get; private set; }
internal double Sharpness { get; private set; }
/// The signature of an upright RGBA frame.
internal static Signature Of(RgbaImage image, TimeSpan actual)
{
var (w, h) = (image.Width, image.Height);
var coarse = Grid.Of(image, GridSize, GridSize);
var fine = Grid.Of(image, Math.Clamp(w / FineCell, 1, FineGridSize), Math.Clamp(h / FineCell, 1, FineGridSize));
var whole = Grid.Of(image, 1, 1);
var s = new Signature(actual, whole, coarse, fine);
var blue = new double[Blocks];
var red = new double[Blocks];
var brightest = 0.0;
for (var i = 0; i < Blocks; i++)
{
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)));
}
ReadOnlySpan pixels = image.Pixels;
s.Dark = brightest < DarkLevel && !HasBrightDetail(pixels, w, h, image.Stride);
s.Uniform = Spread(s.Luma) < UniformSpread && Spread(blue) < UniformSpread && Spread(red) < UniformSpread
&& !HasDetail(pixels, w, h, image.Stride, Bt709(whole.Mean[0][0], whole.Mean[1][0], whole.Mean[2][0]));
s.Sharpness = LaplacianVariance(pixels, w, h, image.Stride);
return s;
}
/// Whether some pixels are bright: a small text on black, lost in the means of the blocks.
private static bool HasBrightDetail(ReadOnlySpan pixels, int w, int h, int stride)
{
long bright = 0;
for (var y = 0; y < h; y++)
{
var row = pixels.Slice(y * stride, w * RgbaImage.BytesPerPixel);
for (var i = 0; i < row.Length; i += RgbaImage.BytesPerPixel)
{
bright += Math.Max(row[i], Math.Max(row[i + 1], row[i + 2])) >= BrightDetail ? 1 : 0;
}
}
return bright > DetailShare * w * h;
}
/// Whether the pixels vary, though the blocks do not: a small text, a fine texture.
private static bool HasDetail(ReadOnlySpan pixels, int w, int h, int stride, double mean)
{
double squares = 0;
long far = 0;
for (var y = 0; y < h; y++)
{
var row = pixels.Slice(y * stride, w * RgbaImage.BytesPerPixel);
for (var i = 0; i < row.Length; i += RgbaImage.BytesPerPixel)
{
var d = Bt709(row[i], row[i + 1], row[i + 2]) - mean;
squares += d * d;
far += Math.Abs(d) > UniformDetail ? 1 : 0;
}
}
return squares >= UniformVariance * w * h || far > DetailShare * w * h;
}
private static double Spread(double[] values)
{
var mean = values.Average();
var sum = 0.0;
foreach (var v in values)
{
sum += (v - mean) * (v - mean);
}
return Math.Sqrt(sum / values.Length);
}
///
/// 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).
///
private static double LaplacianVariance(ReadOnlySpan pixels, int w, int h, int stride)
{
if (w < 3 || h < 3)
{
return 0;
}
var luma = ArrayPool.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.Shared.Return(luma);
}
}
}
///
/// The stream, remembering the first error of its own: an or an
/// thrown by it, not the ones the readers raise above it for a file cut
/// short or damaged.
///
private sealed class WatchedStream(Stream inner) : Stream
{
internal ExceptionDispatchInfo? Fault { get; private set; }
public override bool CanRead => true;
public override bool CanSeek => true;
public override bool CanWrite => false;
public override long Length
{
get
{
try
{
return inner.Length;
}
catch (Exception ex)
{
Remember(ex);
throw;
}
}
}
public override long Position
{
get => inner.Position;
set => inner.Position = value; // reads nothing: an error comes from a damaged table
}
public override int Read(byte[] buffer, int offset, int count) => Read(buffer.AsSpan(offset, count));
public override int Read(Span buffer)
{
try
{
return inner.Read(buffer);
}
catch (Exception ex)
{
Remember(ex);
throw;
}
}
public override long Seek(long offset, SeekOrigin origin) => inner.Seek(offset, origin);
public override void Flush()
{
}
public override void SetLength(long value) => throw new NotSupportedException();
public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException();
private void Remember(Exception ex)
{
if (ex is UnauthorizedAccessException or (IOException and not EndOfStreamException))
{
Fault ??= ExceptionDispatchInfo.Capture(ex);
}
}
}
}