Esportazione, tappa E4: video fermi #80
No files matched your search
@@ -359,7 +359,7 @@ public sealed record VideoAnalysis(
|
||||
|
||||
/// <summary>
|
||||
/// The codes of <c>video_analysis.note</c> (tappa E4), English, separated by spaces like <c>export_item.note</c>. They
|
||||
/// say why a video is «Non analizzabile».
|
||||
/// say why a video is «Non analizzabile», or (<see cref="SmallMotion"/>) that a small part of a still video moves.
|
||||
/// </summary>
|
||||
public static class VideoAnalysisNotes
|
||||
{
|
||||
@@ -381,8 +381,14 @@ public static class VideoAnalysisNotes
|
||||
/// <summary>Every frame looked at is all of one single colour, not dark (answer 42 of Alberto, 29 November 2026).</summary>
|
||||
public const string SingleColor = "SingleColor";
|
||||
|
||||
/// <summary>
|
||||
/// On a still video: a small part of the picture moves (an animated sticker, a moving caption), within the area a
|
||||
/// still video may change (answer 47 of Alberto, 29 November 2026).
|
||||
/// </summary>
|
||||
public const string SmallMotion = "SmallMotion";
|
||||
|
||||
/// <summary>Every code of algorithm 1, in the order above.</summary>
|
||||
public static IReadOnlyList<string> All { get; } = [FrameNotAvailable, DurationUnknown, Unreadable, TooSlow, AllDark, SingleColor];
|
||||
public static IReadOnlyList<string> All { get; } = [FrameNotAvailable, DurationUnknown, Unreadable, TooSlow, AllDark, SingleColor, SmallMotion];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -45,33 +45,20 @@ public sealed record VideoImage(int Width, int Height, byte[] Rgb)
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Whether a video only shows a still picture (a photo with music, for example): then one frame stands for the whole
|
||||
/// video. <see cref="Difference"/> is the largest mean difference, on a 0–255 scale, between the first sampled frame and
|
||||
/// the others, measured on a coarse grid so that the noise of the compression does not count.
|
||||
/// </summary>
|
||||
public sealed record VideoStillness(bool IsStill, int SampledFrames, double Difference);
|
||||
|
||||
/// <summary>
|
||||
/// Frames of videos without external programs (spec §8.4: thumbnails of imported videos and of videos without a cover):
|
||||
/// the container readers of <see cref="ContainerReader"/> and the H.264 and HEVC decoders written in house
|
||||
/// (<see cref="H264Decoder"/>, <see cref="H265Decoder"/>). Videos in other codecs (VP9, AV1, ...) give no frame: the
|
||||
/// interface shows the neutral tile.
|
||||
/// interface shows the neutral tile. Whether a video is still is told by <see cref="StillVideoAnalyzer"/>.
|
||||
/// </summary>
|
||||
public sealed partial class VideoFrameDecoder
|
||||
{
|
||||
/// <summary>Differences up to this value (0–255) count as compression noise of a still picture.</summary>
|
||||
public const double StillThreshold = 3.0;
|
||||
|
||||
/// <summary>
|
||||
/// The longest a frame or a stillness analysis may take: what the external extractor used before C3 was given. A damaged
|
||||
/// file never holds an import or a rebuild for longer.
|
||||
/// The longest a frame may take: what the external extractor used before C3 was given. A damaged file never holds an
|
||||
/// import or a rebuild for longer.
|
||||
/// </summary>
|
||||
public static readonly TimeSpan DefaultBudget = TimeSpan.FromSeconds(30);
|
||||
|
||||
private const int GridSize = 32;
|
||||
private const int SampledPositions = 6;
|
||||
private const int MaxSequentialSamples = 2000;
|
||||
private const int DefaultMaxRun = 300;
|
||||
|
||||
/// <summary>How far back from a sample flagged as key the decoder looks for one it can really start from.</summary>
|
||||
@@ -125,16 +112,6 @@ public sealed partial class VideoFrameDecoder
|
||||
return Task.Run(() => WithinBudget(token => DecodeFrame(videoPath, at, maxLongSide, token), ct), ct);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Whether the video shows a still picture, from frames spread over its whole length; null when it cannot be told
|
||||
/// (unreadable file, codec not decoded, or one long run without key frames in a long video).
|
||||
/// </summary>
|
||||
public Task<VideoStillness?> AnalyseStillnessAsync(string videoPath, CancellationToken ct = default)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(videoPath);
|
||||
return Task.Run(() => WithinBudget(token => AnalyseStillness(videoPath, token), ct), ct);
|
||||
}
|
||||
|
||||
/// <summary>Runs <paramref name="work"/> for at most the budget: past it the result is null, as for an unreadable file.</summary>
|
||||
private T? WithinBudget<T>(Func<CancellationToken, T?> work, CancellationToken ct)
|
||||
where T : class
|
||||
@@ -197,94 +174,6 @@ public sealed partial class VideoFrameDecoder
|
||||
}
|
||||
}
|
||||
|
||||
private VideoStillness? AnalyseStillness(string path, CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
ct.ThrowIfCancellationRequested();
|
||||
using var stream = ContainerReader.OpenRead(path);
|
||||
if (Open(stream) is not { } video)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var samples = video.Samples;
|
||||
if (samples.Count == 1)
|
||||
{
|
||||
return new VideoStillness(true, 1, 0);
|
||||
}
|
||||
|
||||
// Positions spread over the presentation, from the first to the last frame.
|
||||
long first = long.MaxValue, last = long.MinValue;
|
||||
foreach (var s in samples)
|
||||
{
|
||||
first = Math.Min(first, s.PresentationTime);
|
||||
last = Math.Max(last, s.PresentationTime);
|
||||
}
|
||||
|
||||
var decoding = new Decoding(stream, video, maxRun);
|
||||
var targets = new SortedSet<int>();
|
||||
for (var i = 0; i < SampledPositions; i++)
|
||||
{
|
||||
ct.ThrowIfCancellationRequested();
|
||||
var time = first + ((last - first) * i / (SampledPositions - 1));
|
||||
var index = Closest(samples, time);
|
||||
|
||||
// Far from where decoding can start in a long video: the frame there stands for it, so the work stays
|
||||
// bounded.
|
||||
var start = decoding.RunStart(index);
|
||||
if (index - start > maxRun && samples.Count > MaxSequentialSamples)
|
||||
{
|
||||
index = start;
|
||||
}
|
||||
|
||||
targets.Add(index);
|
||||
}
|
||||
|
||||
if (targets.Count < 2)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var frames = decoding.DecodeAll([.. targets], ct);
|
||||
if (frames.Count < 2)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
double[]? reference = null;
|
||||
var difference = 0.0;
|
||||
foreach (var index in targets)
|
||||
{
|
||||
if (!frames.TryGetValue(index, out var frame))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var grid = Grid(frame);
|
||||
if (reference is null)
|
||||
{
|
||||
reference = grid;
|
||||
continue;
|
||||
}
|
||||
|
||||
double sum = 0;
|
||||
for (var i = 0; i < grid.Length; i++)
|
||||
{
|
||||
sum += Math.Abs(grid[i] - reference[i]);
|
||||
}
|
||||
|
||||
difference = Math.Max(difference, sum / grid.Length);
|
||||
}
|
||||
|
||||
return new VideoStillness(difference <= StillThreshold, frames.Count, Math.Round(difference, 2));
|
||||
}
|
||||
catch (Exception ex) when (IsUnreadable(ex))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static bool IsUnreadable(Exception ex) => ex is ContainerException or H264Exception or H265Exception or IOException
|
||||
or EndOfStreamException or UnauthorizedAccessException or ArgumentException or IndexOutOfRangeException
|
||||
or InvalidOperationException or OverflowException or InvalidDataException;
|
||||
@@ -560,8 +449,8 @@ public sealed partial class VideoFrameDecoder
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Decodes the targets (sample indices in ascending order) and keeps every frame: the few a thumbnail or a
|
||||
/// stillness check asks for.
|
||||
/// Decodes the targets (sample indices in ascending order) and keeps every frame: the few a thumbnail asks
|
||||
/// for.
|
||||
/// </summary>
|
||||
internal Dictionary<int, Frame> DecodeAll(int[] targets, CancellationToken ct)
|
||||
{
|
||||
@@ -648,65 +537,6 @@ public sealed partial class VideoFrameDecoder
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A coarse grid of mean luma and chroma values, to compare frames without their compression noise.</summary>
|
||||
private static double[] Grid(Frame frame) =>
|
||||
frame.Hevc is { } h ? Grid(Planes(h)) : frame.Avc!.BytesPerSample == 2 ? Grid(WidePlanes(frame.Avc)) : Grid(Planes(frame.Avc));
|
||||
|
||||
/// <summary>
|
||||
/// The grid on an 8-bit scale: luma means in the first half, mean distances of the chroma from its middle in the
|
||||
/// second (zero for a monochrome picture).
|
||||
/// </summary>
|
||||
private static double[] Grid<T>(in YuvPlanes<T> frame)
|
||||
where T : unmanaged, IBinaryInteger<T>
|
||||
{
|
||||
var grid = new double[GridSize * GridSize * 2];
|
||||
var counts = new int[GridSize * GridSize];
|
||||
var lumaScale = 1.0 / (1 << Math.Max(0, frame.BitDepthY - 8));
|
||||
ReadOnlySpan<T> luma = frame.Y;
|
||||
for (var y = 0; y < frame.Height; y++)
|
||||
{
|
||||
var gy = y * GridSize / frame.Height;
|
||||
var row = luma.Slice(y * frame.Width, frame.Width);
|
||||
for (var x = 0; x < row.Length; x++)
|
||||
{
|
||||
var cell = (gy * GridSize) + (x * GridSize / frame.Width);
|
||||
grid[cell] += int.CreateTruncating(row[x]) * lumaScale;
|
||||
counts[cell]++;
|
||||
}
|
||||
}
|
||||
|
||||
var chromaCounts = new int[GridSize * GridSize];
|
||||
if (!frame.Monochrome)
|
||||
{
|
||||
var cw = frame.ChromaWidth;
|
||||
var ch = (frame.Height + (1 << frame.ChromaShiftY) - 1) >> frame.ChromaShiftY;
|
||||
var middle = 1 << (frame.BitDepthC - 1);
|
||||
var chromaScale = 1.0 / (1 << Math.Max(0, frame.BitDepthC - 8)) / 2;
|
||||
ReadOnlySpan<T> cb = frame.Cb, cr = frame.Cr;
|
||||
for (var y = 0; y < ch; y++)
|
||||
{
|
||||
var gy = y * GridSize / ch;
|
||||
for (var x = 0; x < cw; x++)
|
||||
{
|
||||
var cell = (gy * GridSize) + (x * GridSize / cw);
|
||||
var i = (y * cw) + x;
|
||||
grid[(GridSize * GridSize) + cell] +=
|
||||
(Math.Abs(int.CreateTruncating(cb[i]) - middle) + Math.Abs(int.CreateTruncating(cr[i]) - middle)) * chromaScale;
|
||||
chromaCounts[cell]++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (var i = 0; i < counts.Length; i++)
|
||||
{
|
||||
grid[i] = counts[i] > 0 ? grid[i] / counts[i] : 0;
|
||||
var c = (GridSize * GridSize) + i;
|
||||
grid[c] = chromaCounts[i] > 0 ? grid[c] / chromaCounts[i] : 0;
|
||||
}
|
||||
|
||||
return grid;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The planes of an H.264 frame of 8-bit samples, at any chroma sampling. A monochrome frame comes with grey 4:2:0
|
||||
/// chroma planes (<see cref="H264Frame"/>), which the conversion does not read.
|
||||
@@ -719,7 +549,7 @@ public sealed partial class VideoFrameDecoder
|
||||
|
||||
/// <summary>
|
||||
/// The planes of an H.264 frame above 8 bits (two bytes a sample, little-endian), as 16-bit values: copied once,
|
||||
/// for the few frames a thumbnail or a stillness check decodes.
|
||||
/// for the few frames a thumbnail or a frame copy decodes.
|
||||
/// </summary>
|
||||
private static YuvPlanes<ushort> WidePlanes(H264Frame frame)
|
||||
{
|
||||
|
||||
@@ -164,6 +164,50 @@ public sealed class VideoFrameReader : IDisposable
|
||||
return targets;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// As <see cref="Locate"/>, but each instant moves to the key sample (a sync sample: a frame decoding can start from)
|
||||
/// shown nearest to it, when one is shown within <paramref name="reach"/> of it (the earlier of two as near): a frame
|
||||
/// that costs one decoding instead of a run from the key frame before it. Used where any frame near the instant
|
||||
/// does, as the still-video analysis (tappa E4).
|
||||
/// </summary>
|
||||
public IReadOnlyList<VideoFrameTarget> LocateNearKey(IReadOnlyList<TimeSpan> instants, TimeSpan reach)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(instants);
|
||||
var targets = Locate(instants);
|
||||
if (targets.Count == 0 || reach <= TimeSpan.Zero)
|
||||
{
|
||||
return targets;
|
||||
}
|
||||
|
||||
var timescale = (Int128)Math.Max(1, video!.Timescale);
|
||||
var result = new VideoFrameTarget[targets.Count];
|
||||
for (var i = 0; i < targets.Count; i++)
|
||||
{
|
||||
// Shown times compared in track units: the instant and the reach brought to them (rounded down).
|
||||
var at = (Int128)instants[i].Ticks * timescale / TimeSpan.TicksPerSecond;
|
||||
var span = (Int128)reach.Ticks * timescale / TimeSpan.TicksPerSecond;
|
||||
var best = -1;
|
||||
var distance = Int128.MaxValue;
|
||||
foreach (var sample in order)
|
||||
{
|
||||
var gap = Int128.Abs(shown[sample] - at);
|
||||
if (shown[sample] - at > span)
|
||||
{
|
||||
break; // in shown order: every later sample is further
|
||||
}
|
||||
|
||||
if (gap <= span && video.Samples[sample].Key && gap < distance)
|
||||
{
|
||||
(best, distance) = (sample, gap);
|
||||
}
|
||||
}
|
||||
|
||||
result[i] = best < 0 ? targets[i] : new VideoFrameTarget(i, instants[i], ShownAt(best), best);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Decodes the targets lazily, in decoding order (not the order of the instants): each frame comes out as soon as it
|
||||
/// is decoded and must be disposed by the caller. A target whose sample gives no picture (a damaged stream) is left
|
||||
|
||||
@@ -80,23 +80,6 @@ public sealed class HevcVideoTests
|
||||
Assert.AreEqual((byte)'B', bmp[0]);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task AnHevcVideoOfAStillPictureIsRecognisedAndOneThatMovesIsNot()
|
||||
{
|
||||
var es = ElementaryStream.LoadHevc(Moving);
|
||||
using var temp = new TempFolder("fermo-hevc");
|
||||
var still = TestVideos.Write(temp, "fermo.mp4", TestVideos.Mp4(es.FirstPictureRepeated(90)));
|
||||
var result = await VideoFrameDecoder.Instance.AnalyseStillnessAsync(still);
|
||||
Assert.IsNotNull(result);
|
||||
Assert.IsTrue(result.IsStill);
|
||||
Assert.AreEqual(0, result.Difference);
|
||||
|
||||
var moving = TestVideos.Write(temp, "movimento.mkv", TestVideos.Matroska(ElementaryStream.LoadHevc("CAINIT_A_SHARP_4")));
|
||||
var other = await VideoFrameDecoder.Instance.AnalyseStillnessAsync(moving);
|
||||
Assert.IsNotNull(other);
|
||||
Assert.IsFalse(other.IsStill, $"differenza {other.Difference}");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void AccessPointsAreTheIrapPictures()
|
||||
{
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
using System.Buffers.Binary;
|
||||
using Febe.Core.Codecs.Containers;
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Core.Import;
|
||||
using Febe.Core.Library;
|
||||
using Febe.Tests.Support;
|
||||
@@ -78,9 +79,9 @@ public sealed class MalformedInputTests
|
||||
var path = TestVideos.Write(temp, $"{trial}.{kind}", Garble(file, random));
|
||||
_ = ContainerVideoMetadataProbe.Probe(path, Now); // null or metadata, never an exception
|
||||
var image = await VideoFrameDecoder.Instance.DecodeFrameAsync(path, TimeSpan.FromSeconds(1));
|
||||
var stillness = await VideoFrameDecoder.Instance.AnalyseStillnessAsync(path);
|
||||
var stillness = await StillVideoAnalyzer.AnalyseAsync(path, VideoFrameDecoder.DefaultBudget);
|
||||
decoded += image is null ? 0 : 1;
|
||||
_ = stillness;
|
||||
Assert.IsTrue(stillness.Outcome != VideoAnalysisOutcome.NotAnalyzable || stillness.Note is not null, "un video non analizzabile dice perché");
|
||||
}
|
||||
|
||||
// Most damage hits frame data, not headers: many variants still give a frame. WMV and MPEG program streams have
|
||||
|
||||
@@ -0,0 +1,237 @@
|
||||
using Febe.Core.Codecs.H264;
|
||||
|
||||
namespace Febe.Tests.Codecs.Containers;
|
||||
|
||||
/// <summary>
|
||||
/// Test videos built from pictures whose every pixel is known (I_PCM H.264, <see cref="H264PcmWriter"/>), for the
|
||||
/// still-video analysis of tappa E4: a photo-like picture, grain, fades, an animated sticker, a moving caption, black and
|
||||
/// single-colour pictures. 144 × 256 (9:16, as phones film) at 30 pictures a second through <see cref="TestVideos"/>, so
|
||||
/// audio and rotation come along; nothing comes from Instagram or from a real file.
|
||||
/// </summary>
|
||||
internal static class PcmVideos
|
||||
{
|
||||
public const int Width = 144;
|
||||
|
||||
public const int Height = 256;
|
||||
|
||||
/// <summary>Pictures a second (<see cref="TestVideos.Timescale"/> / <see cref="TestVideos.FrameTicks"/>).</summary>
|
||||
public const int Fps = 30;
|
||||
|
||||
/// <summary>An elementary stream of <paramref name="count"/> IDR pictures, picture <c>i</c> given by <paramref name="picture"/>.</summary>
|
||||
public static ElementaryStream Stream(string name, int count, Func<int, H264PcmPicture> picture)
|
||||
{
|
||||
using var annexB = new MemoryStream();
|
||||
var first = picture(0);
|
||||
foreach (var nal in new[] { H264PcmWriter.Sps(first.Width, first.Height), H264PcmWriter.Pps() })
|
||||
{
|
||||
annexB.Write([0, 0, 0, 1]);
|
||||
annexB.Write(nal);
|
||||
}
|
||||
|
||||
for (var i = 0; i < count; i++)
|
||||
{
|
||||
annexB.Write([0, 0, 0, 1]);
|
||||
annexB.Write(H264PcmWriter.Idr(i == 0 ? first : picture(i), i % 2));
|
||||
}
|
||||
|
||||
return ElementaryStream.FromAnnexB(name, annexB.ToArray());
|
||||
}
|
||||
|
||||
/// <summary>An MP4 of <paramref name="count"/> pictures at <see cref="Fps"/>, optionally rotated and with an audio track.</summary>
|
||||
public static byte[] Mp4(int count, Func<int, H264PcmPicture> picture, int rotation = 0, bool audio = false) =>
|
||||
TestVideos.Mp4(Stream("pcm", count, picture), rotation: rotation, audio: audio);
|
||||
|
||||
/// <summary>
|
||||
/// A photo-like picture: a diagonal gradient, a few coloured shapes and a fine texture (so it has detail to be sharp
|
||||
/// with). Luma 16–235, chroma 16–240.
|
||||
/// </summary>
|
||||
public static H264PcmPicture Photo(int seed = 1)
|
||||
{
|
||||
var random = new Random(seed);
|
||||
var p = new H264PcmPicture(Width, Height);
|
||||
for (var y = 0; y < Height; y++)
|
||||
{
|
||||
for (var x = 0; x < Width; x++)
|
||||
{
|
||||
var texture = ((x / 2) + (y / 2)) % 2 == 0 ? 6 : -6;
|
||||
p.Y[(y * Width) + x] = Luma(40 + (x * 100 / Width) + (y * 60 / Height) + texture);
|
||||
}
|
||||
}
|
||||
|
||||
for (var y = 0; y < Height / 2; y++)
|
||||
{
|
||||
for (var x = 0; x < Width / 2; x++)
|
||||
{
|
||||
p.Cb[(y * Width / 2) + x] = (byte)(100 + (y * 50 / (Height / 2)));
|
||||
p.Cr[(y * Width / 2) + x] = (byte)(110 + (x * 40 / (Width / 2)));
|
||||
}
|
||||
}
|
||||
|
||||
for (var shape = 0; shape < 6; shape++)
|
||||
{
|
||||
var (cx, cy, r) = (random.Next(Width), random.Next(Height), 12 + random.Next(24));
|
||||
var (luma, cb, cr) = (random.Next(30, 220), random.Next(40, 220), random.Next(40, 220));
|
||||
var round = shape % 2 == 0;
|
||||
Paint(p, cx - r, cy - r, 2 * r, 2 * r, (x, y) => !round || ((x - cx) * (x - cx)) + ((y - cy) * (y - cy)) <= r * r ? (luma, cb, cr) : null);
|
||||
}
|
||||
|
||||
return p;
|
||||
}
|
||||
|
||||
/// <summary>A picture of one colour.</summary>
|
||||
public static H264PcmPicture Flat(byte luma, byte cb = 128, byte cr = 128)
|
||||
{
|
||||
var p = new H264PcmPicture(Width, Height);
|
||||
Array.Fill(p.Y, luma);
|
||||
Array.Fill(p.Cb, cb);
|
||||
Array.Fill(p.Cr, cr);
|
||||
return p;
|
||||
}
|
||||
|
||||
/// <summary>Black (limited range).</summary>
|
||||
public static H264PcmPicture Black() => Flat(16);
|
||||
|
||||
/// <summary>A copy of <paramref name="source"/>.</summary>
|
||||
public static H264PcmPicture Copy(H264PcmPicture source)
|
||||
{
|
||||
var p = new H264PcmPicture(source.Width, source.Height);
|
||||
source.Y.CopyTo(p.Y, 0);
|
||||
source.Cb.CopyTo(p.Cb, 0);
|
||||
source.Cr.CopyTo(p.Cr, 0);
|
||||
return p;
|
||||
}
|
||||
|
||||
/// <summary>Grain: every luma sample moved by up to ± <paramref name="amplitude"/>, differently for each seed.</summary>
|
||||
public static H264PcmPicture Noise(H264PcmPicture source, int amplitude, int seed)
|
||||
{
|
||||
var random = new Random(seed);
|
||||
var p = Copy(source);
|
||||
for (var i = 0; i < p.Y.Length; i++)
|
||||
{
|
||||
p.Y[i] = Luma(p.Y[i] + random.Next(-amplitude, amplitude + 1));
|
||||
}
|
||||
|
||||
return p;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The picture faded towards black by <paramref name="factor"/> (1: as it is, 0: black), as an editor fades: luma
|
||||
/// towards 16, chroma towards 128.
|
||||
/// </summary>
|
||||
public static H264PcmPicture Fade(H264PcmPicture source, double factor)
|
||||
{
|
||||
var p = Copy(source);
|
||||
for (var i = 0; i < p.Y.Length; i++)
|
||||
{
|
||||
p.Y[i] = (byte)Math.Round(16 + (factor * (p.Y[i] - 16)));
|
||||
}
|
||||
|
||||
for (var i = 0; i < p.Cb.Length; i++)
|
||||
{
|
||||
p.Cb[i] = (byte)Math.Round(128 + (factor * (p.Cb[i] - 128)));
|
||||
p.Cr[i] = (byte)Math.Round(128 + (factor * (p.Cr[i] - 128)));
|
||||
}
|
||||
|
||||
return p;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The picture with a sticker of <paramref name="width"/> × <paramref name="height"/> pixels at (x, y): a white and
|
||||
/// magenta checkerboard whose phase <paramref name="phase"/> animates it in place.
|
||||
/// </summary>
|
||||
public static H264PcmPicture Sticker(H264PcmPicture source, int x, int y, int width, int height, int phase = 0)
|
||||
{
|
||||
var p = Copy(source);
|
||||
Paint(p, x, y, width, height, (px, py) => (((px - x) / 4) + ((py - y) / 4) + phase) % 2 == 0 ? (235, 128, 128) : (90, 200, 220));
|
||||
return p;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The picture with a caption band <paramref name="height"/> pixels high from row <paramref name="top"/>: a dark band
|
||||
/// with light «letters» that scroll left by <paramref name="offset"/> pixels.
|
||||
/// </summary>
|
||||
public static H264PcmPicture Caption(H264PcmPicture source, int top, int height, int offset)
|
||||
{
|
||||
var p = Copy(source);
|
||||
Paint(p, 0, top, Width, height, (px, py) =>
|
||||
{
|
||||
var column = (px + offset) % 12;
|
||||
var letter = column < 7 && (py - top) > 1 && (py - top) < height - 2 && ((px + offset) / 12 % 5) != 4;
|
||||
return letter ? (230, 128, 128) : (30, 128, 128);
|
||||
});
|
||||
return p;
|
||||
}
|
||||
|
||||
/// <summary>The picture moved right by <paramref name="dx"/> pixels (a pan), the left edge repeated.</summary>
|
||||
public static H264PcmPicture Shift(H264PcmPicture source, int dx)
|
||||
{
|
||||
var p = new H264PcmPicture(source.Width, source.Height);
|
||||
for (var y = 0; y < Height; y++)
|
||||
{
|
||||
for (var x = 0; x < Width; x++)
|
||||
{
|
||||
p.Y[(y * Width) + x] = source.Y[(y * Width) + Math.Clamp(x - dx, 0, Width - 1)];
|
||||
}
|
||||
}
|
||||
|
||||
for (var y = 0; y < Height / 2; y++)
|
||||
{
|
||||
for (var x = 0; x < Width / 2; x++)
|
||||
{
|
||||
var from = (y * Width / 2) + Math.Clamp(x - (dx / 2), 0, (Width / 2) - 1);
|
||||
p.Cb[(y * Width / 2) + x] = source.Cb[from];
|
||||
p.Cr[(y * Width / 2) + x] = source.Cr[from];
|
||||
}
|
||||
}
|
||||
|
||||
return p;
|
||||
}
|
||||
|
||||
/// <summary>The picture with its luma blurred by a 3 × 3 box, as a strong compression softens it.</summary>
|
||||
public static H264PcmPicture Blur(H264PcmPicture source)
|
||||
{
|
||||
var p = Copy(source);
|
||||
for (var y = 0; y < Height; y++)
|
||||
{
|
||||
for (var x = 0; x < Width; x++)
|
||||
{
|
||||
var sum = 0;
|
||||
for (var dy = -1; dy <= 1; dy++)
|
||||
{
|
||||
for (var dx = -1; dx <= 1; dx++)
|
||||
{
|
||||
sum += source.Y[(Math.Clamp(y + dy, 0, Height - 1) * Width) + Math.Clamp(x + dx, 0, Width - 1)];
|
||||
}
|
||||
}
|
||||
|
||||
p.Y[(y * Width) + x] = (byte)((sum + 4) / 9);
|
||||
}
|
||||
}
|
||||
|
||||
return p;
|
||||
}
|
||||
|
||||
/// <summary>Paints the pixels of a rectangle (clipped to the picture) for which <paramref name="colour"/> gives a colour.</summary>
|
||||
private static void Paint(H264PcmPicture p, int x, int y, int width, int height, Func<int, int, (int Luma, int Cb, int Cr)?> colour)
|
||||
{
|
||||
for (var py = Math.Max(0, y); py < Math.Min(Height, y + height); py++)
|
||||
{
|
||||
for (var px = Math.Max(0, x); px < Math.Min(Width, x + width); px++)
|
||||
{
|
||||
if (colour(px, py) is not { } c)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
p.Y[(py * Width) + px] = Luma(c.Luma);
|
||||
if (px % 2 == 0 && py % 2 == 0)
|
||||
{
|
||||
p.Cb[(py / 2 * Width / 2) + (px / 2)] = (byte)Math.Clamp(c.Cb, 16, 240);
|
||||
p.Cr[(py / 2 * Width / 2) + (px / 2)] = (byte)Math.Clamp(c.Cr, 16, 240);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static byte Luma(int value) => (byte)Math.Clamp(value, 16, 235);
|
||||
}
|
||||
@@ -0,0 +1,340 @@
|
||||
using Febe.Core.Codecs.H264;
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Core.Export;
|
||||
using Febe.Core.Library;
|
||||
using Febe.Tests.Support;
|
||||
|
||||
namespace Febe.Tests.Codecs.Containers;
|
||||
|
||||
/// <summary>
|
||||
/// «È un video fermo?» (spec §4.10, tappa E4, algorithm 1) on videos the tests build (<see cref="PcmVideos"/>) and on the
|
||||
/// ITU conformance streams: still pictures with grain, audio, fades, a small animated sticker or caption (answer 47),
|
||||
/// motion, very short clips, black and single-colour videos (answer 42), rotation, unreadable files and the time limit.
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public sealed class StillVideoAnalyzerTests
|
||||
{
|
||||
/// <summary>The time of picture <c>i</c> of a <see cref="PcmVideos"/> video in whole milliseconds, as FrameAt carries it.</summary>
|
||||
private static long Ms(int picture) => ExportFrames.ActualMs(TimeSpan.FromTicks(picture * TimeSpan.TicksPerSecond / PcmVideos.Fps));
|
||||
|
||||
[TestMethod]
|
||||
[DataRow(false)]
|
||||
[DataRow(true)]
|
||||
public void AFixedPictureIsStillWithOrWithoutAudio(bool audio)
|
||||
{
|
||||
var photo = PcmVideos.Photo();
|
||||
var result = Analyse(PcmVideos.Mp4(30, _ => photo, audio: audio));
|
||||
|
||||
Assert.AreEqual(VideoAnalysisOutcome.Still, result.Outcome, Describe(result));
|
||||
Assert.AreEqual(audio, result.HasAudio);
|
||||
Assert.IsNull(result.Note);
|
||||
Assert.AreEqual(0, result.Difference);
|
||||
Assert.AreEqual(StillVideoAnalyzer.Samples, result.Sampled);
|
||||
Assert.AreEqual(1, result.Algorithm);
|
||||
|
||||
// Seven equal parts of one second: the first one looked at is picture 2 (the nearest to 72 ms), never the very
|
||||
// first.
|
||||
Assert.AreEqual(Ms(2), result.FrameAtMs, "a parità di nitidezza il primo mostrato fra quelli guardati");
|
||||
Assert.AreEqual(new VideoAnalysis("abc", 1, VideoAnalysisOutcome.Still, Make.T0, result.FrameAt, null), result.ToAnalysis("abc", Make.T0));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void GrainIsNotMotion()
|
||||
{
|
||||
var photo = PcmVideos.Photo(2);
|
||||
var result = Analyse(PcmVideos.Mp4(30, i => PcmVideos.Noise(photo, 3, i)));
|
||||
Assert.AreEqual(VideoAnalysisOutcome.Still, result.Outcome, Describe(result));
|
||||
Assert.IsNull(result.Note, "la grana non è una parte che si muove");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void AFadeFromBlackIsStillAndTheFrameComesAfterIt()
|
||||
{
|
||||
// The first nine pictures fade in from black (picture 2, the first one looked at, at 22 %; picture 6 at 67 %);
|
||||
// the third one looked at is picture 11, the one nearest to 358 ms.
|
||||
var photo = PcmVideos.Photo(3);
|
||||
var result = Analyse(PcmVideos.Mp4(30, i => i < 9 ? PcmVideos.Fade(photo, i / 9.0) : photo));
|
||||
|
||||
Assert.AreEqual(VideoAnalysisOutcome.Still, result.Outcome, Describe(result));
|
||||
Assert.AreEqual(Ms(11), result.FrameAtMs, "il più nitido: il primo a piena luce, non uno della dissolvenza");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void AFadeToBlackAndBlackFramesAtBothEndsLeaveItStill()
|
||||
{
|
||||
var photo = PcmVideos.Photo(4);
|
||||
var fadeOut = Analyse(PcmVideos.Mp4(30, i => i >= 21 ? PcmVideos.Fade(photo, (29 - i) / 9.0) : photo));
|
||||
Assert.AreEqual(VideoAnalysisOutcome.Still, fadeOut.Outcome, Describe(fadeOut));
|
||||
Assert.IsLessThan(Ms(21), fadeOut.FrameAtMs!.Value);
|
||||
|
||||
var black = Analyse(PcmVideos.Mp4(42, i => i is < 8 or >= 34 ? PcmVideos.Black() : photo));
|
||||
Assert.AreEqual(VideoAnalysisOutcome.Still, black.Outcome, Describe(black));
|
||||
Assert.IsGreaterThanOrEqualTo(Ms(8), black.FrameAtMs!.Value);
|
||||
Assert.IsLessThan(Ms(34), black.FrameAtMs.Value);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void BlackBetweenTwoPicturesIsMotion()
|
||||
{
|
||||
var photo = PcmVideos.Photo(5);
|
||||
var result = Analyse(PcmVideos.Mp4(30, i => i is >= 12 and < 18 ? PcmVideos.Black() : photo));
|
||||
Assert.AreEqual(VideoAnalysisOutcome.Moving, result.Outcome, Describe(result));
|
||||
Assert.IsNull(result.FrameAt);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void MotionIsMotion()
|
||||
{
|
||||
// The demo's moving gradient, a slow pan of a photo (2 pixels a picture) and a slideshow of two photos.
|
||||
using (var demo = new MemoryStream(H264PcmWriter.DemoVideo()))
|
||||
{
|
||||
var gradient = StillVideoAnalyzer.Analyse(demo, CancellationToken.None);
|
||||
Assert.AreEqual(VideoAnalysisOutcome.Moving, gradient.Outcome, Describe(gradient));
|
||||
}
|
||||
|
||||
var photo = PcmVideos.Photo(6);
|
||||
var pan = Analyse(PcmVideos.Mp4(30, i => PcmVideos.Shift(photo, 2 * i)));
|
||||
Assert.AreEqual(VideoAnalysisOutcome.Moving, pan.Outcome, Describe(pan));
|
||||
Assert.IsLessThan(StillVideoAnalyzer.Samples, pan.Sampled, "la prima coppia che si muove basta");
|
||||
|
||||
var other = PcmVideos.Photo(7);
|
||||
var slideshow = Analyse(PcmVideos.Mp4(30, i => i < 15 ? photo : other));
|
||||
Assert.AreEqual(VideoAnalysisOutcome.Moving, slideshow.Outcome, Describe(slideshow));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void ASmallStickerThatMovesLeavesTheVideoStill()
|
||||
{
|
||||
// 16 × 24 and 24 × 40 pixels (1 % and 2,6 % of the picture) crossing the photo, and 28 × 48 (3,6 %) animated in
|
||||
// place.
|
||||
var photo = PcmVideos.Photo(8);
|
||||
var crossing = Analyse(PcmVideos.Mp4(30, i => PcmVideos.Sticker(photo, 4 * i, 100, 16, 24)));
|
||||
Assert.AreEqual(VideoAnalysisOutcome.Still, crossing.Outcome, Describe(crossing));
|
||||
Assert.AreEqual(VideoAnalysisNotes.SmallMotion, crossing.Note);
|
||||
Assert.IsGreaterThan(0, crossing.MovingArea);
|
||||
Assert.IsLessThanOrEqualTo(StillVideoAnalyzer.AreaThreshold, crossing.MovingArea);
|
||||
|
||||
var larger = Analyse(PcmVideos.Mp4(30, i => PcmVideos.Sticker(photo, 4 * i, 100, 24, 40)));
|
||||
Assert.AreEqual(VideoAnalysisOutcome.Still, larger.Outcome, Describe(larger));
|
||||
|
||||
var animated = Analyse(PcmVideos.Mp4(30, i => PcmVideos.Sticker(photo, 90, 20, 28, 48, i)));
|
||||
Assert.AreEqual(VideoAnalysisOutcome.Still, animated.Outcome, Describe(animated));
|
||||
Assert.AreEqual(VideoAnalysisNotes.SmallMotion, animated.Note);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void ALargeStickerThatMovesIsMotion()
|
||||
{
|
||||
// 48 × 80 pixels: 10 % of the picture.
|
||||
var photo = PcmVideos.Photo(9);
|
||||
var result = Analyse(PcmVideos.Mp4(30, i => PcmVideos.Sticker(photo, 3 * i, 90, 48, 80)));
|
||||
Assert.AreEqual(VideoAnalysisOutcome.Moving, result.Outcome, Describe(result));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void AThinMovingCaptionLeavesTheVideoStillAndAWideOneMoves()
|
||||
{
|
||||
// One row of blocks (8 pixels of 256, 3 %) of scrolling letters; then a band of a quarter of the picture.
|
||||
var photo = PcmVideos.Photo(10);
|
||||
var thin = Analyse(PcmVideos.Mp4(30, i => PcmVideos.Caption(photo, 232, 8, 5 * i)));
|
||||
Assert.AreEqual(VideoAnalysisOutcome.Still, thin.Outcome, Describe(thin));
|
||||
Assert.AreEqual(VideoAnalysisNotes.SmallMotion, thin.Note);
|
||||
|
||||
var wide = Analyse(PcmVideos.Mp4(30, i => PcmVideos.Caption(photo, 160, 64, 5 * i)));
|
||||
Assert.AreEqual(VideoAnalysisOutcome.Moving, wide.Outcome, Describe(wide));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void VeryShortClipsAreAnalysedFrameByFrame()
|
||||
{
|
||||
// 0,4 seconds: 12 pictures.
|
||||
var photo = PcmVideos.Photo(11);
|
||||
var same = Analyse(PcmVideos.Mp4(12, _ => photo));
|
||||
Assert.AreEqual(VideoAnalysisOutcome.Still, same.Outcome, Describe(same));
|
||||
Assert.AreEqual(StillVideoAnalyzer.Samples, same.Sampled);
|
||||
|
||||
var other = PcmVideos.Photo(12);
|
||||
var changing = Analyse(PcmVideos.Mp4(12, i => i < 6 ? photo : other));
|
||||
Assert.AreEqual(VideoAnalysisOutcome.Moving, changing.Outcome, Describe(changing));
|
||||
|
||||
// Two pictures in all: both are looked at.
|
||||
var two = Analyse(PcmVideos.Mp4(2, i => i == 0 ? photo : other));
|
||||
Assert.AreEqual(VideoAnalysisOutcome.Moving, two.Outcome, Describe(two));
|
||||
Assert.AreEqual(2, two.Sampled);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void AVideoOfOnePictureIsThatPicture()
|
||||
{
|
||||
var result = Analyse(PcmVideos.Mp4(1, _ => PcmVideos.Photo(13), audio: true));
|
||||
Assert.AreEqual(VideoAnalysisOutcome.Still, result.Outcome, Describe(result));
|
||||
Assert.AreEqual(0L, result.FrameAtMs);
|
||||
Assert.AreEqual(1, result.Sampled);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void AllBlackAndAllOneColourAreNotAnalysable()
|
||||
{
|
||||
var black = Analyse(PcmVideos.Mp4(30, _ => PcmVideos.Black(), audio: true));
|
||||
Assert.AreEqual(VideoAnalysisOutcome.NotAnalyzable, black.Outcome, Describe(black));
|
||||
Assert.AreEqual(VideoAnalysisNotes.AllDark, black.Note);
|
||||
Assert.IsNull(black.FrameAt);
|
||||
|
||||
var nearlyBlack = Analyse(PcmVideos.Mp4(30, i => PcmVideos.Noise(PcmVideos.Flat(24), 4, i)));
|
||||
Assert.AreEqual(VideoAnalysisNotes.AllDark, nearlyBlack.Note, Describe(nearlyBlack));
|
||||
|
||||
var oneBlack = Analyse(PcmVideos.Mp4(1, _ => PcmVideos.Black()));
|
||||
Assert.AreEqual(VideoAnalysisNotes.AllDark, oneBlack.Note, Describe(oneBlack));
|
||||
|
||||
var red = PcmVideos.Flat(81, 90, 240);
|
||||
var single = Analyse(PcmVideos.Mp4(30, _ => red));
|
||||
Assert.AreEqual(VideoAnalysisOutcome.NotAnalyzable, single.Outcome, Describe(single));
|
||||
Assert.AreEqual(VideoAnalysisNotes.SingleColor, single.Note);
|
||||
|
||||
// A muted colour (a saturated one clips at white, and a fade of it cannot be undone).
|
||||
var brick = PcmVideos.Flat(110, 110, 170);
|
||||
var fading = Analyse(PcmVideos.Mp4(30, i => i < 9 ? PcmVideos.Fade(brick, i / 9.0) : PcmVideos.Noise(brick, 2, i)));
|
||||
Assert.AreEqual(VideoAnalysisNotes.SingleColor, fading.Note, Describe(fading));
|
||||
|
||||
// One colour after another: the picture changes.
|
||||
var blue = PcmVideos.Flat(41, 240, 110);
|
||||
var changing = Analyse(PcmVideos.Mp4(30, i => i < 15 ? red : blue));
|
||||
Assert.AreEqual(VideoAnalysisOutcome.Moving, changing.Outcome, Describe(changing));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TheSharpestFrameIsChosen()
|
||||
{
|
||||
// Every picture softened but picture 15 (the fourth looked at): the cells are the same, the detail is not.
|
||||
var photo = PcmVideos.Photo(14);
|
||||
var soft = PcmVideos.Blur(photo);
|
||||
var result = Analyse(PcmVideos.Mp4(30, i => i == 15 ? photo : soft));
|
||||
Assert.AreEqual(VideoAnalysisOutcome.Still, result.Outcome, Describe(result));
|
||||
Assert.AreEqual(Ms(15), result.FrameAtMs);
|
||||
Assert.IsGreaterThan(0, result.Sharpness);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[DataRow(90)]
|
||||
[DataRow(270)]
|
||||
public void RotatedVideosAreAnalysedUpright(int rotation)
|
||||
{
|
||||
var photo = PcmVideos.Photo(15);
|
||||
var data = PcmVideos.Mp4(30, _ => photo, rotation: rotation);
|
||||
var still = Analyse(data);
|
||||
Assert.AreEqual(VideoAnalysisOutcome.Still, still.Outcome, Describe(still));
|
||||
Assert.AreEqual(rotation, still.Rotation);
|
||||
|
||||
// The chosen instant gives the frame upright, as «Salva il fotogramma» will save it.
|
||||
using var stream = new MemoryStream(data);
|
||||
using var reader = VideoFrameReader.Open(stream, out _);
|
||||
using var frame = reader.Decode(reader.Locate([still.FrameAt!.Value]), CancellationToken.None).Single();
|
||||
Assert.AreEqual((PcmVideos.Height, PcmVideos.Width), (frame.Image.Width, frame.Image.Height));
|
||||
Assert.AreEqual(still.FrameAtMs, ExportFrames.ActualMs(frame.Actual));
|
||||
|
||||
var moving = Analyse(PcmVideos.Mp4(30, i => PcmVideos.Shift(photo, 3 * i), rotation: rotation));
|
||||
Assert.AreEqual(VideoAnalysisOutcome.Moving, moving.Outcome, Describe(moving));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TheSameVideoGivesTheSameResult()
|
||||
{
|
||||
var photo = PcmVideos.Photo(16);
|
||||
var data = PcmVideos.Mp4(30, i => PcmVideos.Noise(photo, 3, i));
|
||||
Assert.AreEqual(Analyse(data), Analyse(data));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TheInstantIsTheShownTimeAfterAnEmptyEdit()
|
||||
{
|
||||
// A QuickTime file whose video starts half a second late (an empty edit), as some phones write it.
|
||||
var photo = PcmVideos.Photo(17);
|
||||
var es = PcmVideos.Stream("pcm", 30, _ => photo);
|
||||
var result = Analyse(TestVideos.Mov(es, new MovOptions(VideoEmptyEdit: TestVideos.Timescale / 2)));
|
||||
Assert.AreEqual(VideoAnalysisOutcome.Still, result.Outcome, Describe(result));
|
||||
Assert.IsGreaterThanOrEqualTo(500L, result.FrameAtMs!.Value);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void ConformanceStreamsOfAStillPictureAndOfMotion()
|
||||
{
|
||||
var still = Analyse(TestVideos.Mp4(ElementaryStream.Load("BA1_Sony_D").FirstPictureRepeated(90)));
|
||||
Assert.AreEqual(VideoAnalysisOutcome.Still, still.Outcome, Describe(still));
|
||||
Assert.AreEqual(0, still.Difference);
|
||||
|
||||
foreach (var name in new[] { "CABA3_SVA_B", "FRExt1_Panasonic_D" })
|
||||
{
|
||||
var moving = Analyse(TestVideos.Mp4(ElementaryStream.Load(name)));
|
||||
Assert.AreEqual(VideoAnalysisOutcome.Moving, moving.Outcome, $"{name}: {Describe(moving)}");
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void HevcVideosOfAStillPictureAndOfMotion()
|
||||
{
|
||||
var still = Analyse(TestVideos.Mp4(ElementaryStream.LoadHevc("INITQP_A_Sony_1").FirstPictureRepeated(90)));
|
||||
Assert.AreEqual(VideoAnalysisOutcome.Still, still.Outcome, Describe(still));
|
||||
Assert.AreEqual(0, still.Difference);
|
||||
|
||||
var moving = Analyse(TestVideos.Matroska(ElementaryStream.LoadHevc("CAINIT_A_SHARP_4")));
|
||||
Assert.AreEqual(VideoAnalysisOutcome.Moving, moving.Outcome, Describe(moving));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task UnreadableVideosAreNotAnalysableAndNeverThrow()
|
||||
{
|
||||
Assert.AreEqual(VideoAnalysisNotes.FrameNotAvailable, Analyse(new byte[4096]).Note);
|
||||
byte[] junk = [0, 0, 0, 16, .. "ftypisom"u8, 0, 0, 0, 0, 0, 0, 0, 9, .. "mdat"u8, 1];
|
||||
Assert.AreEqual(VideoAnalysisNotes.FrameNotAvailable, Analyse(junk).Note);
|
||||
|
||||
// A codec Febe does not decode.
|
||||
var vp9 = Analyse(TestVideos.Matroska(ElementaryStream.Load("BA1_Sony_D"), codecId: "V_VP9"));
|
||||
Assert.AreEqual(VideoAnalysisOutcome.NotAnalyzable, vp9.Outcome);
|
||||
Assert.AreEqual(VideoAnalysisNotes.FrameNotAvailable, vp9.Note);
|
||||
|
||||
// Cut short anywhere: never an exception, and never «Fermo» from frames that are not there.
|
||||
var whole = PcmVideos.Mp4(30, _ => PcmVideos.Photo(18));
|
||||
foreach (var length in new[] { whole.Length / 10, whole.Length / 2, whole.Length - 1000 })
|
||||
{
|
||||
var cut = Analyse(whole[..length]);
|
||||
Assert.AreNotEqual(VideoAnalysisOutcome.Moving, cut.Outcome, $"{length}: {Describe(cut)}");
|
||||
}
|
||||
|
||||
using var temp = new TempFolder("fermo-illeggibile");
|
||||
var missing = await StillVideoAnalyzer.AnalyseAsync(temp.Combine("non-esiste.mp4"), TimeSpan.FromSeconds(30));
|
||||
Assert.AreEqual(VideoAnalysisNotes.Unreadable, missing.Note);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task PastTheBudgetItIsTooSlowButTheCallerCanStillCancel()
|
||||
{
|
||||
var data = PcmVideos.Mp4(30, _ => PcmVideos.Photo(19));
|
||||
using (var stream = new MemoryStream(data))
|
||||
{
|
||||
var late = StillVideoAnalyzer.Analyse(stream, TimeSpan.Zero, CancellationToken.None);
|
||||
Assert.AreEqual(VideoAnalysisOutcome.NotAnalyzable, late.Outcome);
|
||||
Assert.AreEqual(VideoAnalysisNotes.TooSlow, late.Note);
|
||||
Assert.AreEqual(0, late.Sampled, "un tempo zero annulla subito");
|
||||
}
|
||||
|
||||
using var temp = new TempFolder("fermo-tempo");
|
||||
var path = TestVideos.Write(temp, "video.mp4", data);
|
||||
Assert.AreEqual(VideoAnalysisOutcome.Still, (await StillVideoAnalyzer.AnalyseAsync(path, TimeSpan.FromMinutes(2))).Outcome);
|
||||
|
||||
using var cancelled = new CancellationTokenSource();
|
||||
await cancelled.CancelAsync();
|
||||
await Assert.ThrowsAsync<OperationCanceledException>(() => StillVideoAnalyzer.AnalyseAsync(path, TimeSpan.FromSeconds(30), cancelled.Token));
|
||||
using var again = new MemoryStream(data);
|
||||
Assert.ThrowsExactly<OperationCanceledException>(() => StillVideoAnalyzer.Analyse(again, TimeSpan.FromSeconds(30), cancelled.Token));
|
||||
}
|
||||
|
||||
private static StillVideoResult Analyse(byte[] video)
|
||||
{
|
||||
using var stream = new MemoryStream(video);
|
||||
return StillVideoAnalyzer.Analyse(stream, CancellationToken.None);
|
||||
}
|
||||
|
||||
private static string Describe(StillVideoResult r) =>
|
||||
$"{r.Outcome} nota {r.Note ?? "-"} istante {r.FrameAtMs?.ToString(System.Globalization.CultureInfo.InvariantCulture) ?? "-"} " +
|
||||
$"guardati {r.Sampled} differenza {r.Difference} area {r.MovingArea} nitidezza {r.Sharpness}";
|
||||
}
|
||||
@@ -7,7 +7,7 @@ using Febe.Tests.Support;
|
||||
|
||||
namespace Febe.Tests.Codecs.Containers;
|
||||
|
||||
/// <summary>The in-house frame decoder for thumbnails, and the recognition of videos of a still picture.</summary>
|
||||
/// <summary>The in-house frame decoder for thumbnails (still videos: <see cref="StillVideoAnalyzerTests"/>).</summary>
|
||||
[TestClass]
|
||||
public sealed class VideoFrameDecoderTests
|
||||
{
|
||||
@@ -144,32 +144,6 @@ public sealed class VideoFrameDecoderTests
|
||||
CollectionAssert.AreEqual(rgb[..3], rgb[3..6], "la riga in alto è uniforme");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task AVideoOfAStillPictureIsRecognised()
|
||||
{
|
||||
var es = ElementaryStream.Load("BA1_Sony_D");
|
||||
using var temp = new TempFolder("fermo");
|
||||
var still = TestVideos.Write(temp, "fermo.mp4", TestVideos.Mp4(es.FirstPictureRepeated(90)));
|
||||
var result = await VideoFrameDecoder.Instance.AnalyseStillnessAsync(still);
|
||||
Assert.IsNotNull(result);
|
||||
Assert.IsTrue(result.IsStill);
|
||||
Assert.IsTrue(result.SampledFrames >= 2);
|
||||
Assert.AreEqual(0, result.Difference);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[DataRow("CABA3_SVA_B")]
|
||||
[DataRow("FRExt1_Panasonic_D")]
|
||||
public async Task AVideoThatMovesIsNotStill(string name)
|
||||
{
|
||||
var es = ElementaryStream.Load(name);
|
||||
using var temp = new TempFolder("movimento");
|
||||
var path = TestVideos.Write(temp, "video.mp4", TestVideos.Mp4(es));
|
||||
var result = await VideoFrameDecoder.Instance.AnalyseStillnessAsync(path);
|
||||
Assert.IsNotNull(result);
|
||||
Assert.IsFalse(result.IsStill, $"differenza {result.Difference}");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task AFrameFarFromWhereDecodingCanStartGivesWayToTheFrameThere()
|
||||
{
|
||||
@@ -182,7 +156,6 @@ public sealed class VideoFrameDecoderTests
|
||||
var decoder = new VideoFrameDecoder(VideoFrameDecoder.DefaultBudget, maxRun: 5);
|
||||
var image = await decoder.DecodeFrameAsync(path, TimeSpan.FromSeconds(1));
|
||||
CollectionAssert.AreEqual(VideoFrameDecoder.ToImage(DecodedFrame(es, 0), 0, 0).Rgb, image!.Rgb);
|
||||
Assert.IsNotNull(await decoder.AnalyseStillnessAsync(path), "anche l'analisi resta limitata e risponde");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
@@ -193,7 +166,6 @@ public sealed class VideoFrameDecoderTests
|
||||
var path = TestVideos.Write(temp, "video.mp4", TestVideos.Mp4(es));
|
||||
var late = new VideoFrameDecoder(TimeSpan.Zero, maxRun: 300);
|
||||
Assert.IsNull(await late.DecodeFrameAsync(path, TimeSpan.FromSeconds(1)), "oltre il tempo concesso: nessun fotogramma");
|
||||
Assert.IsNull(await late.AnalyseStillnessAsync(path));
|
||||
|
||||
// A cancellation asked by the caller is not a missing frame: it stays a cancellation.
|
||||
using var cancelled = new CancellationTokenSource();
|
||||
@@ -242,7 +214,6 @@ public sealed class VideoFrameDecoderTests
|
||||
using var temp = new TempFolder("illeggibile");
|
||||
var junk = TestVideos.Write(temp, "rotto.mp4", [0, 0, 0, 16, .. "ftypisom"u8, 0, 0, 0, 0, 0, 0, 0, 9, .. "mdat"u8, 1]);
|
||||
Assert.IsNull(await VideoFrameDecoder.Instance.ExtractImageAsync(junk));
|
||||
Assert.IsNull(await VideoFrameDecoder.Instance.AnalyseStillnessAsync(junk));
|
||||
Assert.IsNull(await VideoFrameDecoder.Instance.ExtractImageAsync(temp.Combine("non-esiste.mkv")));
|
||||
}
|
||||
|
||||
|
||||
@@ -85,6 +85,29 @@ public sealed class VideoFramesTests
|
||||
CollectionAssert.AreEqual(first.Select(t => t.Sample).ToArray(), again.Select(t => t.Sample).ToArray());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void NearAKeyFrameTheKeyFrameIsTaken()
|
||||
{
|
||||
// CABA3_SVA_B has one IDR picture, at the start: only an instant within reach of it moves there.
|
||||
var es = ElementaryStream.Load("CABA3_SVA_B");
|
||||
using var stream = new MemoryStream(TestVideos.Mp4(es));
|
||||
using var reader = VideoFrameReader.Open(stream, out _);
|
||||
TimeSpan[] instants = [TimeSpan.FromMilliseconds(60), TimeSpan.FromMilliseconds(500)];
|
||||
var exact = reader.Locate(instants);
|
||||
var near = reader.LocateNearKey(instants, TimeSpan.FromMilliseconds(100));
|
||||
Assert.AreEqual(0, near[0].Sample);
|
||||
Assert.AreEqual(TimeSpan.Zero, near[0].Actual);
|
||||
Assert.AreEqual(exact[1], near[1], "nessun fotogramma chiave vicino: quello mostrato all'istante");
|
||||
CollectionAssert.AreEqual(exact.ToArray(), reader.LocateNearKey(instants, TimeSpan.Zero).ToArray());
|
||||
|
||||
// Every picture a key frame: the one shown nearest, also after the instant (the earlier of two as near).
|
||||
using var pcm = new MemoryStream(PcmVideos.Mp4(30, _ => PcmVideos.Photo()));
|
||||
using var all = VideoFrameReader.Open(pcm, out _);
|
||||
var nearest = all.LocateNearKey([TimeSpan.FromMilliseconds(358), TimeSpan.FromMilliseconds(50)], TimeSpan.FromMilliseconds(40));
|
||||
Assert.AreEqual((11, 1), (nearest[0].Sample, nearest[1].Sample));
|
||||
Assert.AreEqual(1, nearest[1].Index);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void RotationIsApplied()
|
||||
{
|
||||
|
||||
Reference in new issue
Block a user