Una scritta o un marchio sul nero, un cartello blu e una foto scura che si dissolvono risultavano «In movimento»: il guadagno si stima pesando i blocchi sulla luce, sul canale più forte non bruciato. Lo stesso per un'immagine scura quanto la soglia, che la grana porta sopra e sotto: un fotogramma scuro fra due si confronta, non si condanna. Gli istanti nuovi abbracciano almeno il 48 % del giro di un filmato ripetuto da 2 a 40 volte; prima, a quasi sette ripetizioni, cadevano tutti insieme e il video risultava «Fermo». Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
945 lines
42 KiB
C#
945 lines
42 KiB
C#
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;
|
||
|
||
/// <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 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 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.</item>
|
||
/// <item>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.</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, 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>
|
||
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>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): 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.
|
||
/// </summary>
|
||
internal static readonly double[] Offsets = [0.54, 0.865, 0.417, 0.253, 0.432, 0.45, 0.46];
|
||
|
||
/// <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>
|
||
internal const double EarlyAreaFactor = 3;
|
||
|
||
/// <summary>Blocks darker than this (their largest channel) in both frames do not take part in the estimate of a fade.</summary>
|
||
internal const double GainFloor = 8;
|
||
|
||
/// <summary>The fewest blocks that can tell a fade.</summary>
|
||
internal const int GainBlocks = 10;
|
||
|
||
/// <summary>A block this near (0–255) to what the fade makes of it follows it: the rounding of a dim frame.</summary>
|
||
internal const double GainNoise = 1.5;
|
||
|
||
/// <summary>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.</summary>
|
||
internal const double GainAgreement = 0.1;
|
||
|
||
/// <summary>The largest brightness ratio undone as a fade.</summary>
|
||
internal const double GainRange = 16;
|
||
|
||
/// <summary>
|
||
/// 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.
|
||
/// </summary>
|
||
internal 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>
|
||
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, 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);
|
||
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;
|
||
}
|
||
|
||
/// <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"/>); one that stops being
|
||
/// readable meanwhile throws.
|
||
/// </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, 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<Signature>(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));
|
||
}
|
||
|
||
/// <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>
|
||
/// 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.
|
||
/// </summary>
|
||
private static bool SameColour(List<Signature> 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;
|
||
});
|
||
}
|
||
|
||
/// <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 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, 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, bool Small) AgainstStillPicture(List<Signature> 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);
|
||
}
|
||
|
||
/// <summary>
|
||
/// 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 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));
|
||
}
|
||
}
|
||
|
||
/// <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, 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).
|
||
/// </summary>
|
||
private static double Gain(Signature a, Signature b) => Fade(a, b, clippedToo: false) ?? Fade(a, b, clippedToo: true) ?? 1;
|
||
|
||
/// <summary>
|
||
/// 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 <see cref="GainAgreement"/>
|
||
/// (a different picture gives ratios all over), and the blocks are at least <see cref="GainBlocks"/>; 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 <see cref="GainFloor"/> in both frames does not.
|
||
/// </summary>
|
||
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;
|
||
}
|
||
|
||
/// <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.
|
||
/// </summary>
|
||
internal static Grid Of(RgbaImage image, int columns, int rows)
|
||
{
|
||
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;
|
||
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;
|
||
}
|
||
}
|
||
|
||
/// <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;
|
||
|
||
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; }
|
||
|
||
/// <summary>The luma of each block.</summary>
|
||
internal double[] Luma { get; } = new double[Blocks];
|
||
|
||
/// <summary>The frame as one cell: its mean colour.</summary>
|
||
internal Grid Whole { get; }
|
||
|
||
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.</summary>
|
||
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<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(whole.Mean[0][0], whole.Mean[1][0], whole.Mean[2][0]));
|
||
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;
|
||
}
|
||
}
|
||
|
||
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)
|
||
{
|
||
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);
|
||
}
|
||
}
|
||
}
|
||
|
||
/// <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);
|
||
}
|
||
}
|
||
}
|
||
}
|