merge: deep analysis, advisor and sequence presets
This commit is contained in:
24 files changed
+3979
No files matched your search
@@ -0,0 +1,107 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<root>
|
||||
<resheader name="resmimetype"><value>text/microsoft-resx</value></resheader>
|
||||
<resheader name="version"><value>2.0</value></resheader>
|
||||
<resheader name="reader"><value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value></resheader>
|
||||
<resheader name="writer"><value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value></resheader>
|
||||
<data name="Advisor.Finding.BlackFrames" xml:space="preserve"><value>{0} frames are black (lens cap or missed exposure).</value><comment>{0} frame count</comment></data>
|
||||
<data name="Advisor.Finding.CameraChanged" xml:space="preserve"><value>The camera body changes {0} times.</value><comment>{0} change count</comment></data>
|
||||
<data name="Advisor.Finding.ClockJumps" xml:space="preserve"><value>The camera clock jumps {0} times (largest jump {1:0} s).</value><comment>{0} jump count; {1} largest jump in seconds, signed</comment></data>
|
||||
<data name="Advisor.Finding.Clouds" xml:space="preserve"><value>Clouds cover about {0:0}% of the sky on average.</value><comment>{0} mean cloud coverage in percent</comment></data>
|
||||
<data name="Advisor.Finding.DayNightTransition" xml:space="preserve"><value>Covers day and night: {0} day, {1} twilight and {2} night frames.</value><comment>{0} day frames; {1} twilight frames; {2} night frames</comment></data>
|
||||
<data name="Advisor.Finding.DuplicateFrames" xml:space="preserve"><value>{0} frames repeat the previous frame.</value><comment>{0} frame count</comment></data>
|
||||
<data name="Advisor.Finding.DuplicateTimestamps" xml:space="preserve"><value>{0} frames share their capture time with the previous frame.</value><comment>{0} frame count</comment></data>
|
||||
<data name="Advisor.Finding.ExposureSteps" xml:space="preserve"><value>{0} exposure changes, typically {1:0} frames apart, {2:+0.0;-0.0;0} EV in total.</value><comment>{0} step count; {1} median frames between steps (0 with one step); {2} summed camera EV change</comment></data>
|
||||
<data name="Advisor.Finding.Flicker" xml:space="preserve"><value>Brightness flickers by {0:0.###} EV around its smooth course.</value><comment>{0} RMS flicker in EV</comment></data>
|
||||
<data name="Advisor.Finding.Gaps" xml:space="preserve"><value>{0} gaps in the cadence; the longest lasts {1:0} s.</value><comment>{0} gap count; {1} longest gap in seconds</comment></data>
|
||||
<data name="Advisor.Finding.IrregularInterval" xml:space="preserve"><value>Intervals vary by {0:0.##} s around {1:0.##} s.</value><comment>{0} interval jitter (median absolute deviation) in seconds; {1} median interval in seconds</comment></data>
|
||||
<data name="Advisor.Finding.LensChanged" xml:space="preserve"><value>The lens changes {0} times.</value><comment>{0} change count</comment></data>
|
||||
<data name="Advisor.Finding.MissingExposure" xml:space="preserve"><value>{0} frames have no shutter time or aperture in their metadata.</value><comment>{0} frame count</comment></data>
|
||||
<data name="Advisor.Finding.MixedOrientation" xml:space="preserve"><value>{0} frames have a different orientation.</value><comment>{0} frame count</comment></data>
|
||||
<data name="Advisor.Finding.MixedResolution" xml:space="preserve"><value>{0} frames differ from the main size {1}×{2}.</value><comment>{0} frame count; {1} main width in pixels; {2} main height in pixels</comment></data>
|
||||
<data name="Advisor.Finding.NoTimestamps" xml:space="preserve"><value>Only {0} of {1} frames have a capture time, so cadence and gaps cannot be measured.</value><comment>{0} frames with a capture time; {1} frames in total</comment></data>
|
||||
<data name="Advisor.Finding.NonMonotonicTimestamps" xml:space="preserve"><value>{0} frames are out of time order.</value><comment>{0} frame count</comment></data>
|
||||
<data name="Advisor.Finding.Panning" xml:space="preserve"><value>The view drifts by {0:0.##} px per frame (pan or slider).</value><comment>{0} drift in source pixels per frame</comment></data>
|
||||
<data name="Advisor.Finding.SceneChanges" xml:space="preserve"><value>The view jumps at {0} frames (camera moved or bumped).</value><comment>{0} frame count</comment></data>
|
||||
<data name="Advisor.Finding.Sessions" xml:space="preserve"><value>Shot in {0} separate sessions.</value><comment>{0} session count</comment></data>
|
||||
<data name="Advisor.Finding.Shake" xml:space="preserve"><value>The camera shakes by {0:0.##} px RMS; hiding it costs {1:0.#}% of the frame.</value><comment>{0} shake RMS in source pixels; {1} crop cost in percent of the area</comment></data>
|
||||
<data name="Advisor.Finding.StarField" xml:space="preserve"><value>Stars are visible on {0} frames.</value><comment>{0} frame count</comment></data>
|
||||
<data name="Advisor.Finding.StepsNotReceived" xml:space="preserve"><value>{0} logged exposure changes never reached the pixels.</value><comment>{0} step count</comment></data>
|
||||
<data name="Advisor.Finding.TimeZoneEstimated" xml:space="preserve"><value>No time zone recorded; a UTC offset of {0} min was estimated from the longitude.</value><comment>{0} UTC offset in minutes</comment></data>
|
||||
<data name="Advisor.Finding.UnreadableFrames" xml:space="preserve"><value>{0} frames could not be decoded.</value><comment>{0} frame count</comment></data>
|
||||
<data name="Advisor.Finding.WhiteBalanceJitter" xml:space="preserve"><value>Colour balance jumps by {0:0.#}% between frames.</value><comment>{0} RMS colour-ratio jitter in percent</comment></data>
|
||||
<data name="Advisor.Finding.WhiteFrames" xml:space="preserve"><value>{0} frames are blown out to white.</value><comment>{0} frame count</comment></data>
|
||||
<data name="Advisor.Missing.Deep" xml:space="preserve"><value>Needs the deep analysis of the pixels, which has not run yet; nothing was changed.</value><comment>no placeholders</comment></data>
|
||||
<data name="Advisor.Missing.Exposure" xml:space="preserve"><value>Shutter time or aperture is missing from the metadata, so this cannot be decided; nothing was changed.</value><comment>no placeholders</comment></data>
|
||||
<data name="Advisor.Missing.Motion" xml:space="preserve"><value>Too few frame pairs to measure motion; nothing was changed.</value><comment>no placeholders</comment></data>
|
||||
<data name="Advisor.Missing.Shake" xml:space="preserve"><value>Shake was measurable on only {0}% of the frames (too little texture); nothing was changed.</value><comment>{0} percent of frame pairs with a measured shift</comment></data>
|
||||
<data name="Advisor.Missing.SourceSize" xml:space="preserve"><value>The source resolution is unknown; nothing was changed.</value><comment>no placeholders</comment></data>
|
||||
<data name="Advisor.Missing.Timestamps" xml:space="preserve"><value>Only {0} of {1} frames have a capture time, so this cannot be measured; nothing was changed.</value><comment>{0} frames with a capture time; {1} frames in total</comment></data>
|
||||
<data name="Advisor.Preset.Construction" xml:space="preserve"><value>Construction cam — {0} {1} {2} fps, adaptive timing</value><comment>{0} resolution label such as 1080p; {1} codec label such as H.264; {2} frame rate</comment></data>
|
||||
<data name="Advisor.Preset.HolyGrail" xml:space="preserve"><value>Holy grail sunset — {0} {1} {2} fps, transitions {3}</value><comment>{0} resolution label such as 4K; {1} codec label such as HEVC; {2} frame rate; {3} transition length in frames</comment></data>
|
||||
<data name="Advisor.Preset.NightSky" xml:space="preserve"><value>Night sky — {0} {1} {2} fps, deflicker {3}</value><comment>{0} resolution label such as 4K; {1} codec label such as HEVC Main10; {2} frame rate; {3} deflicker window in frames</comment></data>
|
||||
<data name="Advisor.Preset.NightSkyStabilised" xml:space="preserve"><value>Night sky — {0} {1} {2} fps, deflicker {3}, stabilise</value><comment>{0} resolution label such as 4K; {1} codec label such as HEVC Main10; {2} frame rate; {3} deflicker window in frames</comment></data>
|
||||
<data name="Advisor.Preset.SocialVertical" xml:space="preserve"><value>Social vertical {0}×{1}</value><comment>{0} width in pixels; {1} height in pixels</comment></data>
|
||||
<data name="Advisor.Preset.Standard" xml:space="preserve"><value>Standard — {0} {1} {2} fps</value><comment>{0} resolution label such as 1080p; {1} codec label such as H.264; {2} frame rate</comment></data>
|
||||
<data name="Advisor.PresetReason.Construction" xml:space="preserve"><value>{0} sessions over {1} days with pauses: adaptive timing in a widely compatible 1080p file.</value><comment>{0} session count; {1} capture span in days</comment></data>
|
||||
<data name="Advisor.PresetReason.HolyGrail" xml:space="preserve"><value>{0} exposure steps across a {1} EV change of light: smooth day-to-night transitions.</value><comment>{0} received step count; {1} change of scene brightness in EV</comment></data>
|
||||
<data name="Advisor.PresetReason.NightSky" xml:space="preserve"><value>Stars or a dark sky on {0}% of the frames: dark gradients need 10 bits and steady brightness.</value><comment>{0} percent of frames with stars, or of dark frames</comment></data>
|
||||
<data name="Advisor.PresetReason.SocialVertical" xml:space="preserve"><value>A 9:16 crop for phones and social feeds.</value><comment>no placeholders</comment></data>
|
||||
<data name="Advisor.PresetReason.Standard" xml:space="preserve"><value>General settings for this sequence.</value><comment>no placeholders</comment></data>
|
||||
<data name="Advisor.Reason.Aspect.Landscape" xml:space="preserve"><value>The {0}×{1} source cropped to 16:9 keeps {2}% of its height.</value><comment>{0} source width in pixels; {1} source height in pixels; {2} kept height in percent</comment></data>
|
||||
<data name="Advisor.Reason.Aspect.Native" xml:space="preserve"><value>The source is already 16:9.</value><comment>no placeholders</comment></data>
|
||||
<data name="Advisor.Reason.Aspect.Portrait" xml:space="preserve"><value>Portrait source: 9:16 fills a phone screen.</value><comment>no placeholders</comment></data>
|
||||
<data name="Advisor.Reason.Aspect.Wide" xml:space="preserve"><value>The {0}×{1} source cropped to 16:9 keeps {2}% of its width.</value><comment>{0} source width in pixels; {1} source height in pixels; {2} kept width in percent</comment></data>
|
||||
<data name="Advisor.Reason.Deflicker.Off" xml:space="preserve"><value>Flicker is {0} EV, below the visible 0.02 EV: deflicker stays off.</value><comment>{0} RMS flicker in EV</comment></data>
|
||||
<data name="Advisor.Reason.Deflicker.On" xml:space="preserve"><value>Brightness deviates by {0} EV from its smooth course: deflicker removes the flicker.</value><comment>{0} RMS flicker in EV</comment></data>
|
||||
<data name="Advisor.Reason.Exclude" xml:space="preserve"><value>{0} black, white, duplicate or unreadable frames would flash or stutter in the video: excluded.</value><comment>{0} frame count</comment></data>
|
||||
<data name="Advisor.Reason.Export.Night" xml:space="preserve"><value>Night sky: 10-bit HEVC keeps dark gradients free of banding.</value><comment>no placeholders</comment></data>
|
||||
<data name="Advisor.Reason.Export.Standard" xml:space="preserve"><value>Best preset for a {0}×{1} output with the available encoders.</value><comment>{0} output width in pixels; {1} output height in pixels</comment></data>
|
||||
<data name="Advisor.Reason.Export.Vertical" xml:space="preserve"><value>Portrait framing: vertical 1080×1920 for phones.</value><comment>no placeholders</comment></data>
|
||||
<data name="Advisor.Reason.FitToSeconds" xml:space="preserve"><value>The plan is scaled so the {0} frames last {1} s at {2} fps.</value><comment>{0} frame count; {1} target duration in seconds; {2} frame rate</comment></data>
|
||||
<data name="Advisor.Reason.Flow.Balanced" xml:space="preserve"><value>Balanced flow quality is enough for motion blur and previews.</value><comment>no placeholders</comment></data>
|
||||
<data name="Advisor.Reason.Flow.Best" xml:space="preserve"><value>Interpolated frames need per-pixel motion: best flow quality.</value><comment>no placeholders</comment></data>
|
||||
<data name="Advisor.Reason.FrameRate.Cinematic" xml:space="preserve"><value>Moderate motion ({0} px per frame): the 24 fps cinema rate gives a {1} s clip.</value><comment>{0} speed of moving content in output pixels per frame; {1} clip duration in seconds</comment></data>
|
||||
<data name="Advisor.Reason.FrameRate.Default" xml:space="preserve"><value>Slow or unmeasured motion: 30 fps gives a {0} s clip.</value><comment>{0} clip duration in seconds</comment></data>
|
||||
<data name="Advisor.Reason.FrameRate.FastMotion" xml:space="preserve"><value>Fast motion ({0} px per frame): 24 fps slows it down; the clip lasts {1} s.</value><comment>{0} speed of moving content in output pixels per frame; {1} clip duration in seconds</comment></data>
|
||||
<data name="Advisor.Reason.FrameRate.Fit" xml:space="preserve"><value>{0} frames fill {1} s best at {2} fps.</value><comment>{0} frame count; {1} target duration in seconds; {2} frame rate</comment></data>
|
||||
<data name="Advisor.Reason.FrameRate.Long" xml:space="preserve"><value>{0} frames: 60 fps keeps the clip to {1} s.</value><comment>{0} frame count; {1} clip duration in seconds</comment></data>
|
||||
<data name="Advisor.Reason.FrameRate.Sessions" xml:space="preserve"><value>Capture over several sessions: 30 fps gives a {0} s clip.</value><comment>{0} clip duration in seconds</comment></data>
|
||||
<data name="Advisor.Reason.FrameRate.Short" xml:space="preserve"><value>Only {0} frames: 24 fps keeps the clip {1} s long.</value><comment>{0} frame count; {1} clip duration in seconds</comment></data>
|
||||
<data name="Advisor.Reason.Framing.Horizon" xml:space="preserve"><value>The horizon sits {0}% from the top: the crop places it on the nearest third.</value><comment>{0} horizon position in percent of the source height</comment></data>
|
||||
<data name="Advisor.Reason.Hero" xml:space="preserve"><value>Frame {0} is sharp and well exposed, without clipped highlights.</value><comment>{0} frame number, counted from 1</comment></data>
|
||||
<data name="Advisor.Reason.HolyGrail.Metadata" xml:space="preserve"><value>{0} exposure changes in the metadata (pixels not checked yet): each is spread over a smooth transition.</value><comment>{0} logged step count</comment></data>
|
||||
<data name="Advisor.Reason.HolyGrail.None" xml:space="preserve"><value>Exposure settings never change: no transitions needed.</value><comment>no placeholders</comment></data>
|
||||
<data name="Advisor.Reason.HolyGrail.NotReceived" xml:space="preserve"><value>The camera logged {0} exposure changes but the pixels show none: no transitions needed.</value><comment>{0} logged step count</comment></data>
|
||||
<data name="Advisor.Reason.HolyGrail.Received" xml:space="preserve"><value>{0} exposure changes reached the pixels: each is spread over a smooth transition.</value><comment>{0} received step count</comment></data>
|
||||
<data name="Advisor.Reason.MotionBlur.Already" xml:space="preserve"><value>The exposure already gives a {0}° shutter angle, at least the {1}° target: no synthetic blur needed.</value><comment>{0} real shutter angle in degrees; {1} target angle in degrees</comment></data>
|
||||
<data name="Advisor.Reason.MotionBlur.Little" xml:space="preserve"><value>Content moves only {0} px per frame: blur would be invisible, so it stays off.</value><comment>{0} speed of moving content in output pixels per frame</comment></data>
|
||||
<data name="Advisor.Reason.MotionBlur.On" xml:space="preserve"><value>Real shutter angle {0}° and motion of {1} px per frame: blurring to {2}° adds {3} px trails that hide strobing.</value><comment>{0} real shutter angle in degrees; {1} speed of moving content in output pixels per frame; {2} target angle in degrees; {3} added trail in output pixels</comment></data>
|
||||
<data name="Advisor.Reason.Regions.Horizon" xml:space="preserve"><value>Horizon found with {0}% confidence: sky and land are deflickered separately.</value><comment>{0} mask confidence in percent</comment></data>
|
||||
<data name="Advisor.Reason.Regions.Luminance" xml:space="preserve"><value>Sky separated by brightness with {0}% confidence: sky and land are deflickered separately.</value><comment>{0} mask confidence in percent</comment></data>
|
||||
<data name="Advisor.Reason.Regions.Off" xml:space="preserve"><value>The sky/land split is only {0}% reliable: one curve for the whole frame is safer.</value><comment>{0} mask confidence in percent</comment></data>
|
||||
<data name="Advisor.Reason.Resolution.Codec" xml:space="preserve"><value>The {0} encoder handles at most {1}×{2}.</value><comment>{0} encoder name; {1} maximum width in pixels; {2} maximum height in pixels</comment></data>
|
||||
<data name="Advisor.Reason.Resolution.Preview" xml:space="preserve"><value>{0} frames decode only as {1}×{2} embedded previews, which cap the output.</value><comment>{0} frame count; {1} preview width in pixels; {2} preview height in pixels</comment></data>
|
||||
<data name="Advisor.Reason.Resolution.Source" xml:space="preserve"><value>Largest standard size within the {0}×{1} source.</value><comment>{0} source width in pixels; {1} source height in pixels</comment></data>
|
||||
<data name="Advisor.Reason.ShutterAngle" xml:space="preserve"><value>180° is the film look; the real shutter angle is {0}° ({1} s exposure every {2} s).</value><comment>{0} real shutter angle in degrees; {1} median exposure time in seconds; {2} median interval in seconds</comment></data>
|
||||
<data name="Advisor.Reason.Stabilize.HighCrop" xml:space="preserve"><value>Shake of {0} px at output size, but hiding it crops {1}% of the frame: check the framing.</value><comment>{0} shake RMS in output pixels; {1} crop cost in percent of the area</comment></data>
|
||||
<data name="Advisor.Reason.Stabilize.Off" xml:space="preserve"><value>Measured shake of {0} px at output size (0.3 px or less): the camera was steady.</value><comment>{0} shake RMS in output pixels</comment></data>
|
||||
<data name="Advisor.Reason.Stabilize.On" xml:space="preserve"><value>Measured shake of {0} px at output size (above 0.3 px): stabilisation crops {1}% of the frame area.</value><comment>{0} shake RMS in output pixels; {1} crop cost in percent of the area</comment></data>
|
||||
<data name="Advisor.Reason.Stabilize.Smoothing" xml:space="preserve"><value>Smoothing the camera path over {0} frames removes shake and keeps deliberate pans.</value><comment>{0} smoothing sigma in frames</comment></data>
|
||||
<data name="Advisor.Reason.Strength.Full" xml:space="preserve"><value>Strong flicker ({0} EV): every frame lands on the smooth curve.</value><comment>{0} RMS flicker in EV</comment></data>
|
||||
<data name="Advisor.Reason.Strength.Partial" xml:space="preserve"><value>Mild flicker ({0} EV): reliable frames keep 20% of their own variation.</value><comment>{0} RMS flicker in EV</comment></data>
|
||||
<data name="Advisor.Reason.Timing.Irregular" xml:space="preserve"><value>Intervals vary by {0} s around {1} s: adaptive timing follows the capture clock so motion stays even.</value><comment>{0} interval jitter in seconds; {1} median interval in seconds</comment></data>
|
||||
<data name="Advisor.Reason.Timing.ManyGaps" xml:space="preserve"><value>{0} gaps in the cadence: adaptive timing keeps the output pace true to capture time.</value><comment>{0} gap count</comment></data>
|
||||
<data name="Advisor.Reason.Timing.Regular" xml:space="preserve"><value>Steady {0} s interval (jitter {1} s): each photo becomes one video frame.</value><comment>{0} median interval in seconds; {1} jitter in seconds</comment></data>
|
||||
<data name="Advisor.Reason.Timing.Sessions" xml:space="preserve"><value>Shot in {0} sessions with pauses up to {1} h: adaptive timing keeps the pauses short and the pace even.</value><comment>{0} session count; {1} longest pause in hours</comment></data>
|
||||
<data name="Advisor.Reason.Timing.SparseGaps" xml:space="preserve"><value>{0} short gaps, but motion is unmeasured or fast: constant timing skips them cleanly.</value><comment>{0} gap count</comment></data>
|
||||
<data name="Advisor.Reason.Timing.SparseGapsSmooth" xml:space="preserve"><value>{0} short gaps and smooth motion ({1} px per frame): interpolated frames fill the gaps.</value><comment>{0} gap count; {1} speed of moving content in output pixels per frame</comment></data>
|
||||
<data name="Advisor.Reason.Transition.Single" xml:space="preserve"><value>A single exposure step: a {0}-frame transition keeps the change gentle.</value><comment>{0} transition length in frames</comment></data>
|
||||
<data name="Advisor.Reason.Transition.Spacing" xml:space="preserve"><value>Exposure steps are {0} frames apart: transitions of half that ({1} frames) never overlap.</value><comment>{0} median frames between steps; {1} transition length in frames</comment></data>
|
||||
<data name="Advisor.Reason.WhiteBalance.Off" xml:space="preserve"><value>Colour balance is steady ({0}% from frame to frame): no smoothing needed.</value><comment>{0} RMS colour-ratio jitter in percent</comment></data>
|
||||
<data name="Advisor.Reason.WhiteBalance.On" xml:space="preserve"><value>Colour balance jumps by {0}% from frame to frame: smoothing steadies it and keeps the slow drift.</value><comment>{0} RMS colour-ratio jitter in percent</comment></data>
|
||||
<data name="Advisor.Reason.Window.Correlation" xml:space="preserve"><value>Flicker stays correlated over {0} frames: a {1}-frame window spans four times that.</value><comment>{0} correlation length in frames; {1} window in frames</comment></data>
|
||||
<data name="Advisor.Reason.Window.Maximum" xml:space="preserve"><value>Flicker drifts over {0} frames: the window is capped at {1} frames so real changes of light survive.</value><comment>{0} flicker period or correlation length in frames; {1} window in frames</comment></data>
|
||||
<data name="Advisor.Reason.Window.Minimum" xml:space="preserve"><value>Flicker changes from frame to frame without a rhythm: the shortest robust window, {0} frames, removes it.</value><comment>{0} window in frames</comment></data>
|
||||
<data name="Advisor.Reason.Window.Period" xml:space="preserve"><value>Flicker repeats every {0} frames: a {1}-frame window averages four cycles.</value><comment>{0} flicker period in frames; {1} window in frames</comment></data>
|
||||
</root>
|
||||
@@ -0,0 +1,107 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<root>
|
||||
<resheader name="resmimetype"><value>text/microsoft-resx</value></resheader>
|
||||
<resheader name="version"><value>2.0</value></resheader>
|
||||
<resheader name="reader"><value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value></resheader>
|
||||
<resheader name="writer"><value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value></resheader>
|
||||
<data name="Advisor.Finding.BlackFrames" xml:space="preserve"><value>{0} fotogrammi sono neri (tappo sull'obiettivo o scatto mancato).</value></data>
|
||||
<data name="Advisor.Finding.CameraChanged" xml:space="preserve"><value>Il corpo macchina cambia {0} volte.</value></data>
|
||||
<data name="Advisor.Finding.ClockJumps" xml:space="preserve"><value>L'orologio della fotocamera salta {0} volte (salto maggiore {1:0} s).</value></data>
|
||||
<data name="Advisor.Finding.Clouds" xml:space="preserve"><value>Le nuvole coprono in media circa il {0:0}% del cielo.</value></data>
|
||||
<data name="Advisor.Finding.DayNightTransition" xml:space="preserve"><value>Copre giorno e notte: {0} fotogrammi di giorno, {1} al crepuscolo e {2} di notte.</value></data>
|
||||
<data name="Advisor.Finding.DuplicateFrames" xml:space="preserve"><value>{0} fotogrammi ripetono il precedente.</value></data>
|
||||
<data name="Advisor.Finding.DuplicateTimestamps" xml:space="preserve"><value>{0} fotogrammi hanno lo stesso orario di scatto del precedente.</value></data>
|
||||
<data name="Advisor.Finding.ExposureSteps" xml:space="preserve"><value>{0} cambi di esposizione, di solito ogni {1:0} fotogrammi, {2:+0.0;-0.0;0} EV in totale.</value></data>
|
||||
<data name="Advisor.Finding.Flicker" xml:space="preserve"><value>La luminosità sfarfalla di {0:0.###} EV attorno al suo andamento regolare.</value></data>
|
||||
<data name="Advisor.Finding.Gaps" xml:space="preserve"><value>{0} pause nella cadenza; la più lunga dura {1:0} s.</value></data>
|
||||
<data name="Advisor.Finding.IrregularInterval" xml:space="preserve"><value>Gli intervalli variano di {0:0.##} s attorno a {1:0.##} s.</value></data>
|
||||
<data name="Advisor.Finding.LensChanged" xml:space="preserve"><value>L'obiettivo cambia {0} volte.</value></data>
|
||||
<data name="Advisor.Finding.MissingExposure" xml:space="preserve"><value>{0} fotogrammi non hanno tempo di scatto o diaframma nei metadati.</value></data>
|
||||
<data name="Advisor.Finding.MixedOrientation" xml:space="preserve"><value>{0} fotogrammi hanno un orientamento diverso.</value></data>
|
||||
<data name="Advisor.Finding.MixedResolution" xml:space="preserve"><value>{0} fotogrammi hanno dimensioni diverse da {1}×{2}.</value></data>
|
||||
<data name="Advisor.Finding.NoTimestamps" xml:space="preserve"><value>Solo {0} fotogrammi su {1} hanno un orario di scatto: cadenza e pause non sono misurabili.</value></data>
|
||||
<data name="Advisor.Finding.NonMonotonicTimestamps" xml:space="preserve"><value>{0} fotogrammi sono fuori ordine temporale.</value></data>
|
||||
<data name="Advisor.Finding.Panning" xml:space="preserve"><value>L'inquadratura scorre di {0:0.##} px per fotogramma (panoramica o slider).</value></data>
|
||||
<data name="Advisor.Finding.SceneChanges" xml:space="preserve"><value>L'inquadratura salta in {0} fotogrammi (fotocamera spostata o urtata).</value></data>
|
||||
<data name="Advisor.Finding.Sessions" xml:space="preserve"><value>Ripreso in {0} sessioni separate.</value></data>
|
||||
<data name="Advisor.Finding.Shake" xml:space="preserve"><value>La fotocamera vibra di {0:0.##} px RMS; compensarla costa il {1:0.#}% dell'inquadratura.</value></data>
|
||||
<data name="Advisor.Finding.StarField" xml:space="preserve"><value>Le stelle sono visibili in {0} fotogrammi.</value></data>
|
||||
<data name="Advisor.Finding.StepsNotReceived" xml:space="preserve"><value>{0} cambi di esposizione registrati non hanno raggiunto i pixel.</value></data>
|
||||
<data name="Advisor.Finding.TimeZoneEstimated" xml:space="preserve"><value>Fuso orario non registrato; uno scostamento UTC di {0} min è stato stimato dalla longitudine.</value></data>
|
||||
<data name="Advisor.Finding.UnreadableFrames" xml:space="preserve"><value>{0} fotogrammi non sono decodificabili.</value></data>
|
||||
<data name="Advisor.Finding.WhiteBalanceJitter" xml:space="preserve"><value>Il bilanciamento del colore varia del {0:0.#}% tra un fotogramma e l'altro.</value></data>
|
||||
<data name="Advisor.Finding.WhiteFrames" xml:space="preserve"><value>{0} fotogrammi sono completamente bruciati.</value></data>
|
||||
<data name="Advisor.Missing.Deep" xml:space="preserve"><value>Serve l'analisi approfondita dei pixel, non ancora eseguita; nulla è stato cambiato.</value></data>
|
||||
<data name="Advisor.Missing.Exposure" xml:space="preserve"><value>Tempo di scatto o diaframma mancano nei metadati, quindi non si può decidere; nulla è stato cambiato.</value></data>
|
||||
<data name="Advisor.Missing.Motion" xml:space="preserve"><value>Troppo poche coppie di fotogrammi per misurare il movimento; nulla è stato cambiato.</value></data>
|
||||
<data name="Advisor.Missing.Shake" xml:space="preserve"><value>La vibrazione era misurabile solo sul {0}% dei fotogrammi (poca texture); nulla è stato cambiato.</value></data>
|
||||
<data name="Advisor.Missing.SourceSize" xml:space="preserve"><value>La risoluzione della sorgente è sconosciuta; nulla è stato cambiato.</value></data>
|
||||
<data name="Advisor.Missing.Timestamps" xml:space="preserve"><value>Solo {0} fotogrammi su {1} hanno un orario di scatto, quindi non è misurabile; nulla è stato cambiato.</value></data>
|
||||
<data name="Advisor.Preset.Construction" xml:space="preserve"><value>Cantiere — {0} {1} {2} fps, temporizzazione adattiva</value></data>
|
||||
<data name="Advisor.Preset.HolyGrail" xml:space="preserve"><value>Tramonto holy grail — {0} {1} {2} fps, transizioni {3}</value></data>
|
||||
<data name="Advisor.Preset.NightSky" xml:space="preserve"><value>Cielo notturno — {0} {1} {2} fps, deflicker {3}</value></data>
|
||||
<data name="Advisor.Preset.NightSkyStabilised" xml:space="preserve"><value>Cielo notturno — {0} {1} {2} fps, deflicker {3}, stabilizza</value></data>
|
||||
<data name="Advisor.Preset.SocialVertical" xml:space="preserve"><value>Social verticale {0}×{1}</value></data>
|
||||
<data name="Advisor.Preset.Standard" xml:space="preserve"><value>Standard — {0} {1} {2} fps</value></data>
|
||||
<data name="Advisor.PresetReason.Construction" xml:space="preserve"><value>{0} sessioni in {1} giorni con pause: temporizzazione adattiva in un file 1080p ampiamente compatibile.</value></data>
|
||||
<data name="Advisor.PresetReason.HolyGrail" xml:space="preserve"><value>{0} cambi di esposizione su una variazione di luce di {1} EV: transizioni morbide tra giorno e notte.</value></data>
|
||||
<data name="Advisor.PresetReason.NightSky" xml:space="preserve"><value>Stelle o cielo scuro nel {0}% dei fotogrammi: i gradienti scuri richiedono 10 bit e luminosità stabile.</value></data>
|
||||
<data name="Advisor.PresetReason.SocialVertical" xml:space="preserve"><value>Un ritaglio 9:16 per telefoni e social.</value></data>
|
||||
<data name="Advisor.PresetReason.Standard" xml:space="preserve"><value>Impostazioni generali per questa sequenza.</value></data>
|
||||
<data name="Advisor.Reason.Aspect.Landscape" xml:space="preserve"><value>La sorgente {0}×{1} ritagliata a 16:9 conserva il {2}% dell'altezza.</value></data>
|
||||
<data name="Advisor.Reason.Aspect.Native" xml:space="preserve"><value>La sorgente è già in 16:9.</value></data>
|
||||
<data name="Advisor.Reason.Aspect.Portrait" xml:space="preserve"><value>Sorgente verticale: il 9:16 riempie lo schermo di un telefono.</value></data>
|
||||
<data name="Advisor.Reason.Aspect.Wide" xml:space="preserve"><value>La sorgente {0}×{1} ritagliata a 16:9 conserva il {2}% della larghezza.</value></data>
|
||||
<data name="Advisor.Reason.Deflicker.Off" xml:space="preserve"><value>Lo sfarfallio è di {0} EV, sotto gli 0,02 EV visibili: il deflicker resta spento.</value></data>
|
||||
<data name="Advisor.Reason.Deflicker.On" xml:space="preserve"><value>La luminosità si discosta di {0} EV dal suo andamento regolare: il deflicker elimina lo sfarfallio.</value></data>
|
||||
<data name="Advisor.Reason.Exclude" xml:space="preserve"><value>{0} fotogrammi neri, bianchi, duplicati o illeggibili lampeggerebbero o farebbero scattare il video: esclusi.</value></data>
|
||||
<data name="Advisor.Reason.Export.Night" xml:space="preserve"><value>Cielo notturno: HEVC a 10 bit evita le bande nei gradienti scuri.</value></data>
|
||||
<data name="Advisor.Reason.Export.Standard" xml:space="preserve"><value>Il preset migliore per un'uscita {0}×{1} con i codificatori disponibili.</value></data>
|
||||
<data name="Advisor.Reason.Export.Vertical" xml:space="preserve"><value>Inquadratura verticale: 1080×1920 per telefoni.</value></data>
|
||||
<data name="Advisor.Reason.FitToSeconds" xml:space="preserve"><value>Il piano viene scalato perché i {0} fotogrammi durino {1} s a {2} fps.</value></data>
|
||||
<data name="Advisor.Reason.Flow.Balanced" xml:space="preserve"><value>La qualità del flusso bilanciata basta per la sfocatura di movimento e le anteprime.</value></data>
|
||||
<data name="Advisor.Reason.Flow.Best" xml:space="preserve"><value>I fotogrammi interpolati richiedono il movimento per pixel: qualità del flusso massima.</value></data>
|
||||
<data name="Advisor.Reason.FrameRate.Cinematic" xml:space="preserve"><value>Movimento moderato ({0} px per fotogramma): la cadenza cinema di 24 fps dà una clip di {1} s.</value></data>
|
||||
<data name="Advisor.Reason.FrameRate.Default" xml:space="preserve"><value>Movimento lento o non misurato: a 30 fps la clip dura {0} s.</value></data>
|
||||
<data name="Advisor.Reason.FrameRate.FastMotion" xml:space="preserve"><value>Movimento rapido ({0} px per fotogramma): a 24 fps rallenta; la clip dura {1} s.</value></data>
|
||||
<data name="Advisor.Reason.FrameRate.Fit" xml:space="preserve"><value>{0} fotogrammi riempiono al meglio {1} s a {2} fps.</value></data>
|
||||
<data name="Advisor.Reason.FrameRate.Long" xml:space="preserve"><value>{0} fotogrammi: a 60 fps la clip dura {1} s.</value></data>
|
||||
<data name="Advisor.Reason.FrameRate.Sessions" xml:space="preserve"><value>Ripresa in più sessioni: a 30 fps la clip dura {0} s.</value></data>
|
||||
<data name="Advisor.Reason.FrameRate.Short" xml:space="preserve"><value>Solo {0} fotogrammi: a 24 fps la clip dura {1} s.</value></data>
|
||||
<data name="Advisor.Reason.Framing.Horizon" xml:space="preserve"><value>L'orizzonte è al {0}% dall'alto: il ritaglio lo porta sul terzo più vicino.</value></data>
|
||||
<data name="Advisor.Reason.Hero" xml:space="preserve"><value>Il fotogramma {0} è nitido e ben esposto, senza alte luci bruciate.</value></data>
|
||||
<data name="Advisor.Reason.HolyGrail.Metadata" xml:space="preserve"><value>{0} cambi di esposizione nei metadati (pixel non ancora verificati): ognuno viene distribuito su una transizione morbida.</value></data>
|
||||
<data name="Advisor.Reason.HolyGrail.None" xml:space="preserve"><value>Le impostazioni di esposizione non cambiano mai: nessuna transizione necessaria.</value></data>
|
||||
<data name="Advisor.Reason.HolyGrail.NotReceived" xml:space="preserve"><value>La fotocamera ha registrato {0} cambi di esposizione ma i pixel non ne mostrano: nessuna transizione necessaria.</value></data>
|
||||
<data name="Advisor.Reason.HolyGrail.Received" xml:space="preserve"><value>{0} cambi di esposizione hanno raggiunto i pixel: ognuno viene distribuito su una transizione morbida.</value></data>
|
||||
<data name="Advisor.Reason.MotionBlur.Already" xml:space="preserve"><value>L'esposizione dà già un angolo di {0}°, almeno i {1}° previsti: nessuna sfocatura sintetica necessaria.</value></data>
|
||||
<data name="Advisor.Reason.MotionBlur.Little" xml:space="preserve"><value>Il contenuto si sposta solo di {0} px per fotogramma: la sfocatura sarebbe invisibile, quindi resta spenta.</value></data>
|
||||
<data name="Advisor.Reason.MotionBlur.On" xml:space="preserve"><value>Angolo reale {0}° e movimento di {1} px per fotogramma: la sfocatura a {2}° aggiunge scie di {3} px che nascondono gli scatti.</value></data>
|
||||
<data name="Advisor.Reason.Regions.Horizon" xml:space="preserve"><value>Orizzonte trovato con affidabilità del {0}%: cielo e terreno vengono corretti separatamente.</value></data>
|
||||
<data name="Advisor.Reason.Regions.Luminance" xml:space="preserve"><value>Cielo separato per luminosità con affidabilità del {0}%: cielo e terreno vengono corretti separatamente.</value></data>
|
||||
<data name="Advisor.Reason.Regions.Off" xml:space="preserve"><value>La separazione cielo/terreno è affidabile solo al {0}%: una curva unica per tutta l'immagine è più sicura.</value></data>
|
||||
<data name="Advisor.Reason.Resolution.Codec" xml:space="preserve"><value>Il codificatore {0} gestisce al massimo {1}×{2}.</value></data>
|
||||
<data name="Advisor.Reason.Resolution.Preview" xml:space="preserve"><value>{0} fotogrammi si decodificano solo come anteprime incorporate {1}×{2}, che limitano l'uscita.</value></data>
|
||||
<data name="Advisor.Reason.Resolution.Source" xml:space="preserve"><value>La dimensione standard più grande entro la sorgente {0}×{1}.</value></data>
|
||||
<data name="Advisor.Reason.ShutterAngle" xml:space="preserve"><value>180° è l'aspetto cinematografico; l'angolo d'otturatore reale è {0}° (esposizione di {1} s ogni {2} s).</value></data>
|
||||
<data name="Advisor.Reason.Stabilize.HighCrop" xml:space="preserve"><value>Vibrazione di {0} px alla risoluzione di uscita, ma compensarla ritaglia il {1}% dell'inquadratura: controlla il taglio.</value></data>
|
||||
<data name="Advisor.Reason.Stabilize.Off" xml:space="preserve"><value>Vibrazione misurata di {0} px alla risoluzione di uscita (al massimo 0,3 px): la fotocamera era stabile.</value></data>
|
||||
<data name="Advisor.Reason.Stabilize.On" xml:space="preserve"><value>Vibrazione misurata di {0} px alla risoluzione di uscita (oltre 0,3 px): la stabilizzazione ritaglia il {1}% dell'area.</value></data>
|
||||
<data name="Advisor.Reason.Stabilize.Smoothing" xml:space="preserve"><value>Smussare il percorso della fotocamera su {0} fotogrammi elimina la vibrazione e conserva le panoramiche volute.</value></data>
|
||||
<data name="Advisor.Reason.Strength.Full" xml:space="preserve"><value>Sfarfallio forte ({0} EV): ogni fotogramma viene portato sulla curva regolare.</value></data>
|
||||
<data name="Advisor.Reason.Strength.Partial" xml:space="preserve"><value>Sfarfallio lieve ({0} EV): i fotogrammi affidabili conservano il 20% della propria variazione.</value></data>
|
||||
<data name="Advisor.Reason.Timing.Irregular" xml:space="preserve"><value>Gli intervalli variano di {0} s attorno a {1} s: la temporizzazione adattiva segue l'orario di scatto e rende il movimento uniforme.</value></data>
|
||||
<data name="Advisor.Reason.Timing.ManyGaps" xml:space="preserve"><value>{0} pause nella cadenza: la temporizzazione adattiva mantiene il ritmo fedele all'orario di scatto.</value></data>
|
||||
<data name="Advisor.Reason.Timing.Regular" xml:space="preserve"><value>Intervallo costante di {0} s (variazione {1} s): ogni foto diventa un fotogramma del video.</value></data>
|
||||
<data name="Advisor.Reason.Timing.Sessions" xml:space="preserve"><value>Ripreso in {0} sessioni con pause fino a {1} h: la temporizzazione adattiva accorcia le pause e mantiene il ritmo.</value></data>
|
||||
<data name="Advisor.Reason.Timing.SparseGaps" xml:space="preserve"><value>{0} brevi pause, ma il movimento non è misurato o è rapido: la temporizzazione costante le salta in modo pulito.</value></data>
|
||||
<data name="Advisor.Reason.Timing.SparseGapsSmooth" xml:space="preserve"><value>{0} brevi pause e movimento regolare ({1} px per fotogramma): i fotogrammi interpolati riempiono le pause.</value></data>
|
||||
<data name="Advisor.Reason.Transition.Single" xml:space="preserve"><value>Un solo cambio di esposizione: una transizione di {0} fotogrammi lo rende graduale.</value></data>
|
||||
<data name="Advisor.Reason.Transition.Spacing" xml:space="preserve"><value>I cambi di esposizione distano {0} fotogrammi: transizioni lunghe la metà ({1} fotogrammi) non si sovrappongono mai.</value></data>
|
||||
<data name="Advisor.Reason.WhiteBalance.Off" xml:space="preserve"><value>Il bilanciamento del colore è stabile ({0}% tra fotogrammi): nessuno smussamento necessario.</value></data>
|
||||
<data name="Advisor.Reason.WhiteBalance.On" xml:space="preserve"><value>Il bilanciamento del colore varia del {0}% tra fotogrammi: lo smussamento lo stabilizza e mantiene la deriva lenta.</value></data>
|
||||
<data name="Advisor.Reason.Window.Correlation" xml:space="preserve"><value>Lo sfarfallio resta correlato per {0} fotogrammi: una finestra di {1} fotogrammi ne copre quattro volte tanto.</value></data>
|
||||
<data name="Advisor.Reason.Window.Maximum" xml:space="preserve"><value>Lo sfarfallio varia su {0} fotogrammi: la finestra è limitata a {1} fotogrammi per conservare i veri cambi di luce.</value></data>
|
||||
<data name="Advisor.Reason.Window.Minimum" xml:space="preserve"><value>Lo sfarfallio cambia da un fotogramma all'altro senza ritmo: la finestra robusta più corta, {0} fotogrammi, lo elimina.</value></data>
|
||||
<data name="Advisor.Reason.Window.Period" xml:space="preserve"><value>Lo sfarfallio si ripete ogni {0} fotogrammi: una finestra di {1} fotogrammi media quattro cicli.</value></data>
|
||||
</root>
|
||||
@@ -0,0 +1,91 @@
|
||||
using System.Globalization;
|
||||
using Titano.Core.Analysis;
|
||||
using Titano.Core.Analysis.Deep;
|
||||
using Titano.Core.Localization;
|
||||
using Titano.Core.Project;
|
||||
|
||||
namespace Titano.Core.Advisor;
|
||||
|
||||
/// <summary>
|
||||
/// The analysis advisor (BRIEF §10.3, §10.4): turns the light and deep analyses into explained recommendations
|
||||
/// (<see cref="Recommend"/>), stores them as Auto values without touching manual ones (<see cref="Apply"/>), and takes
|
||||
/// the heavier per-section decisions on request (<see cref="Optimise"/>). Deterministic; every reason is a resource
|
||||
/// key plus arguments.
|
||||
/// </summary>
|
||||
public static class Advisor
|
||||
{
|
||||
/// <summary>
|
||||
/// Recommendations for every parameter the rules cover (see <see cref="AdvisorRules"/>), in section order, plus
|
||||
/// every finding of both analyses. Without a deep report, pixel-based parameters get missing-data recommendations.
|
||||
/// </summary>
|
||||
public static AdvisorResult Recommend(LightAnalysisReport light, DeepAnalysisReport? deep, SequenceContext context)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(light);
|
||||
ArgumentNullException.ThrowIfNull(context);
|
||||
var findings = new List<Finding>(light.Findings);
|
||||
if (deep is not null) findings.AddRange(deep.Findings.Select(f => f.ToFinding()));
|
||||
return new AdvisorResult(new AdvisorRules(light, deep, context).Run(), findings);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Fills <see cref="Auto{T}.AutoValue"/>, <see cref="Auto{T}.ReasonKey"/> and <see cref="Auto{T}.ReasonArgs"/> of every
|
||||
/// advised parameter. Manual values stay in force; missing data changes no value (its reason is stored only where no
|
||||
/// advice exists yet). Plain, non-Auto settings are left to <see cref="Optimise"/>.
|
||||
/// </summary>
|
||||
public static ProjectSettings Apply(ProjectSettings settings, AdvisorResult result)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(settings);
|
||||
ArgumentNullException.ThrowIfNull(result);
|
||||
foreach (var recommendation in result.Recommendations)
|
||||
{
|
||||
if (ParameterBindings.Find(recommendation.Parameter)?.Advise is { } advise) settings = advise(settings, recommendation);
|
||||
}
|
||||
return settings;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// "Optimise section" (BRIEF §10.4): applies the section's advice, returns module switches (deflicker, regions, holy
|
||||
/// grail, white balance, motion blur, stabilisation, timing mode, export preset) to Auto where the advice differs
|
||||
/// from the value in force, and takes the plain decisions (fit-to duration, hero frame when unset, exclusions added
|
||||
/// to the user's, crop placement when centred, output size cap). Missing data changes nothing.
|
||||
/// Returns every effective value that changed, with its reason.
|
||||
/// </summary>
|
||||
public static OptimiseResult Optimise(AdvisorSection section, ProjectSettings settings, AdvisorResult result)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(settings);
|
||||
ArgumentNullException.ThrowIfNull(result);
|
||||
var optimised = settings;
|
||||
var changes = new List<SettingChange>();
|
||||
foreach (var binding in ParameterBindings.All)
|
||||
{
|
||||
if (binding.Section != section || result.Find(binding.Parameter) is not { } recommendation) continue;
|
||||
if (binding.Advise is { } advise) optimised = advise(optimised, recommendation);
|
||||
if (recommendation.Value is null) continue;
|
||||
if (binding.IsModuleSwitch && !ParameterBindings.SameValue(binding.Effective(optimised), recommendation.Value)) optimised = binding.ResetToAuto!(optimised);
|
||||
if (binding.Set is { } set) optimised = set(optimised, recommendation);
|
||||
var before = binding.Effective(settings);
|
||||
var after = binding.Effective(optimised);
|
||||
if (!ParameterBindings.SameValue(before, after))
|
||||
changes.Add(new SettingChange(binding.Parameter, before, after, recommendation.ReasonKey, recommendation.ReasonArgs));
|
||||
}
|
||||
return new OptimiseResult(optimised, changes);
|
||||
}
|
||||
|
||||
/// <summary>Localised text of a recommendation in the current UI culture.</summary>
|
||||
public static string Explain(Recommendation recommendation)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(recommendation);
|
||||
return Loc.L(recommendation.ReasonKey, [.. recommendation.ReasonArgs]);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Localised text of a stored reason (<see cref="Auto{T}.ReasonKey"/>/<see cref="Auto{T}.ReasonArgs"/>): numeric
|
||||
/// arguments, stored culture-neutral, are parsed back so they format with the current culture.
|
||||
/// </summary>
|
||||
public static string Explain(string reasonKey, IReadOnlyList<string>? reasonArgs)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(reasonKey);
|
||||
var args = (reasonArgs ?? []).Select(a => double.TryParse(a, NumberStyles.Float, CultureInfo.InvariantCulture, out var number) ? (object)number : a).ToArray();
|
||||
return Loc.L(reasonKey, args);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
namespace Titano.Core.Advisor;
|
||||
|
||||
/// <summary>
|
||||
/// Resource keys (area <c>Advisor</c>) of the advisor's reasons, missing-data notes and sequence presets. Each key is
|
||||
/// written through <c>LocKey(…)</c> so <c>Titano.Tools i18n check</c> verifies it exists in every required culture;
|
||||
/// the resx comment of each key says what its placeholders hold.
|
||||
/// </summary>
|
||||
public static class AdvisorKeys
|
||||
{
|
||||
/// <summary>Every missing-data key starts with this; such a reason never carries a value.</summary>
|
||||
public const string MissingPrefix = "Advisor.Missing.";
|
||||
|
||||
public static string MissingTimestamps { get; } = LocKey("Advisor.Missing.Timestamps");
|
||||
public static string MissingExposure { get; } = LocKey("Advisor.Missing.Exposure");
|
||||
public static string MissingDeep { get; } = LocKey("Advisor.Missing.Deep");
|
||||
public static string MissingMotion { get; } = LocKey("Advisor.Missing.Motion");
|
||||
public static string MissingShake { get; } = LocKey("Advisor.Missing.Shake");
|
||||
public static string MissingSourceSize { get; } = LocKey("Advisor.Missing.SourceSize");
|
||||
|
||||
public static string TimingSessions { get; } = LocKey("Advisor.Reason.Timing.Sessions");
|
||||
public static string TimingIrregular { get; } = LocKey("Advisor.Reason.Timing.Irregular");
|
||||
public static string TimingSparseGapsSmooth { get; } = LocKey("Advisor.Reason.Timing.SparseGapsSmooth");
|
||||
public static string TimingSparseGaps { get; } = LocKey("Advisor.Reason.Timing.SparseGaps");
|
||||
public static string TimingManyGaps { get; } = LocKey("Advisor.Reason.Timing.ManyGaps");
|
||||
public static string TimingRegular { get; } = LocKey("Advisor.Reason.Timing.Regular");
|
||||
|
||||
public static string FrameRateFit { get; } = LocKey("Advisor.Reason.FrameRate.Fit");
|
||||
public static string FrameRateShort { get; } = LocKey("Advisor.Reason.FrameRate.Short");
|
||||
public static string FrameRateLong { get; } = LocKey("Advisor.Reason.FrameRate.Long");
|
||||
public static string FrameRateSessions { get; } = LocKey("Advisor.Reason.FrameRate.Sessions");
|
||||
public static string FrameRateFastMotion { get; } = LocKey("Advisor.Reason.FrameRate.FastMotion");
|
||||
public static string FrameRateCinematic { get; } = LocKey("Advisor.Reason.FrameRate.Cinematic");
|
||||
public static string FrameRateDefault { get; } = LocKey("Advisor.Reason.FrameRate.Default");
|
||||
public static string FitToSeconds { get; } = LocKey("Advisor.Reason.FitToSeconds");
|
||||
|
||||
public static string ShutterAngle { get; } = LocKey("Advisor.Reason.ShutterAngle");
|
||||
public static string MotionBlurOn { get; } = LocKey("Advisor.Reason.MotionBlur.On");
|
||||
public static string MotionBlurAlready { get; } = LocKey("Advisor.Reason.MotionBlur.Already");
|
||||
public static string MotionBlurLittle { get; } = LocKey("Advisor.Reason.MotionBlur.Little");
|
||||
public static string FlowBest { get; } = LocKey("Advisor.Reason.Flow.Best");
|
||||
public static string FlowBalanced { get; } = LocKey("Advisor.Reason.Flow.Balanced");
|
||||
public static string StabilizeOn { get; } = LocKey("Advisor.Reason.Stabilize.On");
|
||||
public static string StabilizeHighCrop { get; } = LocKey("Advisor.Reason.Stabilize.HighCrop");
|
||||
public static string StabilizeOff { get; } = LocKey("Advisor.Reason.Stabilize.Off");
|
||||
public static string StabilizeSmoothing { get; } = LocKey("Advisor.Reason.Stabilize.Smoothing");
|
||||
|
||||
public static string DeflickerOn { get; } = LocKey("Advisor.Reason.Deflicker.On");
|
||||
public static string DeflickerOff { get; } = LocKey("Advisor.Reason.Deflicker.Off");
|
||||
public static string WindowPeriod { get; } = LocKey("Advisor.Reason.Window.Period");
|
||||
public static string WindowCorrelation { get; } = LocKey("Advisor.Reason.Window.Correlation");
|
||||
public static string WindowMinimum { get; } = LocKey("Advisor.Reason.Window.Minimum");
|
||||
public static string WindowMaximum { get; } = LocKey("Advisor.Reason.Window.Maximum");
|
||||
public static string StrengthFull { get; } = LocKey("Advisor.Reason.Strength.Full");
|
||||
public static string StrengthPartial { get; } = LocKey("Advisor.Reason.Strength.Partial");
|
||||
public static string RegionsHorizon { get; } = LocKey("Advisor.Reason.Regions.Horizon");
|
||||
public static string RegionsLuminance { get; } = LocKey("Advisor.Reason.Regions.Luminance");
|
||||
public static string RegionsOff { get; } = LocKey("Advisor.Reason.Regions.Off");
|
||||
public static string HolyGrailReceived { get; } = LocKey("Advisor.Reason.HolyGrail.Received");
|
||||
public static string HolyGrailNotReceived { get; } = LocKey("Advisor.Reason.HolyGrail.NotReceived");
|
||||
public static string HolyGrailNone { get; } = LocKey("Advisor.Reason.HolyGrail.None");
|
||||
public static string HolyGrailMetadata { get; } = LocKey("Advisor.Reason.HolyGrail.Metadata");
|
||||
public static string TransitionSpacing { get; } = LocKey("Advisor.Reason.Transition.Spacing");
|
||||
public static string TransitionSingle { get; } = LocKey("Advisor.Reason.Transition.Single");
|
||||
public static string WhiteBalanceOn { get; } = LocKey("Advisor.Reason.WhiteBalance.On");
|
||||
public static string WhiteBalanceOff { get; } = LocKey("Advisor.Reason.WhiteBalance.Off");
|
||||
|
||||
public static string AspectLandscape { get; } = LocKey("Advisor.Reason.Aspect.Landscape");
|
||||
public static string AspectWide { get; } = LocKey("Advisor.Reason.Aspect.Wide");
|
||||
public static string AspectNative { get; } = LocKey("Advisor.Reason.Aspect.Native");
|
||||
public static string AspectPortrait { get; } = LocKey("Advisor.Reason.Aspect.Portrait");
|
||||
public static string FramingHorizon { get; } = LocKey("Advisor.Reason.Framing.Horizon");
|
||||
|
||||
public static string Hero { get; } = LocKey("Advisor.Reason.Hero");
|
||||
public static string Exclude { get; } = LocKey("Advisor.Reason.Exclude");
|
||||
|
||||
public static string ResolutionSource { get; } = LocKey("Advisor.Reason.Resolution.Source");
|
||||
public static string ResolutionPreview { get; } = LocKey("Advisor.Reason.Resolution.Preview");
|
||||
public static string ResolutionCodec { get; } = LocKey("Advisor.Reason.Resolution.Codec");
|
||||
public static string ExportNight { get; } = LocKey("Advisor.Reason.Export.Night");
|
||||
public static string ExportStandard { get; } = LocKey("Advisor.Reason.Export.Standard");
|
||||
public static string ExportVertical { get; } = LocKey("Advisor.Reason.Export.Vertical");
|
||||
|
||||
public static string PresetNightSky { get; } = LocKey("Advisor.Preset.NightSky");
|
||||
public static string PresetNightSkyStabilised { get; } = LocKey("Advisor.Preset.NightSkyStabilised");
|
||||
public static string PresetHolyGrail { get; } = LocKey("Advisor.Preset.HolyGrail");
|
||||
public static string PresetConstruction { get; } = LocKey("Advisor.Preset.Construction");
|
||||
public static string PresetSocialVertical { get; } = LocKey("Advisor.Preset.SocialVertical");
|
||||
public static string PresetStandard { get; } = LocKey("Advisor.Preset.Standard");
|
||||
public static string PresetReasonNightSky { get; } = LocKey("Advisor.PresetReason.NightSky");
|
||||
public static string PresetReasonHolyGrail { get; } = LocKey("Advisor.PresetReason.HolyGrail");
|
||||
public static string PresetReasonConstruction { get; } = LocKey("Advisor.PresetReason.Construction");
|
||||
public static string PresetReasonSocialVertical { get; } = LocKey("Advisor.PresetReason.SocialVertical");
|
||||
public static string PresetReasonStandard { get; } = LocKey("Advisor.PresetReason.Standard");
|
||||
|
||||
/// <summary>Identity function that marks a literal as a resource key for the i18n check.</summary>
|
||||
private static string LocKey(string key) => key;
|
||||
}
|
||||
@@ -0,0 +1,507 @@
|
||||
using System.Globalization;
|
||||
using Titano.Core.Analysis;
|
||||
using Titano.Core.Analysis.Deep;
|
||||
using Titano.Core.Export;
|
||||
using Titano.Core.Imaging.Geometry;
|
||||
using Titano.Core.Project;
|
||||
using Titano.Core.Video;
|
||||
|
||||
namespace Titano.Core.Advisor;
|
||||
|
||||
/// <summary>
|
||||
/// The recommendation rules of BRIEF §10.3, one method per parameter group. Output size is decided first because
|
||||
/// shake and motion are judged in output pixels: deep-analysis pixels (source resolution) are scaled by output long
|
||||
/// edge / source long edge. Every rule states its thresholds; missing inputs yield a null value with a
|
||||
/// <see cref="AdvisorKeys.MissingPrefix"/> reason.
|
||||
/// </summary>
|
||||
internal sealed class AdvisorRules
|
||||
{
|
||||
/// <summary>Visible shake threshold in output pixels (BRIEF §10.3).</summary>
|
||||
public const double ShakeThresholdPx = 0.3;
|
||||
|
||||
/// <summary>Film-look target shutter angle in degrees.</summary>
|
||||
public const double TargetShutterAngle = 180;
|
||||
|
||||
/// <summary>Path smoothing σ in frames (as <c>StabilizerOptions.SmoothingSigma</c>).</summary>
|
||||
public const double StabilizeSigma = 12;
|
||||
|
||||
private const double RegionConfidence = 0.6;
|
||||
private const double StrongFlickerEv = 0.08;
|
||||
private const double CropCostLimit = 0.15;
|
||||
|
||||
private static readonly (int Width, int Height)[] Landscape = [(3840, 2160), (2560, 1440), (1920, 1080), (1280, 720)];
|
||||
private static readonly (int Width, int Height)[] Portrait = [(1080, 1920), (720, 1280)];
|
||||
|
||||
private readonly LightAnalysisReport _light;
|
||||
private readonly DeepAnalysisReport? _deep;
|
||||
private readonly SequenceContext _context;
|
||||
private readonly List<Recommendation> _result = [];
|
||||
private readonly int _frames;
|
||||
private readonly (int Width, int Height) _source;
|
||||
private (int Width, int Height) _output;
|
||||
private TimingMode? _timing;
|
||||
|
||||
public AdvisorRules(LightAnalysisReport light, DeepAnalysisReport? deep, SequenceContext context)
|
||||
{
|
||||
_light = light;
|
||||
_deep = deep;
|
||||
_context = context;
|
||||
_frames = context.FrameCount > 0 ? context.FrameCount : light.FrameCount;
|
||||
_source = context.SourceWidth > 0 && context.SourceHeight > 0
|
||||
? (context.SourceWidth, context.SourceHeight)
|
||||
: light.DominantSize ?? (deep is { SourceWidth: > 0, SourceHeight: > 0 } ? (deep.SourceWidth, deep.SourceHeight) : (0, 0));
|
||||
}
|
||||
|
||||
public List<Recommendation> Run()
|
||||
{
|
||||
Export();
|
||||
Frames();
|
||||
Timing();
|
||||
Exposure();
|
||||
Motion();
|
||||
Camera();
|
||||
return [.. _result.OrderBy(r => r.Section)];
|
||||
}
|
||||
|
||||
/// <summary>Converts deep-analysis pixels (source resolution) to output pixels.</summary>
|
||||
private double ToOutput(double sourcePixels)
|
||||
{
|
||||
var deepLong = _deep is { SourceWidth: > 0, SourceHeight: > 0 } d ? int.Max(d.SourceWidth, d.SourceHeight) : _deep?.AnalysisLongEdge ?? 0;
|
||||
var outputLong = int.Max(_output.Width, _output.Height);
|
||||
return deepLong > 0 && outputLong > 0 ? sourcePixels * outputLong / deepLong : sourcePixels;
|
||||
}
|
||||
|
||||
private void Add(AdvisorSection section, string parameter, object? value, double confidence, string reason, params object[] args) =>
|
||||
_result.Add(new Recommendation(section, parameter, value, value is null ? 0 : double.Round(confidence, 2), reason, args));
|
||||
|
||||
private void Missing(AdvisorSection section, string parameter, string reason, params object[] args) => Add(section, parameter, null, 0, reason, args);
|
||||
|
||||
/// <summary>
|
||||
/// Output size and preset: standard 16:9 sizes (9:16 for portrait sources; 4K UHD at most) are tried from the
|
||||
/// largest that fits inside the source cropped to that aspect — or inside the embedded previews when frames decode
|
||||
/// only as previews — downwards, and the first whose preset the encoders can produce wins. Preset per size: 10-bit
|
||||
/// HEVC archive for star fields and night skies (dark gradients band in 8 bit), HEVC, then H.264 at 4K; the H.264
|
||||
/// preset of the size below 4K; vertical social for portrait sources.
|
||||
/// </summary>
|
||||
private void Export()
|
||||
{
|
||||
if (_source.Width <= 0 || _source.Height <= 0)
|
||||
{
|
||||
Missing(AdvisorSection.Export, AdvisorParameters.Resolution, AdvisorKeys.MissingSourceSize);
|
||||
Missing(AdvisorSection.Export, AdvisorParameters.ExportPreset, AdvisorKeys.MissingSourceSize);
|
||||
return;
|
||||
}
|
||||
var portrait = _source.Height > _source.Width;
|
||||
var ratio = portrait ? 9.0 / 16 : 16.0 / 9;
|
||||
var cap = Fit(_source.Width, _source.Height, ratio);
|
||||
var reason = AdvisorKeys.ResolutionSource;
|
||||
object[] args = [_source.Width, _source.Height];
|
||||
if (_context is { PreviewOnlyCount: > 0, PreviewWidth: > 0, PreviewHeight: > 0 })
|
||||
{
|
||||
var preview = Fit(_context.PreviewWidth, _context.PreviewHeight, ratio);
|
||||
if (preview.Width < cap.Width)
|
||||
{
|
||||
cap = preview;
|
||||
reason = AdvisorKeys.ResolutionPreview;
|
||||
args = [_context.PreviewOnlyCount, _context.PreviewWidth, _context.PreviewHeight];
|
||||
}
|
||||
}
|
||||
|
||||
var sizes = (portrait ? Portrait : Landscape).Where(s => s.Width <= cap.Width && s.Height <= cap.Height).ToList();
|
||||
if (sizes.Count == 0) sizes.Add((int.Max(2, cap.Width & ~1), int.Max(2, cap.Height & ~1)));
|
||||
EncoderCapability? limiting = null;
|
||||
foreach (var size in sizes)
|
||||
{
|
||||
foreach (var (preset, key) in Candidates(size, portrait))
|
||||
{
|
||||
var codec = ExportPresets.Find(preset)!.Codec;
|
||||
if (!Fits(codec, size, out var capability))
|
||||
{
|
||||
limiting ??= capability;
|
||||
continue;
|
||||
}
|
||||
_output = size;
|
||||
if (limiting is not null)
|
||||
{
|
||||
reason = AdvisorKeys.ResolutionCodec;
|
||||
args = [limiting.Name, limiting.MaxWidth, limiting.MaxHeight];
|
||||
}
|
||||
Add(AdvisorSection.Export, AdvisorParameters.Resolution, ParameterBindings.Size(size.Width, size.Height), 0.9, reason, args);
|
||||
if (key == AdvisorKeys.ExportStandard) Add(AdvisorSection.Export, AdvisorParameters.ExportPreset, preset, 0.7, key, size.Width, size.Height);
|
||||
else Add(AdvisorSection.Export, AdvisorParameters.ExportPreset, preset, key == AdvisorKeys.ExportNight ? 0.8 : 0.7, key);
|
||||
return;
|
||||
}
|
||||
}
|
||||
// No listed encoder can produce any standard size: keep the source-derived size and leave the preset alone.
|
||||
_output = sizes[0];
|
||||
Add(AdvisorSection.Export, AdvisorParameters.Resolution, ParameterBindings.Size(_output.Width, _output.Height), 0.5, reason, args);
|
||||
}
|
||||
|
||||
/// <summary>Presets for one output size in order of preference, with the reason each one carries.</summary>
|
||||
private IEnumerable<(string Preset, string Reason)> Candidates((int Width, int Height) size, bool portrait)
|
||||
{
|
||||
if (portrait)
|
||||
{
|
||||
yield return ("vertical-1080x1920", AdvisorKeys.ExportVertical);
|
||||
yield break;
|
||||
}
|
||||
if (size.Width >= 3840)
|
||||
{
|
||||
if (IsNightSky() && HasTenBitHevc()) yield return ("4k-hevc10-archive", AdvisorKeys.ExportNight);
|
||||
yield return ("4k-hevc", AdvisorKeys.ExportStandard);
|
||||
yield return ("4k-h264", AdvisorKeys.ExportStandard);
|
||||
}
|
||||
else if (size.Width >= 2560) yield return ("1440p-h264", AdvisorKeys.ExportStandard);
|
||||
else if (size.Width >= 1920) yield return ("1080p-h264", AdvisorKeys.ExportStandard);
|
||||
else yield return ("720p-preview", AdvisorKeys.ExportStandard);
|
||||
}
|
||||
|
||||
/// <summary>Whether an encoder for <paramref name="codec"/> handles the size (either orientation); with no
|
||||
/// capability list everything fits. <paramref name="largest"/> is the codec's largest capability, if any.</summary>
|
||||
private bool Fits(VideoCodec codec, (int Width, int Height) size, out EncoderCapability? largest)
|
||||
{
|
||||
largest = null;
|
||||
if (_context.Codecs.Count == 0) return true;
|
||||
var available = _context.Codecs.Where(c => c.Codec == codec).ToList();
|
||||
largest = available.MaxBy(c => (long)c.MaxWidth * c.MaxHeight);
|
||||
return available.Any(c => c.MaxWidth <= 0 || c.MaxHeight <= 0
|
||||
|| (size.Width <= c.MaxWidth && size.Height <= c.MaxHeight)
|
||||
|| (size.Height <= c.MaxWidth && size.Width <= c.MaxHeight));
|
||||
}
|
||||
|
||||
/// <summary>Hero frame from the deep analysis; exclusion of undecodable, black, white and duplicate frames.</summary>
|
||||
private void Frames()
|
||||
{
|
||||
if (_deep is null)
|
||||
{
|
||||
Missing(AdvisorSection.Frames, AdvisorParameters.Hero, AdvisorKeys.MissingDeep);
|
||||
Missing(AdvisorSection.Frames, AdvisorParameters.Excluded, AdvisorKeys.MissingDeep);
|
||||
return;
|
||||
}
|
||||
if (_deep.HeroIndex is { } hero) Add(AdvisorSection.Frames, AdvisorParameters.Hero, hero, 0.6, AdvisorKeys.Hero, hero + 1);
|
||||
var excluded = _deep.Issues.Excludable();
|
||||
if (excluded.Length > 0) Add(AdvisorSection.Frames, AdvisorParameters.Excluded, excluded, 0.9, AdvisorKeys.Exclude, excluded.Length);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Timing mode, in order: several capture sessions (pauses ≥ the session gap) → Adaptive; jitter above 10 % of the
|
||||
/// median interval → Adaptive; gaps that are sparse (≤ 2 % of intervals, each ≤ 10 × median) with smooth measured
|
||||
/// motion (95th percentile ≤ 1 % of the long edge per frame) → Interpolated, or Constant when motion is unknown or
|
||||
/// fast; denser gaps → Adaptive; otherwise Constant. Frame rate, in order: "fit to N s" target → the standard rate
|
||||
/// nearest frames/N; under 240 frames → 24 (clip ≥ 10 s); over 10 min at 30 fps → 60; several sessions → 30; fast
|
||||
/// motion (≥ 1 % of the long edge per frame) → 24; measured moderate motion (≥ 0.2 %) → 24; otherwise 30.
|
||||
/// </summary>
|
||||
private void Timing()
|
||||
{
|
||||
if (_light.MedianIntervalSeconds is not { } median)
|
||||
{
|
||||
Missing(AdvisorSection.Timing, AdvisorParameters.TimingMode, AdvisorKeys.MissingTimestamps, _light.TimedFrameCount, _light.FrameCount);
|
||||
_timing = null;
|
||||
}
|
||||
else
|
||||
{
|
||||
ChooseTimingMode(median);
|
||||
}
|
||||
FrameRate();
|
||||
}
|
||||
|
||||
private void ChooseTimingMode(double median)
|
||||
{
|
||||
var jitter = _light.JitterSeconds ?? 0;
|
||||
var breaks = _light.Intervals.Where(i => i.Kind == IntervalKind.SessionBreak).ToList();
|
||||
var gaps = _light.Intervals.Where(i => i.Kind == IntervalKind.Gap).ToList();
|
||||
var section = AdvisorSection.Timing;
|
||||
var parameter = AdvisorParameters.TimingMode;
|
||||
if (_light.Sessions.Count >= 2 && breaks.Count > 0)
|
||||
{
|
||||
_timing = TimingMode.Adaptive;
|
||||
Add(section, parameter, _timing, 0.85, AdvisorKeys.TimingSessions, _light.Sessions.Count, R(breaks.Max(b => b.Seconds) / 3600, 1));
|
||||
}
|
||||
else if (jitter > 0.1 * median)
|
||||
{
|
||||
_timing = TimingMode.Adaptive;
|
||||
Add(section, parameter, _timing, 0.7, AdvisorKeys.TimingIrregular, R(jitter, 2), R(median, 2));
|
||||
}
|
||||
else if (gaps.Count > 0)
|
||||
{
|
||||
var sparse = gaps.Count <= double.Max(1, 0.02 * _light.Intervals.Count) && gaps.All(g => g.Seconds <= 10 * median);
|
||||
var motion = MotionFraction();
|
||||
if (sparse && motion is <= 0.01)
|
||||
{
|
||||
_timing = TimingMode.Interpolated;
|
||||
Add(section, parameter, _timing, 0.65, AdvisorKeys.TimingSparseGapsSmooth, gaps.Count, R(ToOutput(_deep!.Motion.P95Px!.Value), 1));
|
||||
}
|
||||
else if (sparse)
|
||||
{
|
||||
_timing = TimingMode.Constant;
|
||||
Add(section, parameter, _timing, 0.6, AdvisorKeys.TimingSparseGaps, gaps.Count);
|
||||
}
|
||||
else
|
||||
{
|
||||
_timing = TimingMode.Adaptive;
|
||||
Add(section, parameter, _timing, 0.7, AdvisorKeys.TimingManyGaps, gaps.Count);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
_timing = TimingMode.Constant;
|
||||
Add(section, parameter, _timing, 0.9, AdvisorKeys.TimingRegular, R(median, 2), R(jitter, 2));
|
||||
}
|
||||
}
|
||||
|
||||
private void FrameRate()
|
||||
{
|
||||
var section = AdvisorSection.Timing;
|
||||
var parameter = AdvisorParameters.FrameRate;
|
||||
if (_frames <= 0) return;
|
||||
double Seconds(int fps) => R((double)_frames / fps, 1);
|
||||
var motion = MotionFraction();
|
||||
if (_context.TargetDurationSeconds is > 0 and var target)
|
||||
{
|
||||
var wanted = _frames / target;
|
||||
var fps = new[] { 24, 25, 30, 60 }.MinBy(f => double.Abs(double.Log(f / wanted)));
|
||||
Add(section, parameter, Rate(fps), 0.8, AdvisorKeys.FrameRateFit, _frames, R(target, 1), fps);
|
||||
Add(section, AdvisorParameters.FitToSeconds, target, 0.8, AdvisorKeys.FitToSeconds, _frames, R(target, 1), fps);
|
||||
}
|
||||
else if (_frames < 240) Add(section, parameter, Rate(24), 0.7, AdvisorKeys.FrameRateShort, _frames, Seconds(24));
|
||||
else if (_frames > 30 * 600) Add(section, parameter, Rate(60), 0.6, AdvisorKeys.FrameRateLong, _frames, Seconds(60));
|
||||
else if (_light.Sessions.Count >= 2) Add(section, parameter, Rate(30), 0.7, AdvisorKeys.FrameRateSessions, Seconds(30));
|
||||
else if (motion >= 0.01) Add(section, parameter, Rate(24), 0.6, AdvisorKeys.FrameRateFastMotion, R(ToOutput(_deep!.Motion.P95Px!.Value), 1), Seconds(24));
|
||||
else if (motion >= 0.002) Add(section, parameter, Rate(24), 0.5, AdvisorKeys.FrameRateCinematic, R(ToOutput(_deep!.Motion.P95Px!.Value), 1), Seconds(24));
|
||||
else Add(section, parameter, Rate(30), 0.5, AdvisorKeys.FrameRateDefault, Seconds(30));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deflicker on when the step-free luminance deviates from its smooth curve by ≥ 0.02 EV RMS; window = the
|
||||
/// spectrum's 4 × flicker period (or correlation length), odd, clamped to 15–151 (the reason says when it was
|
||||
/// clamped); strength 1 for ≥ 0.08 EV, else 0.8.
|
||||
/// Regions follow the mask method when its confidence is ≥ 0.6. Holy grail on when metadata exposure steps reached
|
||||
/// the pixels (all metadata steps when pixels were not analysed); transition = half the median spacing of the
|
||||
/// received steps (12 frames for a single step). White-balance smoothing on when the colour ratios jitter by
|
||||
/// ≥ 0.01 log2 RMS around their smoothed course.
|
||||
/// </summary>
|
||||
private void Exposure()
|
||||
{
|
||||
HolyGrail();
|
||||
var section = AdvisorSection.Exposure;
|
||||
if (_deep is null)
|
||||
{
|
||||
foreach (var p in new[] { AdvisorParameters.Deflicker, AdvisorParameters.DeflickerWindow, AdvisorParameters.DeflickerStrength, AdvisorParameters.Regions, AdvisorParameters.WhiteBalanceSmoothing })
|
||||
Missing(section, p, AdvisorKeys.MissingDeep);
|
||||
return;
|
||||
}
|
||||
var flicker = _deep.Flicker;
|
||||
var amplitude = R(flicker.AmplitudeEv, 3);
|
||||
if (flicker.AmplitudeEv >= DeepSequenceAnalysis.VisibleFlickerEv)
|
||||
Add(section, AdvisorParameters.Deflicker, true, double.Min(0.95, 0.5 + 10 * flicker.AmplitudeEv), AdvisorKeys.DeflickerOn, amplitude);
|
||||
else Add(section, AdvisorParameters.Deflicker, false, 0.7, AdvisorKeys.DeflickerOff, amplitude);
|
||||
var scale = flicker.PeriodFrames ?? flicker.CorrelationLength;
|
||||
var window = flicker.RecommendedWindow;
|
||||
if (4 * scale < FlickerSpectrumOptions.Default.MinimumWindow) Add(section, AdvisorParameters.DeflickerWindow, window, 0.6, AdvisorKeys.WindowMinimum, window);
|
||||
else if (4 * scale > FlickerSpectrumOptions.Default.MaximumWindow) Add(section, AdvisorParameters.DeflickerWindow, window, 0.6, AdvisorKeys.WindowMaximum, R(scale, 1), window);
|
||||
else if (flicker.PeriodFrames is not null) Add(section, AdvisorParameters.DeflickerWindow, window, 0.75, AdvisorKeys.WindowPeriod, R(scale, 1), window);
|
||||
else Add(section, AdvisorParameters.DeflickerWindow, window, 0.6, AdvisorKeys.WindowCorrelation, R(scale, 1), window);
|
||||
if (flicker.AmplitudeEv >= StrongFlickerEv) Add(section, AdvisorParameters.DeflickerStrength, 1.0, 0.6, AdvisorKeys.StrengthFull, amplitude);
|
||||
else Add(section, AdvisorParameters.DeflickerStrength, 0.8, 0.6, AdvisorKeys.StrengthPartial, amplitude);
|
||||
|
||||
if (_deep.Regions is not { } regions) Missing(section, AdvisorParameters.Regions, AdvisorKeys.MissingDeep);
|
||||
else
|
||||
{
|
||||
var percent = R(100 * regions.Confidence, 0);
|
||||
if (regions.Confidence < RegionConfidence) Add(section, AdvisorParameters.Regions, RegionMode.Off, 0.7, AdvisorKeys.RegionsOff, percent);
|
||||
else if (regions.Method == RegionMethod.Horizon) Add(section, AdvisorParameters.Regions, RegionMode.Horizon, regions.Confidence, AdvisorKeys.RegionsHorizon, percent);
|
||||
else Add(section, AdvisorParameters.Regions, RegionMode.Luminance, regions.Confidence, AdvisorKeys.RegionsLuminance, percent);
|
||||
}
|
||||
|
||||
var jitter = _deep.WhiteBalance.JitterLog2;
|
||||
var jitterPercent = R(100 * (double.Exp2(jitter) - 1), 1);
|
||||
if (jitter >= DeepSequenceAnalysis.VisibleWhiteBalanceJitter) Add(section, AdvisorParameters.WhiteBalanceSmoothing, true, 0.7, AdvisorKeys.WhiteBalanceOn, jitterPercent);
|
||||
else Add(section, AdvisorParameters.WhiteBalanceSmoothing, false, 0.7, AdvisorKeys.WhiteBalanceOff, jitterPercent);
|
||||
}
|
||||
|
||||
private void HolyGrail()
|
||||
{
|
||||
var section = AdvisorSection.Exposure;
|
||||
if (!_light.ExposureValues.Any(v => v is not null))
|
||||
{
|
||||
Missing(section, AdvisorParameters.HolyGrail, AdvisorKeys.MissingExposure);
|
||||
Missing(section, AdvisorParameters.TransitionLength, AdvisorKeys.MissingExposure);
|
||||
return;
|
||||
}
|
||||
if (_deep is { Exposure: var exposure })
|
||||
{
|
||||
if (exposure.MetadataSteps == 0) Add(section, AdvisorParameters.HolyGrail, false, 0.9, AdvisorKeys.HolyGrailNone);
|
||||
else if (exposure.ReceivedSteps == 0) Add(section, AdvisorParameters.HolyGrail, false, 0.8, AdvisorKeys.HolyGrailNotReceived, exposure.MetadataSteps);
|
||||
else
|
||||
{
|
||||
Add(section, AdvisorParameters.HolyGrail, true, 0.85, AdvisorKeys.HolyGrailReceived, exposure.ReceivedSteps);
|
||||
Transition(exposure.TypicalSpacing, exposure.TransitionLength!.Value, 0.8);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (_light.ExposureSteps.Count == 0)
|
||||
{
|
||||
Add(section, AdvisorParameters.HolyGrail, false, 0.9, AdvisorKeys.HolyGrailNone);
|
||||
return;
|
||||
}
|
||||
Add(section, AdvisorParameters.HolyGrail, true, 0.6, AdvisorKeys.HolyGrailMetadata, _light.ExposureSteps.Count);
|
||||
var spacing = _light.TypicalStepDistance;
|
||||
var length = spacing is { } s ? int.Max(2, (int)double.Round(s / 2)) : HolyGrailOptions.Default.SingleStepTransitionFrames;
|
||||
Transition(spacing, length, 0.5);
|
||||
}
|
||||
|
||||
private void Transition(double? spacing, int length, double confidence)
|
||||
{
|
||||
if (spacing is { } s) Add(AdvisorSection.Exposure, AdvisorParameters.TransitionLength, length, confidence, AdvisorKeys.TransitionSpacing, R(s, 0), length);
|
||||
else Add(AdvisorSection.Exposure, AdvisorParameters.TransitionLength, length, confidence, AdvisorKeys.TransitionSingle, length);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Target shutter angle 180° (film look); real angle = 360 × median exposure / median interval. Motion blur off when
|
||||
/// the real angle already reaches the target or the moving content (95th-percentile flow, output pixels) moves
|
||||
/// under 1 px per frame; otherwise on, adding √(180² − real²)/360 × motion px of trail. Flow quality Best for
|
||||
/// interpolated timing (per-pixel vectors), else Balanced. Stabilisation on when the shake RMS exceeds 0.3 output
|
||||
/// pixels (lower confidence when hiding it costs over 15 % of the frame); path smoothing σ = 12 frames.
|
||||
/// </summary>
|
||||
private void Motion()
|
||||
{
|
||||
var section = AdvisorSection.Motion;
|
||||
var interval = _light.MedianIntervalSeconds;
|
||||
var exposure = _context.MedianExposureSeconds;
|
||||
if (interval is null)
|
||||
{
|
||||
Missing(section, AdvisorParameters.TargetShutterAngle, AdvisorKeys.MissingTimestamps, _light.TimedFrameCount, _light.FrameCount);
|
||||
Missing(section, AdvisorParameters.MotionBlur, AdvisorKeys.MissingTimestamps, _light.TimedFrameCount, _light.FrameCount);
|
||||
}
|
||||
else if (exposure is null)
|
||||
{
|
||||
Missing(section, AdvisorParameters.TargetShutterAngle, AdvisorKeys.MissingExposure);
|
||||
Missing(section, AdvisorParameters.MotionBlur, AdvisorKeys.MissingExposure);
|
||||
}
|
||||
else
|
||||
{
|
||||
var real = double.Min(360, 360 * exposure.Value / interval.Value);
|
||||
Add(section, AdvisorParameters.TargetShutterAngle, TargetShutterAngle, 0.8, AdvisorKeys.ShutterAngle, R(real, 0), Significant(exposure.Value), R(interval.Value, 2));
|
||||
MotionBlur(real);
|
||||
}
|
||||
|
||||
var best = _timing == TimingMode.Interpolated;
|
||||
Add(section, AdvisorParameters.FlowQuality, best ? FlowQualitySetting.Best : FlowQualitySetting.Balanced, 0.6, best ? AdvisorKeys.FlowBest : AdvisorKeys.FlowBalanced);
|
||||
Stabilize();
|
||||
}
|
||||
|
||||
private void MotionBlur(double real)
|
||||
{
|
||||
var section = AdvisorSection.Motion;
|
||||
if (real >= TargetShutterAngle)
|
||||
{
|
||||
Add(section, AdvisorParameters.MotionBlur, false, 0.9, AdvisorKeys.MotionBlurAlready, R(real, 0), TargetShutterAngle);
|
||||
return;
|
||||
}
|
||||
if (_deep is null)
|
||||
{
|
||||
Missing(section, AdvisorParameters.MotionBlur, AdvisorKeys.MissingDeep);
|
||||
return;
|
||||
}
|
||||
if (_deep.Motion.P95Px is not { } p95)
|
||||
{
|
||||
Missing(section, AdvisorParameters.MotionBlur, AdvisorKeys.MissingMotion);
|
||||
return;
|
||||
}
|
||||
var motion = ToOutput(p95);
|
||||
if (motion < 1)
|
||||
{
|
||||
Add(section, AdvisorParameters.MotionBlur, false, 0.8, AdvisorKeys.MotionBlurLittle, R(motion, 1));
|
||||
return;
|
||||
}
|
||||
var trail = motion * double.Sqrt(TargetShutterAngle * TargetShutterAngle - real * real) / 360;
|
||||
Add(section, AdvisorParameters.MotionBlur, true, 0.75, AdvisorKeys.MotionBlurOn, R(real, 0), R(motion, 1), TargetShutterAngle, R(trail, 1));
|
||||
}
|
||||
|
||||
private void Stabilize()
|
||||
{
|
||||
var section = AdvisorSection.Motion;
|
||||
if (_deep is null)
|
||||
{
|
||||
Missing(section, AdvisorParameters.Stabilize, AdvisorKeys.MissingDeep);
|
||||
Missing(section, AdvisorParameters.StabilizeSmoothing, AdvisorKeys.MissingDeep);
|
||||
return;
|
||||
}
|
||||
var shake = _deep.Shake;
|
||||
if (shake.MeasuredFraction < 0.5)
|
||||
{
|
||||
Missing(section, AdvisorParameters.Stabilize, AdvisorKeys.MissingShake, R(100 * shake.MeasuredFraction, 0));
|
||||
return;
|
||||
}
|
||||
var rms = ToOutput(shake.RmsPx);
|
||||
var crop = R(100 * shake.CropCost, 1);
|
||||
if (rms <= ShakeThresholdPx) Add(section, AdvisorParameters.Stabilize, false, 0.8, AdvisorKeys.StabilizeOff, R(rms, 2));
|
||||
else if (shake.CropCost <= CropCostLimit) Add(section, AdvisorParameters.Stabilize, true, 0.8, AdvisorKeys.StabilizeOn, R(rms, 2), crop);
|
||||
else Add(section, AdvisorParameters.Stabilize, true, 0.5, AdvisorKeys.StabilizeHighCrop, R(rms, 2), crop);
|
||||
Add(section, AdvisorParameters.StabilizeSmoothing, StabilizeSigma, 0.6, AdvisorKeys.StabilizeSmoothing, StabilizeSigma);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Aspect 16:9 for landscape sources (the reason says how much height or width the crop keeps), 9:16 for portrait
|
||||
/// ones. When a confident horizon exists and the crop gives up
|
||||
/// height, the crop is placed so the horizon sits on the nearest third of the output frame (recommended only when the
|
||||
/// placement moves at least a fifth of the slack away from centred).
|
||||
/// </summary>
|
||||
private void Camera()
|
||||
{
|
||||
var section = AdvisorSection.Camera;
|
||||
if (_source.Width <= 0 || _source.Height <= 0)
|
||||
{
|
||||
Missing(section, AdvisorParameters.Aspect, AdvisorKeys.MissingSourceSize);
|
||||
return;
|
||||
}
|
||||
if (_source.Height > _source.Width)
|
||||
{
|
||||
Add(section, AdvisorParameters.Aspect, "9:16", 0.7, AdvisorKeys.AspectPortrait);
|
||||
return;
|
||||
}
|
||||
var ratio = (double)_source.Width / _source.Height / (16.0 / 9);
|
||||
var kept = double.Min(1, ratio);
|
||||
if (double.Abs(ratio - 1) < 0.01) Add(section, AdvisorParameters.Aspect, "16:9", 0.9, AdvisorKeys.AspectNative);
|
||||
else if (ratio < 1) Add(section, AdvisorParameters.Aspect, "16:9", 0.7, AdvisorKeys.AspectLandscape, _source.Width, _source.Height, R(100 * ratio, 0));
|
||||
else Add(section, AdvisorParameters.Aspect, "16:9", 0.6, AdvisorKeys.AspectWide, _source.Width, _source.Height, R(100 / ratio, 0));
|
||||
|
||||
if (kept >= 0.99 || _deep?.Regions is not { Method: RegionMethod.Horizon, Confidence: >= RegionConfidence, Horizon: { Length: > 0 } horizon }) return;
|
||||
var row = horizon.Average();
|
||||
var slack = 1 - kept;
|
||||
var third = double.Abs(row - (slack / 2 + kept / 3)) <= double.Abs(row - (slack / 2 + 2 * kept / 3)) ? 1.0 / 3 : 2.0 / 3;
|
||||
var top = double.Clamp(row - third * kept, 0, slack);
|
||||
var offset = R(2 * top / slack - 1, 2);
|
||||
if (double.Abs(offset) >= 0.2) Add(section, AdvisorParameters.OffsetY, offset, 0.5, AdvisorKeys.FramingHorizon, R(100 * row, 0));
|
||||
}
|
||||
|
||||
/// <summary>Night content: a star field, or a sequence the deep analysis or GPS phases call night.</summary>
|
||||
private bool IsNightSky() => _deep is { } d && (d.Sky.StarField || d.Sky.Light == DayNight.Night);
|
||||
|
||||
/// <summary>Speed of moving content as a fraction of the frame's long edge per frame; null without motion data.</summary>
|
||||
private double? MotionFraction()
|
||||
{
|
||||
if (_deep?.Motion.P95Px is not { } p95) return null;
|
||||
var deepLong = _deep.SourceWidth > 0 ? int.Max(_deep.SourceWidth, _deep.SourceHeight) : _deep.AnalysisLongEdge;
|
||||
return deepLong > 0 ? p95 / deepLong : null;
|
||||
}
|
||||
|
||||
private bool HasTenBitHevc() => _context.Codecs.Count == 0 || _context.Codecs.Any(c => c.Codec == VideoCodec.Hevc && c.SupportsTenBit);
|
||||
|
||||
private static (int Width, int Height) Fit(int width, int height, double ratio)
|
||||
{
|
||||
var crop = AspectRatio.FitCrop(RectD.FromSize(width, height), ratio);
|
||||
return ((int)double.Floor(crop.Width + 1e-9), (int)double.Floor(crop.Height + 1e-9));
|
||||
}
|
||||
|
||||
private static string Rate(int fps) => fps.ToString(CultureInfo.InvariantCulture);
|
||||
|
||||
private static double R(double value, int decimals) => double.Round(value, decimals, MidpointRounding.AwayFromZero);
|
||||
|
||||
private static double Significant(double value)
|
||||
{
|
||||
if (!(value > 0)) return value;
|
||||
var decimals = 2 - (int)double.Floor(double.Log10(value));
|
||||
return decimals is >= 0 and <= 15 ? R(value, decimals) : value;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,177 @@
|
||||
using Titano.Core.Analysis;
|
||||
using Titano.Core.Mathematics;
|
||||
using Titano.Core.Model;
|
||||
using Titano.Core.Project;
|
||||
using Titano.Core.Video;
|
||||
|
||||
namespace Titano.Core.Advisor;
|
||||
|
||||
/// <summary>Sequence-editor section a recommendation belongs to (BRIEF §12.3).</summary>
|
||||
public enum AdvisorSection
|
||||
{
|
||||
Frames,
|
||||
Timing,
|
||||
Exposure,
|
||||
Motion,
|
||||
Camera,
|
||||
|
||||
/// <summary>No automatic advice: a temporal median erases stars that move between frames, so stacking stays a user choice.</summary>
|
||||
Stack,
|
||||
|
||||
Export,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stable ids of the parameters the advisor decides, named after their <see cref="ProjectSettings"/> path.
|
||||
/// Value types: see each constant.
|
||||
/// </summary>
|
||||
public static class AdvisorParameters
|
||||
{
|
||||
/// <summary><see cref="int"/> frame index.</summary>
|
||||
public const string Hero = "Frames.Hero";
|
||||
|
||||
/// <summary><see cref="int"/>[] frame indices to exclude.</summary>
|
||||
public const string Excluded = "Frames.Excluded";
|
||||
|
||||
/// <summary><see cref="Project.TimingMode"/>.</summary>
|
||||
public const string TimingMode = "Timing.Mode";
|
||||
|
||||
/// <summary><see cref="string"/> frame rate ("24", "25", "30", "60").</summary>
|
||||
public const string FrameRate = "Timing.FrameRate";
|
||||
|
||||
/// <summary><see cref="double"/> seconds.</summary>
|
||||
public const string FitToSeconds = "Timing.FitToSeconds";
|
||||
|
||||
/// <summary><see cref="bool"/>.</summary>
|
||||
public const string Deflicker = "Exposure.Deflicker";
|
||||
|
||||
/// <summary><see cref="int"/> frames (odd).</summary>
|
||||
public const string DeflickerWindow = "Exposure.DeflickerWindow";
|
||||
|
||||
/// <summary><see cref="double"/> 0..1.</summary>
|
||||
public const string DeflickerStrength = "Exposure.DeflickerStrength";
|
||||
|
||||
/// <summary><see cref="RegionMode"/>.</summary>
|
||||
public const string Regions = "Exposure.Regions";
|
||||
|
||||
/// <summary><see cref="bool"/>.</summary>
|
||||
public const string HolyGrail = "Exposure.HolyGrail";
|
||||
|
||||
/// <summary><see cref="int"/> frames.</summary>
|
||||
public const string TransitionLength = "Exposure.TransitionLength";
|
||||
|
||||
/// <summary><see cref="bool"/>.</summary>
|
||||
public const string WhiteBalanceSmoothing = "Exposure.WhiteBalanceSmoothing";
|
||||
|
||||
/// <summary><see cref="bool"/>.</summary>
|
||||
public const string MotionBlur = "Motion.MotionBlur";
|
||||
|
||||
/// <summary><see cref="double"/> degrees.</summary>
|
||||
public const string TargetShutterAngle = "Motion.TargetShutterAngle";
|
||||
|
||||
/// <summary><see cref="FlowQualitySetting"/>.</summary>
|
||||
public const string FlowQuality = "Motion.FlowQuality";
|
||||
|
||||
/// <summary><see cref="bool"/>.</summary>
|
||||
public const string Stabilize = "Motion.Stabilize";
|
||||
|
||||
/// <summary><see cref="double"/> σ in frames.</summary>
|
||||
public const string StabilizeSmoothing = "Motion.StabilizeSmoothing";
|
||||
|
||||
/// <summary><see cref="string"/> aspect ("16:9", "9:16", …).</summary>
|
||||
public const string Aspect = "Camera.Aspect";
|
||||
|
||||
/// <summary><see cref="double"/> crop placement −1..1 (0 = centred).</summary>
|
||||
public const string OffsetY = "Camera.OffsetY";
|
||||
|
||||
/// <summary><see cref="string"/> built-in export preset id.</summary>
|
||||
public const string ExportPreset = "Export.Preset";
|
||||
|
||||
/// <summary><see cref="string"/> output size "WxH" (the cap from source, previews and encoder).</summary>
|
||||
public const string Resolution = "Export.Resolution";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// One advisor decision (BRIEF §10.3). <see cref="Value"/> is null when data is missing; the reason then says what is
|
||||
/// missing and nothing is changed. <see cref="ReasonArgs"/> are numbers (already rounded for display) or plain tokens,
|
||||
/// formatted by the caller with its culture: <c>Loc.L(ReasonKey, [.. ReasonArgs])</c>.
|
||||
/// </summary>
|
||||
/// <param name="Confidence">0..1: how strongly the measurements support the value.</param>
|
||||
public sealed record Recommendation(
|
||||
AdvisorSection Section,
|
||||
string Parameter,
|
||||
object? Value,
|
||||
double Confidence,
|
||||
string ReasonKey,
|
||||
IReadOnlyList<object> ReasonArgs)
|
||||
{
|
||||
public bool IsMissingData => Value is null;
|
||||
}
|
||||
|
||||
/// <summary>Output of <see cref="Advisor.Recommend"/>: recommendations in section order plus every finding.</summary>
|
||||
public sealed record AdvisorResult(IReadOnlyList<Recommendation> Recommendations, IReadOnlyList<Finding> Findings)
|
||||
{
|
||||
public Recommendation? Find(string parameter) => Recommendations.FirstOrDefault(r => r.Parameter == parameter);
|
||||
|
||||
public IEnumerable<Recommendation> In(AdvisorSection section) => Recommendations.Where(r => r.Section == section);
|
||||
}
|
||||
|
||||
/// <summary>What the advisor knows about the sequence besides the analyses.</summary>
|
||||
public sealed record SequenceContext
|
||||
{
|
||||
public int FrameCount { get; init; }
|
||||
|
||||
/// <summary>Oriented full-resolution size (0 = take the light analysis' dominant size).</summary>
|
||||
public int SourceWidth { get; init; }
|
||||
|
||||
public int SourceHeight { get; init; }
|
||||
|
||||
/// <summary>Frames that decode only through their embedded preview (BRIEF §8.2 tier 2).</summary>
|
||||
public int PreviewOnlyCount { get; init; }
|
||||
|
||||
/// <summary>Oriented size of those embedded previews (0 = unknown).</summary>
|
||||
public int PreviewWidth { get; init; }
|
||||
|
||||
public int PreviewHeight { get; init; }
|
||||
|
||||
/// <summary>Median shutter time in seconds, for the real shutter angle.</summary>
|
||||
public double? MedianExposureSeconds { get; init; }
|
||||
|
||||
/// <summary>Encoders available on the rendering machine; empty = unknown (no codec is ruled out).</summary>
|
||||
public IReadOnlyList<EncoderCapability> Codecs { get; init; } = [];
|
||||
|
||||
/// <summary>Wanted video length ("fit to N seconds"), when the user set one.</summary>
|
||||
public double? TargetDurationSeconds { get; init; }
|
||||
|
||||
/// <summary>Context from the archive's frame rows: count, dominant oriented size, preview-only count, median shutter time.</summary>
|
||||
public static SequenceContext FromFrames(IReadOnlyList<Frame> frames, IReadOnlyList<EncoderCapability>? codecs = null)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(frames);
|
||||
var sizes = new Dictionary<(int, int), int>();
|
||||
var exposures = new List<double>();
|
||||
var previewOnly = 0;
|
||||
foreach (var f in frames)
|
||||
{
|
||||
var size = f.Orientation is >= 5 and <= 8 ? (f.Height, f.Width) : (f.Width, f.Height);
|
||||
if (size.Item1 > 0 && size.Item2 > 0) sizes[size] = sizes.GetValueOrDefault(size) + 1;
|
||||
if (f.ExposureTime is > 0 and var t) exposures.Add(t);
|
||||
if ((f.Flags & FrameFlags.PreviewOnly) != 0) previewOnly++;
|
||||
}
|
||||
var (width, height) = sizes.Count > 0 ? sizes.MaxBy(kv => kv.Value).Key : (0, 0);
|
||||
return new SequenceContext
|
||||
{
|
||||
FrameCount = frames.Count,
|
||||
SourceWidth = width,
|
||||
SourceHeight = height,
|
||||
PreviewOnlyCount = previewOnly,
|
||||
MedianExposureSeconds = exposures.Count > 0 ? Statistics.Median(exposures.ToArray()) : null,
|
||||
Codecs = codecs ?? [],
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A value <see cref="Advisor.Optimise"/> changed: effective value before and after, and why.</summary>
|
||||
public sealed record SettingChange(string Parameter, object? Before, object? After, string ReasonKey, IReadOnlyList<object> ReasonArgs);
|
||||
|
||||
/// <summary>Settings after <see cref="Advisor.Optimise"/> and the report of what changed.</summary>
|
||||
public sealed record OptimiseResult(ProjectSettings Settings, IReadOnlyList<SettingChange> Changes);
|
||||
@@ -0,0 +1,137 @@
|
||||
using System.Collections;
|
||||
using System.Globalization;
|
||||
using Titano.Core.Export;
|
||||
using Titano.Core.Project;
|
||||
|
||||
namespace Titano.Core.Advisor;
|
||||
|
||||
/// <summary>How one advisor parameter reads and writes <see cref="ProjectSettings"/>.</summary>
|
||||
internal sealed class ParameterBinding
|
||||
{
|
||||
public required string Parameter { get; init; }
|
||||
public required AdvisorSection Section { get; init; }
|
||||
|
||||
/// <summary>A module on/off decision: <see cref="Advisor.Optimise"/> returns it to Auto when the advice differs.</summary>
|
||||
public bool IsModuleSwitch { get; init; }
|
||||
|
||||
/// <summary>The value in force (manual, else advised), null when neither exists.</summary>
|
||||
public required Func<ProjectSettings, object?> Effective { get; init; }
|
||||
|
||||
/// <summary>Auto fields: stores the advice and its reason, never touching a manual value.</summary>
|
||||
public Func<ProjectSettings, Recommendation, ProjectSettings>? Advise { get; init; }
|
||||
|
||||
/// <summary>Auto fields: drops the manual value so the advice applies.</summary>
|
||||
public Func<ProjectSettings, ProjectSettings>? ResetToAuto { get; init; }
|
||||
|
||||
/// <summary>Plain fields: the heavier decision <see cref="Advisor.Optimise"/> takes (each guards user choices).</summary>
|
||||
public Func<ProjectSettings, Recommendation, ProjectSettings>? Set { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>The binding of every <see cref="AdvisorParameters"/> id, in section order.</summary>
|
||||
internal static class ParameterBindings
|
||||
{
|
||||
public static IReadOnlyList<ParameterBinding> All { get; } =
|
||||
[
|
||||
new()
|
||||
{
|
||||
Parameter = AdvisorParameters.Hero, Section = AdvisorSection.Frames,
|
||||
Effective = s => s.HeroFrame,
|
||||
Set = (s, r) => s.HeroFrame is null ? s with { HeroFrame = (int)r.Value! } : s,
|
||||
},
|
||||
new()
|
||||
{
|
||||
Parameter = AdvisorParameters.Excluded, Section = AdvisorSection.Frames,
|
||||
Effective = s => s.ExcludedFrames,
|
||||
Set = (s, r) => s with { ExcludedFrames = [.. s.ExcludedFrames.Union((int[])r.Value!).Order()] },
|
||||
},
|
||||
AutoField(AdvisorParameters.TimingMode, AdvisorSection.Timing, true, s => s.Timing.Mode, (s, a) => s with { Timing = s.Timing with { Mode = a } }),
|
||||
AutoField(AdvisorParameters.FrameRate, AdvisorSection.Timing, false, s => s.Timing.FrameRate, (s, a) => s with { Timing = s.Timing with { FrameRate = a } }),
|
||||
new()
|
||||
{
|
||||
Parameter = AdvisorParameters.FitToSeconds, Section = AdvisorSection.Timing,
|
||||
Effective = s => s.Timing.FitToSeconds,
|
||||
Set = (s, r) => s with { Timing = s.Timing with { FitToSeconds = (double)r.Value! } },
|
||||
},
|
||||
AutoField(AdvisorParameters.Deflicker, AdvisorSection.Exposure, true, s => s.Exposure.Deflicker, (s, a) => s with { Exposure = s.Exposure with { Deflicker = a } }),
|
||||
AutoField(AdvisorParameters.DeflickerWindow, AdvisorSection.Exposure, false, s => s.Exposure.DeflickerWindow, (s, a) => s with { Exposure = s.Exposure with { DeflickerWindow = a } }),
|
||||
AutoField(AdvisorParameters.DeflickerStrength, AdvisorSection.Exposure, false, s => s.Exposure.DeflickerStrength, (s, a) => s with { Exposure = s.Exposure with { DeflickerStrength = a } }),
|
||||
AutoField(AdvisorParameters.Regions, AdvisorSection.Exposure, true, s => s.Exposure.Regions, (s, a) => s with { Exposure = s.Exposure with { Regions = a } }),
|
||||
AutoField(AdvisorParameters.HolyGrail, AdvisorSection.Exposure, true, s => s.Exposure.HolyGrail, (s, a) => s with { Exposure = s.Exposure with { HolyGrail = a } }),
|
||||
AutoField(AdvisorParameters.TransitionLength, AdvisorSection.Exposure, false, s => s.Exposure.TransitionLength, (s, a) => s with { Exposure = s.Exposure with { TransitionLength = a } }),
|
||||
AutoField(AdvisorParameters.WhiteBalanceSmoothing, AdvisorSection.Exposure, true, s => s.Exposure.WhiteBalanceSmoothing, (s, a) => s with { Exposure = s.Exposure with { WhiteBalanceSmoothing = a } }),
|
||||
AutoField(AdvisorParameters.MotionBlur, AdvisorSection.Motion, true, s => s.Motion.MotionBlur, (s, a) => s with { Motion = s.Motion with { MotionBlur = a } }),
|
||||
AutoField(AdvisorParameters.TargetShutterAngle, AdvisorSection.Motion, false, s => s.Motion.TargetShutterAngle, (s, a) => s with { Motion = s.Motion with { TargetShutterAngle = a } }),
|
||||
AutoField(AdvisorParameters.FlowQuality, AdvisorSection.Motion, false, s => s.Motion.FlowQuality, (s, a) => s with { Motion = s.Motion with { FlowQuality = a } }),
|
||||
AutoField(AdvisorParameters.Stabilize, AdvisorSection.Motion, true, s => s.Motion.Stabilize, (s, a) => s with { Motion = s.Motion with { Stabilize = a } }),
|
||||
AutoField(AdvisorParameters.StabilizeSmoothing, AdvisorSection.Motion, false, s => s.Motion.StabilizeSmoothing, (s, a) => s with { Motion = s.Motion with { StabilizeSmoothing = a } }),
|
||||
AutoField(AdvisorParameters.Aspect, AdvisorSection.Camera, false, s => s.Camera.Aspect, (s, a) => s with { Camera = s.Camera with { Aspect = a } }),
|
||||
new()
|
||||
{
|
||||
Parameter = AdvisorParameters.OffsetY, Section = AdvisorSection.Camera,
|
||||
Effective = s => s.Camera.OffsetY,
|
||||
Set = (s, r) => s.Camera.OffsetY == 0 ? s with { Camera = s.Camera with { OffsetY = (double)r.Value! } } : s,
|
||||
},
|
||||
AutoField(AdvisorParameters.ExportPreset, AdvisorSection.Export, true, s => s.Export.Preset, (s, a) => s with { Export = s.Export with { Preset = a } }),
|
||||
new()
|
||||
{
|
||||
Parameter = AdvisorParameters.Resolution, Section = AdvisorSection.Export,
|
||||
Effective = s => s.Export.Overrides is { Width: { } w, Height: { } h } ? Size(w, h) : null,
|
||||
Set = CapResolution,
|
||||
},
|
||||
];
|
||||
|
||||
public static ParameterBinding? Find(string parameter) => All.FirstOrDefault(b => b.Parameter == parameter);
|
||||
|
||||
/// <summary>Value equality that compares lists element by element.</summary>
|
||||
public static bool SameValue(object? a, object? b)
|
||||
{
|
||||
if (a is IEnumerable x && b is IEnumerable y && a is not string && b is not string) return x.Cast<object>().SequenceEqual(y.Cast<object>());
|
||||
return Equals(a, b);
|
||||
}
|
||||
|
||||
/// <summary>Recommendation arguments as stored in <see cref="Auto{T}.ReasonArgs"/> (culture-neutral text).</summary>
|
||||
public static string[] Strings(IReadOnlyList<object> args) => [.. args.Select(a => Convert.ToString(a, CultureInfo.InvariantCulture) ?? string.Empty)];
|
||||
|
||||
public static string Size(int width, int height) => string.Create(CultureInfo.InvariantCulture, $"{width}x{height}");
|
||||
|
||||
public static bool HasAdvice<T>(Auto<T> auto) => typeof(T).IsValueType
|
||||
? auto.ReasonKey is not null && !auto.ReasonKey.StartsWith(AdvisorKeys.MissingPrefix, StringComparison.Ordinal)
|
||||
: auto.AutoValue is not null;
|
||||
|
||||
private static ParameterBinding AutoField<T>(string parameter, AdvisorSection section, bool module, Func<ProjectSettings, Auto<T>> get, Func<ProjectSettings, Auto<T>, ProjectSettings> set) => new()
|
||||
{
|
||||
Parameter = parameter,
|
||||
Section = section,
|
||||
IsModuleSwitch = module,
|
||||
Effective = s => EffectiveOf(get(s)),
|
||||
Advise = (s, r) => set(s, Advise(get(s), r)),
|
||||
ResetToAuto = s => set(s, get(s).Reset()),
|
||||
};
|
||||
|
||||
private static object? EffectiveOf<T>(Auto<T> auto) => !auto.IsAuto && auto.Manual is not null ? auto.Manual : HasAdvice(auto) ? auto.AutoValue : null;
|
||||
|
||||
/// <summary>
|
||||
/// Stores a value with its reason. Missing data changes no value: the missing-data reason is stored only when the
|
||||
/// parameter has no advice yet, so the Auto tooltip can say why it is empty.
|
||||
/// </summary>
|
||||
private static Auto<T> Advise<T>(Auto<T> auto, Recommendation recommendation)
|
||||
{
|
||||
var args = Strings(recommendation.ReasonArgs);
|
||||
if (recommendation.Value is null)
|
||||
return HasAdvice(auto) ? auto : auto with { ReasonKey = recommendation.ReasonKey, ReasonArgs = args };
|
||||
if (recommendation.Value is not T value)
|
||||
throw new InvalidOperationException($"{recommendation.Parameter} expects {typeof(T).Name}, got {recommendation.Value.GetType().Name}.");
|
||||
return auto.WithAdvice(value, recommendation.ReasonKey, args);
|
||||
}
|
||||
|
||||
/// <summary>Overrides the output size when the preset in force is larger than the recommended cap.</summary>
|
||||
private static ProjectSettings CapResolution(ProjectSettings settings, Recommendation recommendation)
|
||||
{
|
||||
var parts = ((string)recommendation.Value!).Split('x');
|
||||
var width = int.Parse(parts[0], CultureInfo.InvariantCulture);
|
||||
var height = int.Parse(parts[1], CultureInfo.InvariantCulture);
|
||||
var id = EffectiveOf(settings.Export.Preset) as string;
|
||||
if (id is null || ExportPresets.Find(id) is not { Width: > 0 } preset || (preset.Width <= width && preset.Height <= height)) return settings;
|
||||
return settings with { Export = settings.Export with { Overrides = settings.Export.Overrides with { Width = width, Height = height } } };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,217 @@
|
||||
using System.Globalization;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using Titano.Core.Analysis;
|
||||
using Titano.Core.Analysis.Deep;
|
||||
using Titano.Core.Export;
|
||||
using Titano.Core.Localization;
|
||||
using Titano.Core.Project;
|
||||
using Titano.Core.Video;
|
||||
|
||||
namespace Titano.Core.Advisor;
|
||||
|
||||
/// <summary>
|
||||
/// A one-click bundle (BRIEF §10.3): full project settings plus an export preset, named by a resource key and
|
||||
/// arguments (culture-neutral numbers or tokens) or, for user presets, by the user's own <see cref="Name"/>.
|
||||
/// </summary>
|
||||
public sealed record SequencePreset
|
||||
{
|
||||
/// <summary>"night-sky", "holy-grail", "construction", "social-vertical", "standard", or a user id.</summary>
|
||||
public required string Id { get; init; }
|
||||
|
||||
public required string NameKey { get; init; }
|
||||
public IReadOnlyList<string> NameArgs { get; init; } = [];
|
||||
|
||||
/// <summary>The user's name for a saved preset; overrides <see cref="NameKey"/>.</summary>
|
||||
public string? Name { get; init; }
|
||||
|
||||
public string? ReasonKey { get; init; }
|
||||
public IReadOnlyList<string> ReasonArgs { get; init; } = [];
|
||||
public required ProjectSettings Settings { get; init; }
|
||||
public required string ExportPresetId { get; init; }
|
||||
|
||||
/// <summary>0..1: how well the measured content matches the preset.</summary>
|
||||
public double Confidence { get; init; }
|
||||
|
||||
public bool IsUser { get; init; }
|
||||
|
||||
public string DisplayName() => Name ?? Advisor.Explain(NameKey, NameArgs);
|
||||
|
||||
/// <summary>A copy saved under the user's name.</summary>
|
||||
public SequencePreset AsUserPreset(string name)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(name);
|
||||
return this with { Id = Guid.CreateVersion7().ToString("N"), Name = name.Trim(), IsUser = true };
|
||||
}
|
||||
|
||||
public string ToJson() => JsonSerializer.Serialize(this, AdvisorJson.Default.SequencePreset);
|
||||
|
||||
public static SequencePreset FromJson(string json) =>
|
||||
JsonSerializer.Deserialize(json, AdvisorJson.Default.SequencePreset) ?? throw new InvalidDataException("Preset JSON is empty.");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Generates the sequence presets that fit the measured content, best match first: Night sky (star field or night,
|
||||
/// 4K 10-bit HEVC 24 fps, deflicker, stabilise when shaky), Holy grail sunset (received exposure steps across a
|
||||
/// day/night change, 4K HEVC 30 fps, transitions), Construction cam (several sessions over at least a day, 1080p
|
||||
/// H.264 30 fps, adaptive timing), Standard when none of these match, and Social vertical (1080×1920) always last.
|
||||
/// A preset's export choice gives way to the advised one when the source, previews or encoders cannot reach it.
|
||||
/// Content values stay Auto with the advisor's reasons; the preset's own choices are stored as manual values.
|
||||
/// </summary>
|
||||
public static class SequencePresets
|
||||
{
|
||||
public static IReadOnlyList<SequencePreset> Generate(LightAnalysisReport light, DeepAnalysisReport? deep, SequenceContext context)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(light);
|
||||
ArgumentNullException.ThrowIfNull(context);
|
||||
var advice = Advisor.Recommend(light, deep, context);
|
||||
var advised = Advisor.Apply(new ProjectSettings(), advice);
|
||||
var exportId = advice.Find(AdvisorParameters.ExportPreset)?.Value as string ?? "1080p-h264";
|
||||
var presets = new List<SequencePreset>();
|
||||
|
||||
if (deep is { } d && (d.Sky.StarField || d.Sky.Light == DayNight.Night))
|
||||
{
|
||||
var id = Pick(exportId, "4k-hevc10-archive", context);
|
||||
var window = advised.Exposure.DeflickerWindow.AutoValue;
|
||||
var shaky = advice.Find(AdvisorParameters.Stabilize)?.Value is true;
|
||||
var settings = Manual(advised, id, "24") with { Exposure = advised.Exposure with { Deflicker = advised.Exposure.Deflicker.WithManual(true) } };
|
||||
if (shaky) settings = settings with { Motion = settings.Motion with { Stabilize = settings.Motion.Stabilize.WithManual(true) } };
|
||||
var stars = d.Sky.StarField ? 100.0 * d.Sky.StarFrames / int.Max(1, d.FrameCount) : 0;
|
||||
presets.Add(new SequencePreset
|
||||
{
|
||||
Id = "night-sky",
|
||||
NameKey = shaky ? AdvisorKeys.PresetNightSkyStabilised : AdvisorKeys.PresetNightSky,
|
||||
NameArgs = [Label(id), CodecLabel(id), "24", Text(window)],
|
||||
ReasonKey = AdvisorKeys.PresetReasonNightSky,
|
||||
ReasonArgs = [Text(double.Round(stars))],
|
||||
Settings = settings,
|
||||
ExportPresetId = id,
|
||||
Confidence = d.Sky.StarField ? 0.9 : 0.7,
|
||||
});
|
||||
}
|
||||
|
||||
var received = deep?.Exposure.ReceivedSteps ?? (light.ExposureValues.Any(v => v is not null) ? light.ExposureSteps.Count : 0);
|
||||
var lightChange = deep is not null
|
||||
? deep.Sky.Light is DayNight.DayToNight or DayNight.NightToDay || deep.Exposure.SceneRangeEv >= 3
|
||||
: light.Findings.Any(f => f.Key == FindingKeys.DayNightTransition);
|
||||
if (received > 0 && lightChange)
|
||||
{
|
||||
var id = Pick(exportId, "4k-hevc", context);
|
||||
var transitions = advised.Exposure.TransitionLength.AutoValue;
|
||||
var range = deep?.Exposure.SceneRangeEv ?? 0;
|
||||
var settings = Manual(advised, id, "30") with
|
||||
{
|
||||
Exposure = advised.Exposure with
|
||||
{
|
||||
HolyGrail = advised.Exposure.HolyGrail.WithManual(true),
|
||||
Deflicker = advised.Exposure.Deflicker.WithManual(true),
|
||||
},
|
||||
};
|
||||
presets.Add(new SequencePreset
|
||||
{
|
||||
Id = "holy-grail",
|
||||
NameKey = AdvisorKeys.PresetHolyGrail,
|
||||
NameArgs = [Label(id), CodecLabel(id), "30", Text(transitions)],
|
||||
ReasonKey = AdvisorKeys.PresetReasonHolyGrail,
|
||||
ReasonArgs = [Text(received), Text(double.Round(range, 1))],
|
||||
Settings = settings,
|
||||
ExportPresetId = id,
|
||||
Confidence = 0.85,
|
||||
});
|
||||
}
|
||||
|
||||
if (light.Sessions.Count >= 2 && light.CaptureSpan >= TimeSpan.FromDays(1))
|
||||
{
|
||||
var id = Pick(exportId, "1080p-h264", context);
|
||||
var settings = Manual(advised, id, "30");
|
||||
settings = settings with { Timing = settings.Timing with { Mode = settings.Timing.Mode.WithManual(TimingMode.Adaptive) } };
|
||||
presets.Add(new SequencePreset
|
||||
{
|
||||
Id = "construction",
|
||||
NameKey = AdvisorKeys.PresetConstruction,
|
||||
NameArgs = [Label(id), CodecLabel(id), "30"],
|
||||
ReasonKey = AdvisorKeys.PresetReasonConstruction,
|
||||
ReasonArgs = [Text(light.Sessions.Count), Text(double.Round(light.CaptureSpan.TotalDays, 1))],
|
||||
Settings = settings,
|
||||
ExportPresetId = id,
|
||||
Confidence = 0.8,
|
||||
});
|
||||
}
|
||||
|
||||
if (presets.Count == 0)
|
||||
{
|
||||
var fps = advised.Timing.FrameRate.AutoValue ?? ExportPresets.Find(exportId)?.FrameRate.ToString() ?? "30";
|
||||
presets.Add(new SequencePreset
|
||||
{
|
||||
Id = "standard",
|
||||
NameKey = AdvisorKeys.PresetStandard,
|
||||
NameArgs = [Label(exportId), CodecLabel(exportId), fps],
|
||||
ReasonKey = AdvisorKeys.PresetReasonStandard,
|
||||
Settings = Manual(advised, exportId, null),
|
||||
ExportPresetId = exportId,
|
||||
Confidence = 0.6,
|
||||
});
|
||||
}
|
||||
|
||||
const string vertical = "vertical-1080x1920";
|
||||
var social = Manual(advised, vertical, "30") with { Camera = advised.Camera with { Aspect = advised.Camera.Aspect.WithManual("9:16"), OffsetY = 0 } };
|
||||
presets.Add(new SequencePreset
|
||||
{
|
||||
Id = "social-vertical",
|
||||
NameKey = AdvisorKeys.PresetSocialVertical,
|
||||
NameArgs = ["1080", "1920"],
|
||||
ReasonKey = AdvisorKeys.PresetReasonSocialVertical,
|
||||
Settings = social,
|
||||
ExportPresetId = vertical,
|
||||
Confidence = 0.4,
|
||||
});
|
||||
return [.. presets.OrderByDescending(p => p.Confidence)];
|
||||
}
|
||||
|
||||
/// <summary>The preset's own export choice when the advised size reaches 4K, else the advised (capped) preset.</summary>
|
||||
private static string Pick(string advised, string wanted, SequenceContext context)
|
||||
{
|
||||
var cap = ExportPresets.Find(advised);
|
||||
var target = ExportPresets.Find(wanted)!;
|
||||
var codecOk = context.Codecs.Count == 0 || context.Codecs.Any(c => c.Codec == target.Codec && (target.BitDepth <= 8 || c.SupportsTenBit));
|
||||
return cap is not null && cap.Width >= target.Width && cap.Height >= target.Height && codecOk ? wanted : advised;
|
||||
}
|
||||
|
||||
/// <summary>Export preset and (optionally) frame rate as the preset's manual choices.</summary>
|
||||
private static ProjectSettings Manual(ProjectSettings settings, string exportId, string? frameRate)
|
||||
{
|
||||
settings = settings with { Export = settings.Export with { Preset = settings.Export.Preset.WithManual(exportId) } };
|
||||
return frameRate is null ? settings : settings with { Timing = settings.Timing with { FrameRate = settings.Timing.FrameRate.WithManual(frameRate) } };
|
||||
}
|
||||
|
||||
/// <summary>Resolution label of an export preset ("4K", "1440p", "1080p", …).</summary>
|
||||
private static string Label(string exportId) => ExportPresets.Find(exportId) switch
|
||||
{
|
||||
{ Width: >= 3840 } => "4K",
|
||||
{ Width: > 0 } p => string.Create(CultureInfo.InvariantCulture, $"{int.Min(p.Width, p.Height)}p"),
|
||||
_ => exportId,
|
||||
};
|
||||
|
||||
/// <summary>Codec label of an export preset ("HEVC Main10", "HEVC", "H.264", "AV1"): technical names, not translated.</summary>
|
||||
private static string CodecLabel(string exportId) => ExportPresets.Find(exportId) switch
|
||||
{
|
||||
{ Codec: VideoCodec.Hevc, BitDepth: >= 10 } => "HEVC Main10",
|
||||
{ Codec: VideoCodec.Hevc } => "HEVC",
|
||||
{ Codec: VideoCodec.Av1 } => "AV1",
|
||||
{ Codec: VideoCodec.H264 } => "H.264",
|
||||
{ } p => p.Codec.ToString(),
|
||||
_ => exportId,
|
||||
};
|
||||
|
||||
private static string Text<T>(T value) => Convert.ToString(value, CultureInfo.InvariantCulture) ?? string.Empty;
|
||||
}
|
||||
|
||||
/// <summary>Source-generated JSON for saved sequence presets.</summary>
|
||||
[JsonSourceGenerationOptions(
|
||||
WriteIndented = true,
|
||||
PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase,
|
||||
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
|
||||
UseStringEnumConverter = true,
|
||||
PropertyNameCaseInsensitive = true)]
|
||||
[JsonSerializable(typeof(SequencePreset))]
|
||||
internal sealed partial class AdvisorJson : JsonSerializerContext;
|
||||
@@ -0,0 +1,84 @@
|
||||
using Titano.Core.Imaging;
|
||||
using Titano.Core.Mathematics;
|
||||
|
||||
namespace Titano.Core.Analysis.Deep;
|
||||
|
||||
/// <summary>
|
||||
/// Cloud coverage estimate (BRIEF §10.2) from sky texture: the sky (weight ≥ 0.9 of a <see cref="RegionMask"/>) is
|
||||
/// cut into square blocks and a block is cloudy when the 30th percentile of |Laplacian| of its sRGB-encoded luminance
|
||||
/// exceeds max(<see cref="NoiseFactor"/>·σ, <see cref="MinimumTexture"/>). σ is the 10th percentile of the blocks'
|
||||
/// Immerkær (1996) noise estimates, so the clouds' own texture does not raise the noise floor. Cloud texture lifts nearly every pixel of a block while stars touch a few, so the low percentile ignores
|
||||
/// star fields; the Laplacian ignores smooth sky gradients. A uniform overcast reads as clear sky.
|
||||
/// </summary>
|
||||
public static class CloudCoverage
|
||||
{
|
||||
/// <summary>The 30th percentile of |Laplacian| of pure Gaussian noise is ≈ 1.7σ, so this is 3.5 × the noise level.</summary>
|
||||
public const double NoiseFactor = 6;
|
||||
|
||||
public const double MinimumTexture = 0.004;
|
||||
|
||||
/// <summary>Fraction of sky blocks that are cloudy; NaN when no block is sky.</summary>
|
||||
public static double Estimate(ImageBuffer image, ReadOnlySpan<float> skyWeights, int block = 8)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(image);
|
||||
ArgumentOutOfRangeException.ThrowIfLessThan(block, 3);
|
||||
if (skyWeights.Length != image.PlaneLength) throw new ArgumentException("One sky weight per pixel is required.", nameof(skyWeights));
|
||||
int w = image.Width, h = image.Height;
|
||||
if (w < 3 || h < 3) return double.NaN;
|
||||
var e = new float[image.PlaneLength];
|
||||
ColorSpace.Luminance(image, e);
|
||||
for (var i = 0; i < e.Length; i++) e[i] = ColorSpace.EncodeFast(e[i]);
|
||||
var threshold = double.Max(NoiseFactor * Noise(e, w, h, block), MinimumTexture);
|
||||
|
||||
var values = new double[block * block];
|
||||
int sky = 0, cloudy = 0;
|
||||
for (var by = 0; by + block <= h; by += block)
|
||||
{
|
||||
for (var bx = 0; bx + block <= w; bx += block)
|
||||
{
|
||||
double weight = 0;
|
||||
var count = 0;
|
||||
for (var y = by; y < by + block; y++)
|
||||
{
|
||||
for (var x = bx; x < bx + block; x++)
|
||||
{
|
||||
var i = y * w + x;
|
||||
weight += skyWeights[i];
|
||||
if (x == 0 || y == 0 || x == w - 1 || y == h - 1) continue;
|
||||
values[count++] = double.Abs(e[i - 1] + e[i + 1] + e[i - w] + e[i + w] - 4.0 * e[i]);
|
||||
}
|
||||
}
|
||||
if (weight < 0.9 * block * block || count == 0) continue;
|
||||
sky++;
|
||||
if (Statistics.Select(values.AsSpan(0, count), (int)(0.3 * (count - 1))) > threshold) cloudy++;
|
||||
}
|
||||
}
|
||||
return sky > 0 ? (double)cloudy / sky : double.NaN;
|
||||
}
|
||||
|
||||
/// <summary>10th percentile over whole blocks of the Immerkær fast noise σ (interior pixels only).</summary>
|
||||
private static double Noise(float[] e, int w, int h, int block)
|
||||
{
|
||||
var estimates = new List<double>();
|
||||
for (var by = 0; by + block <= h; by += block)
|
||||
{
|
||||
for (var bx = 0; bx + block <= w; bx += block)
|
||||
{
|
||||
double sum = 0;
|
||||
var count = 0;
|
||||
for (var y = int.Max(1, by); y < int.Min(h - 1, by + block); y++)
|
||||
{
|
||||
for (var x = int.Max(1, bx); x < int.Min(w - 1, bx + block); x++)
|
||||
{
|
||||
var i = y * w + x;
|
||||
sum += double.Abs(e[i - w - 1] + e[i - w + 1] + e[i + w - 1] + e[i + w + 1]
|
||||
- 2.0 * (e[i - w] + e[i + w] + e[i - 1] + e[i + 1]) + 4.0 * e[i]);
|
||||
count++;
|
||||
}
|
||||
}
|
||||
if (count > 0) estimates.Add(double.Sqrt(double.Pi / 2) / 6 * sum / count);
|
||||
}
|
||||
}
|
||||
return estimates.Count > 0 ? Statistics.Percentile(estimates.ToArray(), 0.1) : 0;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace Titano.Core.Analysis.Deep;
|
||||
|
||||
/// <summary>
|
||||
/// Where <see cref="DeepAnalyzer"/> persists per-frame results while it runs, so a crashed or cancelled analysis
|
||||
/// resumes after the last persisted frame.
|
||||
/// </summary>
|
||||
public interface IDeepAnalysisCheckpoint
|
||||
{
|
||||
/// <summary>
|
||||
/// Frames persisted by an earlier run with the same <paramref name="fingerprint"/>, in index order from 0. A store
|
||||
/// holding another fingerprint discards its content and starts over.
|
||||
/// </summary>
|
||||
ValueTask<IReadOnlyList<DeepFrame>> LoadAsync(string fingerprint, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>Persists the next frames (consecutive indices) durably before returning.</summary>
|
||||
ValueTask AppendAsync(IReadOnlyList<DeepFrame> frames, CancellationToken cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Checkpoint as a JSON-lines file (e.g. <c>.titano/analysis.partial</c>): a header line with the fingerprint, then
|
||||
/// one <see cref="DeepFrame"/> per line, flushed to disk after every batch. A torn last line from a crash is dropped
|
||||
/// on load. Delete the file once the final report is saved.
|
||||
/// </summary>
|
||||
public sealed class DeepAnalysisCheckpointFile(string path) : IDeepAnalysisCheckpoint
|
||||
{
|
||||
/// <summary>Conventional file name next to <see cref="DeepAnalysisReport.FileName"/>.</summary>
|
||||
public const string FileName = "analysis.partial";
|
||||
|
||||
private static readonly UTF8Encoding Utf8 = new(false);
|
||||
|
||||
public string Path { get; } = path;
|
||||
|
||||
public async ValueTask<IReadOnlyList<DeepFrame>> LoadAsync(string fingerprint, CancellationToken cancellationToken)
|
||||
{
|
||||
var frames = new List<DeepFrame>();
|
||||
if (File.Exists(Path))
|
||||
{
|
||||
var bytes = await File.ReadAllBytesAsync(Path, cancellationToken).ConfigureAwait(false);
|
||||
var valid = Parse(bytes, fingerprint, frames);
|
||||
if (valid > 0)
|
||||
{
|
||||
// Cut a torn or foreign tail so later appends continue a well-formed file.
|
||||
await using var stream = new FileStream(Path, FileMode.Open, FileAccess.Write, FileShare.None);
|
||||
stream.SetLength(valid);
|
||||
return frames;
|
||||
}
|
||||
}
|
||||
var header = JsonSerializer.Serialize(new CheckpointHeader(fingerprint), DeepCheckpointJson.Default.CheckpointHeader) + "\n";
|
||||
Directory.CreateDirectory(System.IO.Path.GetDirectoryName(System.IO.Path.GetFullPath(Path))!);
|
||||
await File.WriteAllBytesAsync(Path, Utf8.GetBytes(header), cancellationToken).ConfigureAwait(false);
|
||||
return frames;
|
||||
}
|
||||
|
||||
public async ValueTask AppendAsync(IReadOnlyList<DeepFrame> frames, CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(frames);
|
||||
var text = new StringBuilder();
|
||||
foreach (var frame in frames) text.Append(JsonSerializer.Serialize(frame, DeepCheckpointJson.Default.DeepFrame)).Append('\n');
|
||||
await using var stream = new FileStream(Path, FileMode.Append, FileAccess.Write, FileShare.None);
|
||||
await stream.WriteAsync(Utf8.GetBytes(text.ToString()), cancellationToken).ConfigureAwait(false);
|
||||
stream.Flush(flushToDisk: true);
|
||||
}
|
||||
|
||||
public void Delete()
|
||||
{
|
||||
if (File.Exists(Path)) File.Delete(Path);
|
||||
}
|
||||
|
||||
/// <summary>Reads the header and the contiguous frames after it; returns the byte length of the valid prefix
|
||||
/// (0 when the header is missing or belongs to another fingerprint).</summary>
|
||||
private static int Parse(byte[] bytes, string fingerprint, List<DeepFrame> frames)
|
||||
{
|
||||
var offset = 0;
|
||||
var valid = 0;
|
||||
var line = 0;
|
||||
while (offset < bytes.Length)
|
||||
{
|
||||
var end = Array.IndexOf(bytes, (byte)'\n', offset);
|
||||
if (end < 0) break;
|
||||
var span = bytes.AsSpan(offset, end - offset);
|
||||
try
|
||||
{
|
||||
if (line == 0)
|
||||
{
|
||||
if (JsonSerializer.Deserialize(span, DeepCheckpointJson.Default.CheckpointHeader)?.Fingerprint != fingerprint) return 0;
|
||||
}
|
||||
else
|
||||
{
|
||||
var frame = JsonSerializer.Deserialize(span, DeepCheckpointJson.Default.DeepFrame);
|
||||
if (frame is null || frame.Index != frames.Count) break;
|
||||
frames.Add(frame);
|
||||
}
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
if (line == 0) return 0;
|
||||
break;
|
||||
}
|
||||
line++;
|
||||
offset = end + 1;
|
||||
valid = offset;
|
||||
}
|
||||
return valid;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace Titano.Core.Analysis.Deep;
|
||||
|
||||
/// <summary>Source-generated JSON for <c>analysis.json</c> and the database summary: compact, camelCase, enums as names.</summary>
|
||||
[JsonSourceGenerationOptions(
|
||||
PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase,
|
||||
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
|
||||
UseStringEnumConverter = true,
|
||||
PropertyNameCaseInsensitive = true)]
|
||||
[JsonSerializable(typeof(DeepAnalysisReport))]
|
||||
[JsonSerializable(typeof(AnalysisSummary))]
|
||||
internal sealed partial class DeepAnalysisJson : JsonSerializerContext;
|
||||
|
||||
/// <summary>Checkpoint lines: exact doubles, NaN written as a literal so unmeasured values survive a resume.</summary>
|
||||
[JsonSourceGenerationOptions(
|
||||
PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase,
|
||||
NumberHandling = JsonNumberHandling.AllowNamedFloatingPointLiterals,
|
||||
UseStringEnumConverter = true)]
|
||||
[JsonSerializable(typeof(DeepFrame))]
|
||||
[JsonSerializable(typeof(CheckpointHeader))]
|
||||
internal sealed partial class DeepCheckpointJson : JsonSerializerContext;
|
||||
|
||||
/// <summary>First line of a checkpoint file.</summary>
|
||||
internal sealed record CheckpointHeader(string Fingerprint);
|
||||
@@ -0,0 +1,69 @@
|
||||
using System.Globalization;
|
||||
|
||||
namespace Titano.Core.Analysis.Deep;
|
||||
|
||||
/// <summary>Parameters of <see cref="DeepAnalyzer"/>; every value enters the checkpoint fingerprint.</summary>
|
||||
public sealed record DeepAnalysisOptions
|
||||
{
|
||||
public static DeepAnalysisOptions Default { get; } = new();
|
||||
|
||||
/// <summary>Upper bound of the analysis long edge (BRIEF §10.2: half native, capped at 2048).</summary>
|
||||
public int MaxAnalysisLongEdge { get; init; } = 2048;
|
||||
|
||||
/// <summary>Sources smaller than twice this are analysed at this size (or native when smaller).</summary>
|
||||
public int MinAnalysisLongEdge { get; init; } = 512;
|
||||
|
||||
/// <summary>Long edge of the plane the per-frame shift is measured on (nine phase-correlation patches).</summary>
|
||||
public int CorrelationLongEdge { get; init; } = 1024;
|
||||
|
||||
/// <summary>Long edge of the optical-flow images (Draft quality).</summary>
|
||||
public int FlowLongEdge { get; init; } = 512;
|
||||
|
||||
/// <summary>Optical flow runs on the pair (k − 1, k) for every k divisible by this.</summary>
|
||||
public int FlowEvery { get; init; } = 10;
|
||||
|
||||
/// <summary>Long edge of the thumbnails used for regions and cloud coverage.</summary>
|
||||
public int ThumbnailLongEdge { get; init; } = 256;
|
||||
|
||||
/// <summary>Frames sampled evenly for the sky/land mask.</summary>
|
||||
public int RegionSampleFrames { get; init; } = 15;
|
||||
|
||||
/// <summary>Frames whose trimmed mean log2 luminance is at or below this are dark (night) frames.</summary>
|
||||
public double DarkLogLuminance { get; init; } = -4;
|
||||
|
||||
/// <summary>Point sources per megapixel from which a dark frame shows a star field.</summary>
|
||||
public double StarFieldDensity { get; init; } = 30;
|
||||
|
||||
/// <summary>Smallest exposure-aligned histogram distance that can be a scene change.</summary>
|
||||
public double SceneChangeMinimum { get; init; } = 0.25;
|
||||
|
||||
/// <summary>σ (frames) of the camera-path smoothing used for the shake measure (as <c>StabilizerOptions</c>).</summary>
|
||||
public double ShakeSmoothingSigma { get; init; } = 12;
|
||||
|
||||
/// <summary>Frames measured concurrently; also the batch size between checkpoints.</summary>
|
||||
public int MaxDegreeOfParallelism { get; init; } = int.Clamp(Environment.ProcessorCount, 1, 4);
|
||||
|
||||
/// <summary>Analysis long edge for a source whose oriented long edge is <paramref name="sourceLongEdge"/> (0 = unknown).</summary>
|
||||
public int AnalysisLongEdge(int sourceLongEdge)
|
||||
{
|
||||
if (sourceLongEdge <= 0) return MaxAnalysisLongEdge;
|
||||
var half = (sourceLongEdge + 1) / 2;
|
||||
return int.Min(sourceLongEdge, int.Min(MaxAnalysisLongEdge, int.Max(MinAnalysisLongEdge, half)));
|
||||
}
|
||||
|
||||
/// <summary>Stable text of every value that changes per-frame results (parallelism excluded).</summary>
|
||||
public string Fingerprint() => string.Create(CultureInfo.InvariantCulture,
|
||||
$"edge={MinAnalysisLongEdge}-{MaxAnalysisLongEdge};corr={CorrelationLongEdge};flow={FlowLongEdge}/{FlowEvery};thumb={ThumbnailLongEdge};regions={RegionSampleFrames};dark={DarkLogLuminance}");
|
||||
|
||||
internal void Validate()
|
||||
{
|
||||
ArgumentOutOfRangeException.ThrowIfLessThan(MinAnalysisLongEdge, 16);
|
||||
ArgumentOutOfRangeException.ThrowIfLessThan(MaxAnalysisLongEdge, MinAnalysisLongEdge);
|
||||
ArgumentOutOfRangeException.ThrowIfLessThan(CorrelationLongEdge, 16);
|
||||
ArgumentOutOfRangeException.ThrowIfLessThan(FlowLongEdge, 16);
|
||||
ArgumentOutOfRangeException.ThrowIfLessThan(FlowEvery, 1);
|
||||
ArgumentOutOfRangeException.ThrowIfLessThan(ThumbnailLongEdge, 16);
|
||||
ArgumentOutOfRangeException.ThrowIfLessThan(RegionSampleFrames, 1);
|
||||
ArgumentOutOfRangeException.ThrowIfLessThan(MaxDegreeOfParallelism, 1);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,226 @@
|
||||
using System.Text.Json;
|
||||
using Titano.Core.IO;
|
||||
|
||||
namespace Titano.Core.Analysis.Deep;
|
||||
|
||||
/// <summary>Light condition of a whole sequence.</summary>
|
||||
public enum DayNight
|
||||
{
|
||||
Unknown,
|
||||
Day,
|
||||
Night,
|
||||
DayToNight,
|
||||
NightToDay,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Per-frame series of the report as compact parallel arrays (one entry per frame, null = not measured), rounded to
|
||||
/// what charts and render rules need (~100 bytes per frame in JSON). Shifts and motion are in source pixels.
|
||||
/// </summary>
|
||||
public sealed record DeepFrameColumns
|
||||
{
|
||||
/// <summary>Trimmed mean log2 luminance, 0.001 EV.</summary>
|
||||
public double?[] LogLuminance { get; init; } = [];
|
||||
|
||||
public double?[] ClipLow { get; init; } = [];
|
||||
public double?[] ClipHigh { get; init; } = [];
|
||||
|
||||
/// <summary>log2(R/G) and log2(B/G) of the mean colour, 0.001.</summary>
|
||||
public double?[] RedRatio { get; init; } = [];
|
||||
|
||||
public double?[] BlueRatio { get; init; } = [];
|
||||
|
||||
/// <summary>Correlated colour temperature in kelvin, null when not near-Planckian.</summary>
|
||||
public double?[] Kelvin { get; init; } = [];
|
||||
|
||||
/// <summary>Laplacian variance and robust noise σ of sRGB-encoded luminance, two significant digits.</summary>
|
||||
public double?[] Sharpness { get; init; } = [];
|
||||
|
||||
public double?[] Noise { get; init; } = [];
|
||||
|
||||
/// <summary>Content motion from the previous usable frame, 0.01 px.</summary>
|
||||
public double?[] ShiftX { get; init; } = [];
|
||||
|
||||
public double?[] ShiftY { get; init; } = [];
|
||||
|
||||
/// <summary>Stars per megapixel of the analysis image (dark frames only).</summary>
|
||||
public double?[] StarDensity { get; init; } = [];
|
||||
|
||||
public double?[] CloudCoverage { get; init; } = [];
|
||||
public double?[] SkyLogLuminance { get; init; } = [];
|
||||
public double?[] LandLogLuminance { get; init; } = [];
|
||||
public double?[] SceneDistance { get; init; } = [];
|
||||
|
||||
/// <summary><see cref="DeepFrameFlags"/> per frame.</summary>
|
||||
public int[] Flags { get; init; } = [];
|
||||
|
||||
/// <summary>Frames k whose optical flow from k − 1 was sampled, with median and 95th-percentile magnitude (px per frame).</summary>
|
||||
public int[] MotionFrames { get; init; } = [];
|
||||
|
||||
public double[] MotionMedian { get; init; } = [];
|
||||
public double[] MotionP95 { get; init; } = [];
|
||||
|
||||
public DeepFrameFlags FlagsOf(int index) => (DeepFrameFlags)Flags[index];
|
||||
}
|
||||
|
||||
/// <param name="AmplitudeEv">RMS deviation of the step-free luminance from its smooth curve.</param>
|
||||
/// <param name="FrameToFrameEv">RMS frame-to-frame flicker relative to the curve (<see cref="DeflickerDiagnostics.FlickerBefore"/>).</param>
|
||||
/// <param name="PeriodFrames">Period of periodic flicker (<see cref="FlickerSpectrumResult.DominantPeriod"/>).</param>
|
||||
/// <param name="RecommendedWindow">Deflicker window: 4 × period or correlation length, odd, bounded.</param>
|
||||
public sealed record FlickerSummary(double AmplitudeEv, double FrameToFrameEv, double? PeriodFrames, double PeakCorrelation, double CorrelationLength, int RecommendedWindow);
|
||||
|
||||
/// <param name="Horizon">Horizon row / mask height at up to 64 evenly spaced columns (horizon method only).</param>
|
||||
/// <param name="DivergenceEv">RMS of the difference between the sky and land residuals: how independently they flicker.</param>
|
||||
public sealed record RegionSummary(RegionMethod Method, double Confidence, double SkyFraction, int MaskWidth, int MaskHeight, double[]? Horizon, double DivergenceEv);
|
||||
|
||||
/// <summary>One metadata exposure step as the pixels received it (<see cref="ExposureTransition"/>).</summary>
|
||||
public sealed record ExposureStepSummary(int Index, double ExpectedEv, double? MeasuredEv, bool Received, double Length);
|
||||
|
||||
/// <param name="TypicalSpacing">Median frames between received steps (two or more received).</param>
|
||||
/// <param name="TransitionLength">Half the typical spacing, 12 for a single step, null without received steps.</param>
|
||||
/// <param name="SceneRangeEv">5–95 % range of the step-free luminance: how much the light itself changed.</param>
|
||||
public sealed record ExposureSummary(int MetadataSteps, int ReceivedSteps, double? TypicalSpacing, int? TransitionLength, double SceneRangeEv, IReadOnlyList<ExposureStepSummary> Steps);
|
||||
|
||||
/// <param name="JitterLog2">RMS frame-to-frame colour-ratio deviation from the smoothed ratios (log2 units).</param>
|
||||
/// <param name="DriftLog2">Largest range of the smoothed colour ratios (slow, deliberate change).</param>
|
||||
public sealed record WhiteBalanceSummary(double JitterLog2, double DriftLog2, double? KelvinLow, double? KelvinHigh);
|
||||
|
||||
/// <param name="RmsPx">RMS distance of the camera path from its smoothed path, source pixels.</param>
|
||||
/// <param name="CropCost">Area fraction a centred crop must give up to hide every correction.</param>
|
||||
/// <param name="PanPxPerFrame">Average drift of the smoothed path.</param>
|
||||
/// <param name="MeasuredFraction">Share of frame pairs whose shift could be measured (textured patches).</param>
|
||||
public sealed record ShakeSummary(double RmsPx, double MaxPx, double CropCost, double PanPxPerFrame, bool PanDetected, double MeasuredFraction);
|
||||
|
||||
/// <param name="MedianPx">Median of the sampled pairs' median flow magnitude, source px per frame.</param>
|
||||
/// <param name="P95Px">Median of the sampled pairs' 95th-percentile magnitude: the typical speed of moving content.</param>
|
||||
public sealed record MotionSummary(int Pairs, double? MedianPx, double? P95Px, double? MaxP95Px);
|
||||
|
||||
/// <param name="StarDensity">Median stars per megapixel over dark frames.</param>
|
||||
/// <param name="CloudCoverage">Mean cloudy fraction of the sky.</param>
|
||||
public sealed record SkySummary(DayNight Light, double DarkFraction, int DarkFrames, int StarFrames, double? StarDensity, bool StarField, double? CloudCoverage);
|
||||
|
||||
public sealed record FrameIssues(int[] Undecodable, int[] Black, int[] White, int[] Duplicate, int[] SceneChanges)
|
||||
{
|
||||
/// <summary>Every frame that would flash or stutter in a render, ascending.</summary>
|
||||
public int[] Excludable() => [.. Undecodable.Concat(Black).Concat(White).Concat(Duplicate).Distinct().Order()];
|
||||
}
|
||||
|
||||
/// <summary>A <see cref="Finding"/> with numeric arguments, so the report round-trips through JSON.</summary>
|
||||
public sealed record DeepFinding(string Key, FindingSeverity Severity, double[] Arguments, int[] Frames)
|
||||
{
|
||||
public Finding ToFinding() => new(Key, Severity, [.. Arguments.Cast<object>()], Frames);
|
||||
}
|
||||
|
||||
/// <summary>Resource keys of the findings produced by the deep analysis; arguments are numbers.</summary>
|
||||
public static class DeepFindingKeys
|
||||
{
|
||||
public const string UnreadableFrames = "Advisor.Finding.UnreadableFrames";
|
||||
public const string BlackFrames = "Advisor.Finding.BlackFrames";
|
||||
public const string WhiteFrames = "Advisor.Finding.WhiteFrames";
|
||||
public const string DuplicateFrames = "Advisor.Finding.DuplicateFrames";
|
||||
public const string SceneChanges = "Advisor.Finding.SceneChanges";
|
||||
public const string Flicker = "Advisor.Finding.Flicker";
|
||||
public const string Shake = "Advisor.Finding.Shake";
|
||||
public const string Panning = "Advisor.Finding.Panning";
|
||||
public const string StarField = "Advisor.Finding.StarField";
|
||||
public const string Clouds = "Advisor.Finding.Clouds";
|
||||
public const string WhiteBalanceJitter = "Advisor.Finding.WhiteBalanceJitter";
|
||||
public const string StepsNotReceived = "Advisor.Finding.StepsNotReceived";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Result of the deep analysis (BRIEF §10.2), stored as <c>.titano/analysis.json</c>. Versioned; per-frame data is
|
||||
/// columnar (<see cref="DeepFrameColumns"/>), sequence-level results are small records.
|
||||
/// </summary>
|
||||
public sealed record DeepAnalysisReport
|
||||
{
|
||||
public const int CurrentVersion = 1;
|
||||
|
||||
/// <summary>File name inside a sequence's <c>.titano</c> folder.</summary>
|
||||
public const string FileName = "analysis.json";
|
||||
|
||||
public int Version { get; init; } = CurrentVersion;
|
||||
public int FrameCount { get; init; }
|
||||
|
||||
/// <summary>Dominant oriented source size from metadata (0 when unknown): the pixel unit of shifts and motion.</summary>
|
||||
public int SourceWidth { get; init; }
|
||||
|
||||
public int SourceHeight { get; init; }
|
||||
public int AnalysisLongEdge { get; init; }
|
||||
public DeepFrameColumns Frames { get; init; } = new();
|
||||
public required FlickerSummary Flicker { get; init; }
|
||||
public RegionSummary? Regions { get; init; }
|
||||
public required ExposureSummary Exposure { get; init; }
|
||||
public required WhiteBalanceSummary WhiteBalance { get; init; }
|
||||
public required ShakeSummary Shake { get; init; }
|
||||
public required MotionSummary Motion { get; init; }
|
||||
public required SkySummary Sky { get; init; }
|
||||
public required FrameIssues Issues { get; init; }
|
||||
|
||||
/// <summary>Suggested hero frame: sharp, well exposed, near golden hour or mid-sequence, not excluded.</summary>
|
||||
public int? HeroIndex { get; init; }
|
||||
|
||||
public IReadOnlyList<DeepFinding> Findings { get; init; } = [];
|
||||
|
||||
public string ToJson() => JsonSerializer.Serialize(this, DeepAnalysisJson.Default.DeepAnalysisReport);
|
||||
|
||||
public static DeepAnalysisReport FromJson(string json)
|
||||
{
|
||||
var report = JsonSerializer.Deserialize(json, DeepAnalysisJson.Default.DeepAnalysisReport)
|
||||
?? throw new InvalidDataException("analysis.json is empty.");
|
||||
if (report.Version > CurrentVersion)
|
||||
throw new InvalidDataException($"analysis.json version {report.Version} is newer than this Titano ({CurrentVersion}).");
|
||||
return report;
|
||||
}
|
||||
|
||||
/// <summary>Writes the report atomically (temp file, flush, rename).</summary>
|
||||
public void Save(string path) => AtomicFile.WriteAllText(path, ToJson());
|
||||
|
||||
public static DeepAnalysisReport Load(string path) => FromJson(File.ReadAllText(path));
|
||||
}
|
||||
|
||||
/// <summary>Compact digest of a <see cref="DeepAnalysisReport"/> for the sequence row of the database (BRIEF §5).</summary>
|
||||
public sealed record AnalysisSummary
|
||||
{
|
||||
public int Version { get; init; } = DeepAnalysisReport.CurrentVersion;
|
||||
public int FrameCount { get; init; }
|
||||
public DayNight Light { get; init; }
|
||||
public double FlickerEv { get; init; }
|
||||
public double? FlickerPeriod { get; init; }
|
||||
|
||||
/// <summary>Shake RMS in source pixels.</summary>
|
||||
public double ShakePx { get; init; }
|
||||
|
||||
/// <summary>Typical speed of moving content (<see cref="MotionSummary.P95Px"/>).</summary>
|
||||
public double? MotionPx { get; init; }
|
||||
|
||||
public bool StarField { get; init; }
|
||||
public double? StarDensity { get; init; }
|
||||
public double? CloudCoverage { get; init; }
|
||||
public int WarningCount { get; init; }
|
||||
public int? HeroIndex { get; init; }
|
||||
|
||||
public static AnalysisSummary From(DeepAnalysisReport report)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(report);
|
||||
return new AnalysisSummary
|
||||
{
|
||||
FrameCount = report.FrameCount,
|
||||
Light = report.Sky.Light,
|
||||
FlickerEv = report.Flicker.AmplitudeEv,
|
||||
FlickerPeriod = report.Flicker.PeriodFrames,
|
||||
ShakePx = report.Shake.RmsPx,
|
||||
MotionPx = report.Motion.P95Px,
|
||||
StarField = report.Sky.StarField,
|
||||
StarDensity = report.Sky.StarDensity,
|
||||
CloudCoverage = report.Sky.CloudCoverage,
|
||||
WarningCount = report.Findings.Count(f => f.Severity >= FindingSeverity.Warning),
|
||||
HeroIndex = report.HeroIndex,
|
||||
};
|
||||
}
|
||||
|
||||
public string ToJson() => JsonSerializer.Serialize(this, DeepAnalysisJson.Default.AnalysisSummary);
|
||||
|
||||
public static AnalysisSummary FromJson(string json) =>
|
||||
JsonSerializer.Deserialize(json, DeepAnalysisJson.Default.AnalysisSummary) ?? throw new InvalidDataException("Analysis summary is empty.");
|
||||
}
|
||||
@@ -0,0 +1,231 @@
|
||||
using System.Diagnostics;
|
||||
using Titano.Core.Imaging;
|
||||
using Titano.Core.Motion;
|
||||
|
||||
namespace Titano.Core.Analysis.Deep;
|
||||
|
||||
/// <summary>
|
||||
/// Deep analysis (BRIEF §10.2): one streaming pass over every frame. A pre-pass segments sky and land on a sample of
|
||||
/// thumbnails; then frames are probed in parallel batches (<see cref="FrameProbe"/>: statistics, stars, region
|
||||
/// luminance, clouds) and compared in order with the previous usable frame (nine-patch phase-correlation shift, duplicate
|
||||
/// test, exposure-aligned histogram distance, consistency-checked Draft optical flow on every
|
||||
/// <see cref="DeepAnalysisOptions.FlowEvery"/>-th pair). Memory is one batch of analysis images plus the previous frame's reduced planes. After every batch the new
|
||||
/// <see cref="DeepFrame"/>s go to the checkpoint, so an interrupted run resumes after the last persisted frame with
|
||||
/// identical results. Sequence-level results are computed by <see cref="DeepSequenceAnalysis"/>.
|
||||
/// </summary>
|
||||
public static class DeepAnalyzer
|
||||
{
|
||||
public static async Task<DeepAnalysisReport> AnalyzeAsync(
|
||||
IFrameSource source,
|
||||
DeepAnalysisOptions? options = null,
|
||||
IDeepAnalysisCheckpoint? checkpoint = null,
|
||||
IProgress<AnalysisProgress>? progress = null,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(source);
|
||||
options ??= DeepAnalysisOptions.Default;
|
||||
options.Validate();
|
||||
var n = source.Count;
|
||||
var metadata = new LightFrame[n];
|
||||
for (var i = 0; i < n; i++) metadata[i] = source.Metadata(i);
|
||||
|
||||
var frames = new DeepFrame[n];
|
||||
var start = 0;
|
||||
if (checkpoint is not null)
|
||||
{
|
||||
var saved = await checkpoint.LoadAsync(Fingerprint(n, options), cancellationToken).ConfigureAwait(false);
|
||||
while (start < saved.Count && start < n && saved[start].Index == start) frames[start] = saved[start++];
|
||||
}
|
||||
|
||||
var mask = n > 0 ? await FrameProbe.SegmentRegionsAsync(source, options, cancellationToken).ConfigureAwait(false) : null;
|
||||
using var state = new SequentialState(options);
|
||||
await PrimeAsync(source, frames, start, options, mask, state, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
var clock = Stopwatch.StartNew();
|
||||
var batch = options.MaxDegreeOfParallelism;
|
||||
for (var first = start; first < n; first += batch)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
var count = int.Min(batch, n - first);
|
||||
var tasks = new Task<FrameProbe>[count];
|
||||
for (var k = 0; k < count; k++)
|
||||
{
|
||||
var index = first + k;
|
||||
tasks[k] = Task.Run(() => FrameProbe.RunAsync(source, index, options, mask, cancellationToken), cancellationToken);
|
||||
}
|
||||
var produced = new DeepFrame[count];
|
||||
try
|
||||
{
|
||||
await Task.WhenAll(tasks).ConfigureAwait(false);
|
||||
for (var k = 0; k < count; k++) produced[k] = frames[first + k] = state.Next(tasks[k].Result, cancellationToken);
|
||||
}
|
||||
finally
|
||||
{
|
||||
foreach (var task in tasks)
|
||||
{
|
||||
if (task.IsCompletedSuccessfully) task.Result.Dispose();
|
||||
}
|
||||
}
|
||||
if (checkpoint is not null) await checkpoint.AppendAsync(produced, cancellationToken).ConfigureAwait(false);
|
||||
if (progress is not null)
|
||||
{
|
||||
var done = first + count;
|
||||
var rate = (done - start) / double.Max(clock.Elapsed.TotalSeconds, 1e-3);
|
||||
progress.Report(new AnalysisProgress(done, n, rate, TimeSpan.FromSeconds((n - done) / rate)));
|
||||
}
|
||||
}
|
||||
|
||||
return DeepSequenceAnalysis.Build(frames, metadata, mask, options);
|
||||
}
|
||||
|
||||
/// <summary>Identifies checkpoints written by this version for this frame count and these options.</summary>
|
||||
public static string Fingerprint(int frameCount, DeepAnalysisOptions options)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(options);
|
||||
return $"titano-deep/{DeepAnalysisReport.CurrentVersion};frames={frameCount};{options.Fingerprint()}";
|
||||
}
|
||||
|
||||
/// <summary>Restores the comparison state of a resumed run from the last usable frame before <paramref name="start"/>.</summary>
|
||||
private static async Task PrimeAsync(IFrameSource source, DeepFrame[] frames, int start, DeepAnalysisOptions options, RegionMask? mask, SequentialState state, CancellationToken cancellationToken)
|
||||
{
|
||||
var last = start - 1;
|
||||
while (last >= 0 && !frames[last].IsUsable) last--;
|
||||
if (last < 0) return;
|
||||
using var probe = await FrameProbe.RunAsync(source, last, options, mask, cancellationToken).ConfigureAwait(false);
|
||||
state.Next(probe, cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The order-dependent comparisons: each usable frame is compared with the previous usable frame and becomes the
|
||||
/// new reference; undecodable, black and white frames leave the state untouched.
|
||||
/// </summary>
|
||||
private sealed class SequentialState(DeepAnalysisOptions options) : IDisposable
|
||||
{
|
||||
private const int MinimumStabilizerSize = 16;
|
||||
private const float ReliableError = 0.5f;
|
||||
private const double MinimumReliable = 0.05;
|
||||
private readonly OpticalFlowEngine _flow = new(FlowQuality.Draft);
|
||||
private Stabilizer? _stabilizer;
|
||||
private FrameStatistics? _previous;
|
||||
private ImageBuffer? _previousFlow;
|
||||
private int _previousIndex = -1;
|
||||
|
||||
public DeepFrame Next(FrameProbe probe, CancellationToken cancellationToken)
|
||||
{
|
||||
if (probe.Statistics is not { } stats) return new DeepFrame { Index = probe.Index, Flags = DeepFrameFlags.Undecodable };
|
||||
var frame = Measured(probe.Index, stats);
|
||||
if (!probe.IsUsable) return frame;
|
||||
|
||||
var (shiftX, shiftY) = Shift(probe);
|
||||
var duplicate = _previous is not null && FrameStatistics.AreLikelyDuplicates(_previous, stats);
|
||||
var scene = _previous is null ? double.NaN : HistogramDistance.ExposureAligned(_previous, stats);
|
||||
var (motionMedian, motionP95) = Motion(probe, stats, cancellationToken);
|
||||
frame = frame with
|
||||
{
|
||||
Flags = frame.Flags | (duplicate ? DeepFrameFlags.Duplicate : DeepFrameFlags.None),
|
||||
Noise = probe.Noise,
|
||||
ShiftX = shiftX,
|
||||
ShiftY = shiftY,
|
||||
MotionMedian = motionMedian,
|
||||
MotionP95 = motionP95,
|
||||
StarDensity = probe.StarDensity,
|
||||
CloudCoverage = probe.CloudCoverage,
|
||||
SkyLogLuminance = probe.SkyLogLuminance,
|
||||
LandLogLuminance = probe.LandLogLuminance,
|
||||
SceneDistance = scene,
|
||||
};
|
||||
|
||||
_previous = stats;
|
||||
_previousIndex = probe.Index;
|
||||
_previousFlow?.Dispose();
|
||||
_previousFlow = probe.TakeFlow();
|
||||
return frame;
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_flow.Dispose();
|
||||
_stabilizer?.Dispose();
|
||||
_previousFlow?.Dispose();
|
||||
}
|
||||
|
||||
private DeepFrame Measured(int index, FrameStatistics stats)
|
||||
{
|
||||
var flags = DeepFrameFlags.None;
|
||||
if (stats.IsBlack()) flags |= DeepFrameFlags.Black;
|
||||
if (stats.IsWhite()) flags |= DeepFrameFlags.White;
|
||||
if (stats.MeanLogLuminance <= options.DarkLogLuminance) flags |= DeepFrameFlags.Dark;
|
||||
var green = stats.MeanGreen;
|
||||
return new DeepFrame
|
||||
{
|
||||
Index = index,
|
||||
Flags = flags,
|
||||
LogLuminance = stats.MeanLogLuminance,
|
||||
ClipLow = stats.ClipLowFraction,
|
||||
ClipHigh = stats.ClipHighFraction,
|
||||
RedRatio = stats.MeanRed > 0 && green > 0 ? double.Log2(stats.MeanRed / green) : double.NaN,
|
||||
BlueRatio = stats.MeanBlue > 0 && green > 0 ? double.Log2(stats.MeanBlue / green) : double.NaN,
|
||||
Kelvin = stats.ColorTemperature?.Kelvin ?? double.NaN,
|
||||
Sharpness = stats.Sharpness,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>Content motion at the centre of the correlation plane, in source pixels; NaN for the first frame of a
|
||||
/// size, too small planes and frames without textured patches.</summary>
|
||||
private (double X, double Y) Shift(FrameProbe probe)
|
||||
{
|
||||
int w = probe.CorrelationWidth, h = probe.CorrelationHeight;
|
||||
if (w < MinimumStabilizerSize || h < MinimumStabilizerSize || probe.Correlation is null) return (double.NaN, double.NaN);
|
||||
if (_stabilizer is null || _stabilizer.Width != w || _stabilizer.Height != h)
|
||||
{
|
||||
_stabilizer?.Dispose();
|
||||
_stabilizer = new Stabilizer(w, h);
|
||||
_stabilizer.AddFrame(probe.Correlation);
|
||||
return (double.NaN, double.NaN);
|
||||
}
|
||||
var motion = _stabilizer.AddFrame(probe.Correlation);
|
||||
if (!motion.Estimated) return (double.NaN, double.NaN);
|
||||
double cx = (w - 1) / 2.0, cy = (h - 1) / 2.0;
|
||||
var (x, y) = motion.Transform.Apply(cx, cy);
|
||||
return ((x - cx) * probe.CorrelationScale, (y - cy) * probe.CorrelationScale);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Draft flow from the previous frame, with the current frame brought to the previous mean level so flicker and
|
||||
/// exposure steps do not read as motion. Only vectors that pass the forward–backward check (error ≤
|
||||
/// <see cref="ReliableError"/> flow pixels) count, so flat noisy areas do not either; NaN when under
|
||||
/// <see cref="MinimumReliable"/> of the vectors are reliable. Magnitudes in source pixels per frame.
|
||||
/// </summary>
|
||||
private (double Median, double P95) Motion(FrameProbe probe, FrameStatistics stats, CancellationToken cancellationToken)
|
||||
{
|
||||
if (probe.Index % options.FlowEvery != 0 || _previousIndex != probe.Index - 1) return (double.NaN, double.NaN);
|
||||
if (probe.Flow is not { } current || _previousFlow is not { } previous || previous.Width != current.Width || previous.Height != current.Height)
|
||||
return (double.NaN, double.NaN);
|
||||
using var levelled = current.Clone();
|
||||
var gain = (float)double.Exp2(_previous!.MeanLogLuminance - stats.MeanLogLuminance);
|
||||
if (float.IsFinite(gain))
|
||||
{
|
||||
foreach (ref var v in levelled.Data) v *= gain;
|
||||
}
|
||||
var (forward, backward) = _flow.ComputeBidirectional(previous, levelled, cancellationToken);
|
||||
using (forward)
|
||||
using (backward)
|
||||
{
|
||||
var u = forward.U;
|
||||
var w = forward.V;
|
||||
var error = forward.Error;
|
||||
var magnitudes = new float[forward.Count];
|
||||
var count = 0;
|
||||
for (var i = 0; i < magnitudes.Length; i++)
|
||||
{
|
||||
if (error[i] <= ReliableError) magnitudes[count++] = float.Hypot(u[i], w[i]);
|
||||
}
|
||||
if (count < MinimumReliable * magnitudes.Length) return (double.NaN, double.NaN);
|
||||
var reliable = magnitudes.AsSpan(0, count);
|
||||
var median = PlaneOps.Median(reliable);
|
||||
var p95 = PlaneOps.Select(reliable, int.Max(0, (int)double.Ceiling(0.95 * count) - 1));
|
||||
return (median * probe.FlowScale, p95 * probe.FlowScale);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
namespace Titano.Core.Analysis.Deep;
|
||||
|
||||
/// <summary>Per-frame conditions found by the deep analysis.</summary>
|
||||
[Flags]
|
||||
public enum DeepFrameFlags
|
||||
{
|
||||
None = 0,
|
||||
|
||||
/// <summary>The source could not decode the frame; every measurement is NaN.</summary>
|
||||
Undecodable = 1,
|
||||
|
||||
Black = 2,
|
||||
White = 4,
|
||||
|
||||
/// <summary>Statistically identical to the previous decoded frame.</summary>
|
||||
Duplicate = 8,
|
||||
|
||||
/// <summary>Exposure-aligned histogram jump from the previous frame (camera moved or bumped); set at sequence level.</summary>
|
||||
SceneChange = 16,
|
||||
|
||||
/// <summary>Trimmed mean log2 luminance at or below <see cref="DeepAnalysisOptions.DarkLogLuminance"/>.</summary>
|
||||
Dark = 32,
|
||||
|
||||
/// <summary>Dark frame with at least <see cref="DeepAnalysisOptions.StarFieldDensity"/> stars per megapixel; set at sequence level.</summary>
|
||||
StarField = 64,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Exact per-frame measurements of <see cref="DeepAnalyzer"/>: what a checkpoint persists and what the
|
||||
/// sequence-level results are computed from. NaN marks a value that was not measured. Shifts and motion are in
|
||||
/// source pixels (oriented full resolution).
|
||||
/// </summary>
|
||||
public sealed record DeepFrame
|
||||
{
|
||||
public int Index { get; init; }
|
||||
public DeepFrameFlags Flags { get; init; }
|
||||
|
||||
/// <summary>Trimmed mean log2 luminance (<see cref="FrameStatistics.MeanLogLuminance"/>).</summary>
|
||||
public double LogLuminance { get; init; } = double.NaN;
|
||||
|
||||
public double ClipLow { get; init; } = double.NaN;
|
||||
public double ClipHigh { get; init; } = double.NaN;
|
||||
|
||||
/// <summary>log2(R/G) of the mean colour (white-balance drift signal).</summary>
|
||||
public double RedRatio { get; init; } = double.NaN;
|
||||
|
||||
/// <summary>log2(B/G) of the mean colour.</summary>
|
||||
public double BlueRatio { get; init; } = double.NaN;
|
||||
|
||||
/// <summary>Correlated colour temperature of the mean colour; NaN when not near-Planckian.</summary>
|
||||
public double Kelvin { get; init; } = double.NaN;
|
||||
|
||||
/// <summary>Laplacian variance of encoded luminance (<see cref="FrameStatistics.Sharpness"/>).</summary>
|
||||
public double Sharpness { get; init; } = double.NaN;
|
||||
|
||||
/// <summary>Robust noise σ of encoded luminance (<see cref="StarFieldDetector.RobustNoise"/>), usable frames only.</summary>
|
||||
public double Noise { get; init; } = double.NaN;
|
||||
|
||||
/// <summary>Content motion from the previous decoded frame at the image centre (nine-patch similarity fit).</summary>
|
||||
public double ShiftX { get; init; } = double.NaN;
|
||||
|
||||
public double ShiftY { get; init; } = double.NaN;
|
||||
|
||||
/// <summary>Median optical-flow magnitude from the previous frame, px per frame (sampled pairs only).</summary>
|
||||
public double MotionMedian { get; init; } = double.NaN;
|
||||
|
||||
/// <summary>95th-percentile optical-flow magnitude from the previous frame (sampled pairs only).</summary>
|
||||
public double MotionP95 { get; init; } = double.NaN;
|
||||
|
||||
/// <summary>Point sources per megapixel of the analysis image (dark frames only).</summary>
|
||||
public double StarDensity { get; init; } = double.NaN;
|
||||
|
||||
/// <summary>Fraction of sky blocks with cloud texture (frames with a sky region only).</summary>
|
||||
public double CloudCoverage { get; init; } = double.NaN;
|
||||
|
||||
/// <summary>Trimmed mean log2 luminance of the sky region (region deflicker signal).</summary>
|
||||
public double SkyLogLuminance { get; init; } = double.NaN;
|
||||
|
||||
public double LandLogLuminance { get; init; } = double.NaN;
|
||||
|
||||
/// <summary>Exposure-aligned chi-square histogram distance from the previous decoded frame.</summary>
|
||||
public double SceneDistance { get; init; } = double.NaN;
|
||||
|
||||
public bool IsUsable => (Flags & (DeepFrameFlags.Undecodable | DeepFrameFlags.Black | DeepFrameFlags.White)) == 0;
|
||||
}
|
||||
@@ -0,0 +1,450 @@
|
||||
using Titano.Core.Mathematics;
|
||||
using Titano.Core.Motion;
|
||||
|
||||
namespace Titano.Core.Analysis.Deep;
|
||||
|
||||
/// <summary>
|
||||
/// Sequence-level results of the deep analysis, computed from the exact <see cref="DeepFrame"/>s and the frame
|
||||
/// metadata: exposure steps as received (<see cref="HolyGrailEngine"/>), flicker spectrum and amplitude on the
|
||||
/// step-free luminance (<see cref="FlickerSpectrum"/>, <see cref="DeflickerEngine"/>), region divergence, white-balance
|
||||
/// jitter (<see cref="WhiteBalanceSmoother"/>), shake from the integrated shifts (camera path minus its
|
||||
/// <see cref="PathSmoother.LocalLinear"/> smoothing, as <see cref="Stabilizer"/>), motion, stars, clouds, day/night,
|
||||
/// scene changes, the hero frame and the findings.
|
||||
/// </summary>
|
||||
public static class DeepSequenceAnalysis
|
||||
{
|
||||
/// <summary>Flicker below this RMS is not visible (≈ 1.4 % brightness).</summary>
|
||||
public const double VisibleFlickerEv = 0.02;
|
||||
|
||||
/// <summary>Colour-ratio jitter (log2 RMS) above which white-balance smoothing helps (≈ 0.7 %).</summary>
|
||||
public const double VisibleWhiteBalanceJitter = 0.01;
|
||||
|
||||
/// <summary>Mid-grey (18 %) in log2 luminance, the hero frame's exposure target.</summary>
|
||||
private const double MidGreyEv = -2.47;
|
||||
|
||||
private const int HorizonSamples = 64;
|
||||
|
||||
public static DeepAnalysisReport Build(IReadOnlyList<DeepFrame> frames, IReadOnlyList<LightFrame> metadata, RegionMask? mask, DeepAnalysisOptions? options = null)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(frames);
|
||||
ArgumentNullException.ThrowIfNull(metadata);
|
||||
options ??= DeepAnalysisOptions.Default;
|
||||
var n = frames.Count;
|
||||
if (metadata.Count != n) throw new ArgumentException("One metadata entry per frame is required.", nameof(metadata));
|
||||
var light = LightAnalyzer.Analyze(metadata);
|
||||
var (sourceWidth, sourceHeight) = light.DominantSize ?? (0, 0);
|
||||
var luminance = new double[n];
|
||||
for (var i = 0; i < n; i++) luminance[i] = frames[i].IsUsable ? frames[i].LogLuminance : double.NaN;
|
||||
|
||||
var (exposure, offsets) = Exposure(luminance, light);
|
||||
var flat = new double[n];
|
||||
for (var i = 0; i < n; i++) flat[i] = luminance[i] - offsets[i];
|
||||
exposure = exposure with { SceneRangeEv = Range(flat, 0.05, 0.95) };
|
||||
var flicker = Flicker(flat);
|
||||
var sceneChanges = SceneChanges(frames, options);
|
||||
var starFrames = new HashSet<int>();
|
||||
var sky = Sky(frames, flat, light, options, starFrames);
|
||||
var shake = Shake(frames, sourceWidth, sourceHeight, options);
|
||||
var issues = new FrameIssues(
|
||||
Where(frames, f => (f.Flags & DeepFrameFlags.Undecodable) != 0),
|
||||
Where(frames, f => (f.Flags & DeepFrameFlags.Black) != 0),
|
||||
Where(frames, f => (f.Flags & DeepFrameFlags.White) != 0),
|
||||
Where(frames, f => (f.Flags & DeepFrameFlags.Duplicate) != 0),
|
||||
[.. sceneChanges.Order()]);
|
||||
var report = new DeepAnalysisReport
|
||||
{
|
||||
FrameCount = n,
|
||||
SourceWidth = sourceWidth,
|
||||
SourceHeight = sourceHeight,
|
||||
AnalysisLongEdge = options.AnalysisLongEdge(int.Max(sourceWidth, sourceHeight)),
|
||||
Frames = Columns(frames, sceneChanges, starFrames),
|
||||
Flicker = flicker,
|
||||
Regions = Regions(frames, mask, flicker.RecommendedWindow),
|
||||
Exposure = exposure,
|
||||
WhiteBalance = WhiteBalance(frames),
|
||||
Shake = shake,
|
||||
Motion = Motion(frames),
|
||||
Sky = sky,
|
||||
Issues = issues,
|
||||
HeroIndex = Hero(frames, sceneChanges, light.DayPhases),
|
||||
};
|
||||
return report with { Findings = Findings(report) };
|
||||
}
|
||||
|
||||
private static (ExposureSummary Summary, double[] Offsets) Exposure(double[] luminance, LightAnalysisReport light)
|
||||
{
|
||||
var n = luminance.Length;
|
||||
if (light.ExposureSteps.Count == 0 || n == 0) return (new ExposureSummary(0, 0, null, null, 0, []), new double[n]);
|
||||
var result = HolyGrailEngine.Compute(luminance, light.ExposureValues);
|
||||
var received = result.Transitions.Where(t => t.Received).Select(t => t.Index).ToArray();
|
||||
double? spacing = null;
|
||||
int? length = null;
|
||||
if (received.Length >= 2)
|
||||
{
|
||||
var gaps = new double[received.Length - 1];
|
||||
for (var i = 1; i < received.Length; i++) gaps[i - 1] = received[i] - received[i - 1];
|
||||
spacing = Statistics.Median(gaps);
|
||||
length = int.Max(2, (int)double.Round(spacing.Value / 2));
|
||||
}
|
||||
else if (received.Length == 1)
|
||||
{
|
||||
length = HolyGrailOptions.Default.SingleStepTransitionFrames;
|
||||
}
|
||||
var steps = result.Transitions
|
||||
.Select(t => new ExposureStepSummary(t.Index, Round(t.ExpectedEv, 3), double.IsFinite(t.MeasuredEv) ? Round(t.MeasuredEv, 3) : null, t.Received, Round(t.Length, 2)))
|
||||
.ToList();
|
||||
return (new ExposureSummary(result.Transitions.Count, received.Length, spacing, length, 0, steps), result.StepOffsets);
|
||||
}
|
||||
|
||||
private static FlickerSummary Flicker(double[] flat)
|
||||
{
|
||||
if (Count(flat) < 3) return new FlickerSummary(0, 0, null, 0, 0, FlickerSpectrumOptions.Default.MinimumWindow);
|
||||
var spectrum = FlickerSpectrum.Analyze(flat);
|
||||
var diagnostics = DeflickerEngine.Compute(flat, new DeflickerOptions { Window = spectrum.RecommendedWindow }).Diagnostics;
|
||||
return new FlickerSummary(
|
||||
Round(diagnostics.ResidualRms, 4),
|
||||
Round(diagnostics.FlickerBefore, 4),
|
||||
spectrum.DominantPeriod is { } p ? Round(p, 2) : null,
|
||||
Round(spectrum.PeakCorrelation, 3),
|
||||
Round(spectrum.CorrelationLength, 2),
|
||||
spectrum.RecommendedWindow);
|
||||
}
|
||||
|
||||
private static RegionSummary? Regions(IReadOnlyList<DeepFrame> frames, RegionMask? mask, int window)
|
||||
{
|
||||
if (mask is null) return null;
|
||||
double[]? horizon = null;
|
||||
if (mask.Horizon is { } h)
|
||||
{
|
||||
var count = int.Min(HorizonSamples, mask.Width);
|
||||
horizon = new double[count];
|
||||
for (var k = 0; k < count; k++)
|
||||
{
|
||||
var x = count > 1 ? (int)((long)k * (mask.Width - 1) / (count - 1)) : 0;
|
||||
horizon[k] = Round(h[x] / mask.Height, 4);
|
||||
}
|
||||
}
|
||||
double skyFraction = 0;
|
||||
foreach (var w in mask.Sky) skyFraction += w;
|
||||
skyFraction /= mask.Sky.Length;
|
||||
|
||||
var n = frames.Count;
|
||||
var sky = new double[n];
|
||||
var land = new double[n];
|
||||
for (var i = 0; i < n; i++)
|
||||
{
|
||||
sky[i] = frames[i].IsUsable ? frames[i].SkyLogLuminance : double.NaN;
|
||||
land[i] = frames[i].IsUsable ? frames[i].LandLogLuminance : double.NaN;
|
||||
}
|
||||
var divergence = 0.0;
|
||||
if (Count(sky) >= 3 && Count(land) >= 3)
|
||||
{
|
||||
var skyFit = LocalRegression.Smooth(sky, window, 1, 3).Fitted;
|
||||
var landFit = LocalRegression.Smooth(land, window, 1, 3).Fitted;
|
||||
var difference = new double[n];
|
||||
for (var i = 0; i < n; i++) difference[i] = sky[i] - skyFit[i] - (land[i] - landFit[i]);
|
||||
divergence = Statistics.Rms(difference);
|
||||
}
|
||||
return new RegionSummary(mask.Method, Round(mask.Confidence, 3), Round(skyFraction, 3), mask.Width, mask.Height, horizon,
|
||||
Round(double.IsFinite(divergence) ? divergence : 0, 4));
|
||||
}
|
||||
|
||||
private static WhiteBalanceSummary WhiteBalance(IReadOnlyList<DeepFrame> frames)
|
||||
{
|
||||
var n = frames.Count;
|
||||
var red = new double[n];
|
||||
var green = new double[n];
|
||||
var blue = new double[n];
|
||||
var kelvin = new double[n];
|
||||
for (var i = 0; i < n; i++)
|
||||
{
|
||||
var f = frames[i];
|
||||
var valid = f.IsUsable && double.IsFinite(f.RedRatio) && double.IsFinite(f.BlueRatio);
|
||||
red[i] = valid ? double.Exp2(f.RedRatio) : double.NaN;
|
||||
green[i] = valid ? 1 : double.NaN;
|
||||
blue[i] = valid ? double.Exp2(f.BlueRatio) : double.NaN;
|
||||
kelvin[i] = f.IsUsable ? f.Kelvin : double.NaN;
|
||||
}
|
||||
if (Count(red) < 3) return new WhiteBalanceSummary(0, 0, null, null);
|
||||
var result = WhiteBalanceSmoother.Smooth(red, green, blue);
|
||||
var deviation = new double[n];
|
||||
for (var i = 0; i < n; i++)
|
||||
{
|
||||
var dr = result.RedRatio[i] - result.SmoothedRedRatio[i];
|
||||
var db = result.BlueRatio[i] - result.SmoothedBlueRatio[i];
|
||||
deviation[i] = double.Sqrt(dr * dr + db * db);
|
||||
}
|
||||
var drift = double.Max(Range(result.SmoothedRedRatio, 0, 1), Range(result.SmoothedBlueRatio, 0, 1));
|
||||
var hasKelvin = Count(kelvin) > 0;
|
||||
return new WhiteBalanceSummary(
|
||||
Round(Statistics.Rms(deviation), 4),
|
||||
Round(drift, 4),
|
||||
hasKelvin ? double.Round(Statistics.Percentile(kelvin, 0.05)) : null,
|
||||
hasKelvin ? double.Round(Statistics.Percentile(kelvin, 0.95)) : null);
|
||||
}
|
||||
|
||||
private static ShakeSummary Shake(IReadOnlyList<DeepFrame> frames, int sourceWidth, int sourceHeight, DeepAnalysisOptions options)
|
||||
{
|
||||
var n = frames.Count;
|
||||
if (n < 2) return new ShakeSummary(0, 0, 0, 0, false, 0);
|
||||
var x = new double[n];
|
||||
var y = new double[n];
|
||||
int measured = 0, pairs = 0;
|
||||
for (var i = 1; i < n; i++)
|
||||
{
|
||||
var f = frames[i];
|
||||
var known = double.IsFinite(f.ShiftX) && double.IsFinite(f.ShiftY);
|
||||
if (f.IsUsable) pairs++;
|
||||
if (known) measured++;
|
||||
x[i] = x[i - 1] + (known ? f.ShiftX : 0);
|
||||
y[i] = y[i - 1] + (known ? f.ShiftY : 0);
|
||||
}
|
||||
var sx = PathSmoother.LocalLinear(x, options.ShakeSmoothingSigma);
|
||||
var sy = PathSmoother.LocalLinear(y, options.ShakeSmoothingSigma);
|
||||
double sum = 0, max = 0, maxX = 0, maxY = 0;
|
||||
for (var i = 0; i < n; i++)
|
||||
{
|
||||
double rx = x[i] - sx[i], ry = y[i] - sy[i];
|
||||
var r2 = rx * rx + ry * ry;
|
||||
sum += r2;
|
||||
max = double.Max(max, double.Sqrt(r2));
|
||||
maxX = double.Max(maxX, double.Abs(rx));
|
||||
maxY = double.Max(maxY, double.Abs(ry));
|
||||
}
|
||||
var width = sourceWidth > 0 ? sourceWidth : options.AnalysisLongEdge(0);
|
||||
var height = sourceHeight > 0 ? sourceHeight : width;
|
||||
var scale = double.Clamp(double.Min(1 - 2 * maxX / width, 1 - 2 * maxY / height), 0, 1);
|
||||
var drift = double.Hypot(sx[n - 1] - sx[0], sy[n - 1] - sy[0]);
|
||||
return new ShakeSummary(
|
||||
Round(double.Sqrt(sum / n), 3),
|
||||
Round(max, 3),
|
||||
Round(1 - scale * scale, 4),
|
||||
Round(drift / (n - 1), 3),
|
||||
drift >= 0.02 * width,
|
||||
Round(pairs > 1 ? double.Min(1, measured / (double)(pairs - 1)) : 0, 3));
|
||||
}
|
||||
|
||||
private static MotionSummary Motion(IReadOnlyList<DeepFrame> frames)
|
||||
{
|
||||
var medians = frames.Where(f => double.IsFinite(f.MotionP95)).Select(f => f.MotionMedian).ToArray();
|
||||
var p95 = frames.Where(f => double.IsFinite(f.MotionP95)).Select(f => f.MotionP95).ToArray();
|
||||
if (p95.Length == 0) return new MotionSummary(0, null, null, null);
|
||||
return new MotionSummary(p95.Length, Round(Statistics.Median(medians), 3), Round(Statistics.Median(p95), 3), Round(p95.Max(), 3));
|
||||
}
|
||||
|
||||
private static SkySummary Sky(IReadOnlyList<DeepFrame> frames, double[] flat, LightAnalysisReport light, DeepAnalysisOptions options, HashSet<int> starFrames)
|
||||
{
|
||||
int usable = 0, dark = 0;
|
||||
var densities = new List<double>();
|
||||
var clouds = new List<double>();
|
||||
foreach (var f in frames)
|
||||
{
|
||||
if (!f.IsUsable) continue;
|
||||
usable++;
|
||||
if (double.IsFinite(f.CloudCoverage)) clouds.Add(f.CloudCoverage);
|
||||
if ((f.Flags & DeepFrameFlags.Dark) == 0) continue;
|
||||
dark++;
|
||||
if (!double.IsFinite(f.StarDensity)) continue;
|
||||
densities.Add(f.StarDensity);
|
||||
if (f.StarDensity >= options.StarFieldDensity) starFrames.Add(f.Index);
|
||||
}
|
||||
var darkFraction = usable > 0 ? (double)dark / usable : 0;
|
||||
return new SkySummary(
|
||||
DayNightOf(flat, darkFraction, usable, light.DayPhases),
|
||||
Round(darkFraction, 3),
|
||||
dark,
|
||||
starFrames.Count,
|
||||
densities.Count > 0 ? double.Round(Statistics.Median(densities.ToArray())) : null,
|
||||
starFrames.Count > 0 && starFrames.Count >= 0.25 * usable,
|
||||
clouds.Count > 0 ? Round(clouds.Average(), 3) : null);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Solar phases when GPS gave them for most frames; otherwise the step-free luminance: a 10–90 % range of at
|
||||
/// least 3 EV is a transition (direction from the first and last tenth), else the dark-frame share decides.
|
||||
/// </summary>
|
||||
private static DayNight DayNightOf(double[] flat, double darkFraction, int usable, DayPhase?[] phases)
|
||||
{
|
||||
int day = 0, night = 0, known = 0;
|
||||
DayPhase? first = null, last = null;
|
||||
foreach (var phase in phases)
|
||||
{
|
||||
if (phase is not { } p) continue;
|
||||
known++;
|
||||
first ??= p;
|
||||
last = p;
|
||||
if (p is DayPhase.Day or DayPhase.GoldenHour) day++;
|
||||
else if (p is DayPhase.Night or DayPhase.AstronomicalTwilight or DayPhase.NauticalTwilight) night++;
|
||||
}
|
||||
if (known * 2 >= phases.Length && known > 0)
|
||||
{
|
||||
if (day > 0 && night > 0) return first >= DayPhase.CivilTwilight && last < DayPhase.CivilTwilight ? DayNight.DayToNight : DayNight.NightToDay;
|
||||
return night > day ? DayNight.Night : DayNight.Day;
|
||||
}
|
||||
if (usable == 0) return DayNight.Unknown;
|
||||
if (Range(flat, 0.1, 0.9) >= 3)
|
||||
{
|
||||
var tenth = int.Max(1, flat.Length / 10);
|
||||
var start = Statistics.Mean(flat.AsSpan(0, tenth));
|
||||
var end = Statistics.Mean(flat.AsSpan(flat.Length - tenth));
|
||||
if (double.IsFinite(start) && double.IsFinite(end)) return start > end ? DayNight.DayToNight : DayNight.NightToDay;
|
||||
}
|
||||
return darkFraction >= 0.5 ? DayNight.Night : DayNight.Day;
|
||||
}
|
||||
|
||||
/// <summary>Spikes of the exposure-aligned histogram distance: above max(minimum, median + 10 robust σ).</summary>
|
||||
private static HashSet<int> SceneChanges(IReadOnlyList<DeepFrame> frames, DeepAnalysisOptions options)
|
||||
{
|
||||
var candidates = frames.Where(f => f.IsUsable && (f.Flags & DeepFrameFlags.Duplicate) == 0 && double.IsFinite(f.SceneDistance)).ToList();
|
||||
var result = new HashSet<int>();
|
||||
if (candidates.Count == 0) return result;
|
||||
var distances = candidates.Select(f => f.SceneDistance).ToArray();
|
||||
var median = Statistics.Median(distances);
|
||||
var sigma = Statistics.MadToSigma * Statistics.MedianAbsoluteDeviation(distances, median);
|
||||
var threshold = double.Max(options.SceneChangeMinimum, median + 10 * sigma);
|
||||
foreach (var f in candidates)
|
||||
{
|
||||
if (f.SceneDistance > threshold) result.Add(f.Index);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Highest √(relative sharpness) × exposure × time score over usable, unique, non-scene-change frames. Exposure
|
||||
/// favours mid-grey and penalises clipping; time favours golden hour (when GPS gave phases) or the middle of the
|
||||
/// sequence. Ties go to the earliest frame.
|
||||
/// </summary>
|
||||
private static int? Hero(IReadOnlyList<DeepFrame> frames, HashSet<int> sceneChanges, DayPhase?[] phases)
|
||||
{
|
||||
var candidates = frames.Where(f => f.IsUsable && (f.Flags & DeepFrameFlags.Duplicate) == 0 && !sceneChanges.Contains(f.Index)
|
||||
&& double.IsFinite(f.Sharpness) && double.IsFinite(f.LogLuminance)).ToList();
|
||||
if (candidates.Count == 0) return null;
|
||||
var medianSharpness = Statistics.Median(candidates.Select(f => f.Sharpness).ToArray());
|
||||
var n = frames.Count;
|
||||
int? best = null;
|
||||
var bestScore = double.NegativeInfinity;
|
||||
foreach (var f in candidates)
|
||||
{
|
||||
var sharp = medianSharpness > 0 ? double.Min(2, f.Sharpness / medianSharpness) : 1;
|
||||
var level = (f.LogLuminance - MidGreyEv) / 1.5;
|
||||
var exposure = double.Exp(-level * level) * double.Max(0, 1 - 5 * f.ClipHigh - 2 * f.ClipLow);
|
||||
var phase = f.Index < phases.Length ? phases[f.Index] : null;
|
||||
var time = phase switch
|
||||
{
|
||||
DayPhase.GoldenHour => 1.0,
|
||||
DayPhase.CivilTwilight => 0.8,
|
||||
DayPhase.Day => 0.6,
|
||||
null => n > 1 ? 1 - 2 * double.Abs((double)f.Index / (n - 1) - 0.5) : 1,
|
||||
_ => 0.4,
|
||||
};
|
||||
var score = double.Sqrt(sharp) * exposure * (0.5 + 0.5 * time);
|
||||
if (score > bestScore)
|
||||
{
|
||||
bestScore = score;
|
||||
best = f.Index;
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
private static List<DeepFinding> Findings(DeepAnalysisReport report)
|
||||
{
|
||||
var findings = new List<DeepFinding>();
|
||||
void Add(string key, FindingSeverity severity, int[] frames, params double[] args) =>
|
||||
findings.Add(new DeepFinding(key, severity, args, frames.Length > Finding.MaxFrames ? frames[..Finding.MaxFrames] : frames));
|
||||
|
||||
var issues = report.Issues;
|
||||
if (issues.Undecodable.Length > 0) Add(DeepFindingKeys.UnreadableFrames, FindingSeverity.Warning, issues.Undecodable, issues.Undecodable.Length);
|
||||
if (issues.Black.Length > 0) Add(DeepFindingKeys.BlackFrames, FindingSeverity.Warning, issues.Black, issues.Black.Length);
|
||||
if (issues.White.Length > 0) Add(DeepFindingKeys.WhiteFrames, FindingSeverity.Warning, issues.White, issues.White.Length);
|
||||
if (issues.Duplicate.Length > 0) Add(DeepFindingKeys.DuplicateFrames, FindingSeverity.Warning, issues.Duplicate, issues.Duplicate.Length);
|
||||
if (issues.SceneChanges.Length > 0) Add(DeepFindingKeys.SceneChanges, FindingSeverity.Warning, issues.SceneChanges, issues.SceneChanges.Length);
|
||||
var ignored = report.Exposure.Steps.Where(s => !s.Received).Select(s => s.Index).ToArray();
|
||||
if (ignored.Length > 0) Add(DeepFindingKeys.StepsNotReceived, FindingSeverity.Warning, ignored, ignored.Length);
|
||||
if (report.Flicker.AmplitudeEv >= VisibleFlickerEv) Add(DeepFindingKeys.Flicker, FindingSeverity.Info, [], Round(report.Flicker.AmplitudeEv, 3));
|
||||
if (report.Shake.RmsPx >= 0.3) Add(DeepFindingKeys.Shake, FindingSeverity.Info, [], Round(report.Shake.RmsPx, 2), Round(100 * report.Shake.CropCost, 1));
|
||||
if (report.Shake.PanDetected) Add(DeepFindingKeys.Panning, FindingSeverity.Info, [], Round(report.Shake.PanPxPerFrame, 2));
|
||||
if (report.Sky.StarField) Add(DeepFindingKeys.StarField, FindingSeverity.Info, [], report.Sky.StarFrames);
|
||||
if (report.Sky.CloudCoverage is { } cover && cover >= 0.1) Add(DeepFindingKeys.Clouds, FindingSeverity.Info, [], double.Round(100 * cover));
|
||||
if (report.WhiteBalance.JitterLog2 >= VisibleWhiteBalanceJitter)
|
||||
Add(DeepFindingKeys.WhiteBalanceJitter, FindingSeverity.Info, [], Round(100 * (double.Exp2(report.WhiteBalance.JitterLog2) - 1), 1));
|
||||
return findings;
|
||||
}
|
||||
|
||||
private static DeepFrameColumns Columns(IReadOnlyList<DeepFrame> frames, HashSet<int> sceneChanges, HashSet<int> starFrames)
|
||||
{
|
||||
var n = frames.Count;
|
||||
double?[] Column(Func<DeepFrame, double> value, Func<double, double> quantise)
|
||||
{
|
||||
var column = new double?[n];
|
||||
for (var i = 0; i < n; i++)
|
||||
{
|
||||
var v = value(frames[i]);
|
||||
column[i] = double.IsFinite(v) ? quantise(v) : null;
|
||||
}
|
||||
return column;
|
||||
}
|
||||
|
||||
var flags = new int[n];
|
||||
for (var i = 0; i < n; i++)
|
||||
{
|
||||
var f = frames[i].Flags;
|
||||
if (sceneChanges.Contains(i)) f |= DeepFrameFlags.SceneChange;
|
||||
if (starFrames.Contains(i)) f |= DeepFrameFlags.StarField;
|
||||
flags[i] = (int)f;
|
||||
}
|
||||
var sampled = frames.Where(f => double.IsFinite(f.MotionP95)).ToArray();
|
||||
return new DeepFrameColumns
|
||||
{
|
||||
LogLuminance = Column(f => f.LogLuminance, v => Round(v, 3)),
|
||||
ClipLow = Column(f => f.ClipLow, v => Round(v, 3)),
|
||||
ClipHigh = Column(f => f.ClipHigh, v => Round(v, 3)),
|
||||
RedRatio = Column(f => f.RedRatio, v => Round(v, 3)),
|
||||
BlueRatio = Column(f => f.BlueRatio, v => Round(v, 3)),
|
||||
Kelvin = Column(f => f.Kelvin, double.Round),
|
||||
Sharpness = Column(f => f.Sharpness, v => Significant(v, 2)),
|
||||
Noise = Column(f => f.Noise, v => Significant(v, 2)),
|
||||
ShiftX = Column(f => f.ShiftX, v => Round(v, 2)),
|
||||
ShiftY = Column(f => f.ShiftY, v => Round(v, 2)),
|
||||
StarDensity = Column(f => f.StarDensity, double.Round),
|
||||
CloudCoverage = Column(f => f.CloudCoverage, v => Round(v, 2)),
|
||||
SkyLogLuminance = Column(f => f.SkyLogLuminance, v => Round(v, 3)),
|
||||
LandLogLuminance = Column(f => f.LandLogLuminance, v => Round(v, 3)),
|
||||
SceneDistance = Column(f => f.SceneDistance, v => Round(v, 3)),
|
||||
Flags = flags,
|
||||
MotionFrames = [.. sampled.Select(f => f.Index)],
|
||||
MotionMedian = [.. sampled.Select(f => Round(f.MotionMedian, 2))],
|
||||
MotionP95 = [.. sampled.Select(f => Round(f.MotionP95, 2))],
|
||||
};
|
||||
}
|
||||
|
||||
private static int[] Where(IReadOnlyList<DeepFrame> frames, Func<DeepFrame, bool> predicate) => [.. frames.Where(predicate).Select(f => f.Index)];
|
||||
|
||||
private static int Count(double[] values)
|
||||
{
|
||||
var count = 0;
|
||||
foreach (var v in values)
|
||||
{
|
||||
if (double.IsFinite(v)) count++;
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
/// <summary>Spread between two percentiles of the finite values (0 when fewer than two).</summary>
|
||||
private static double Range(double[] values, double low, double high)
|
||||
{
|
||||
if (Count(values) < 2) return 0;
|
||||
return Statistics.Percentile(values, high) - Statistics.Percentile(values, low);
|
||||
}
|
||||
|
||||
/// <summary>Rounds half away from zero; adding +0 turns −0 into 0 so JSON never spends a byte on the sign.</summary>
|
||||
private static double Round(double value, int decimals) => double.Round(value, decimals, MidpointRounding.AwayFromZero) + 0.0;
|
||||
|
||||
private static double Significant(double value, int digits)
|
||||
{
|
||||
if (value == 0) return 0;
|
||||
var magnitude = (int)double.Floor(double.Log10(double.Abs(value)));
|
||||
var decimals = digits - 1 - magnitude;
|
||||
return decimals is >= 0 and <= 15 ? Round(value, decimals) : value;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
using Titano.Core.Imaging;
|
||||
using Titano.Core.Motion;
|
||||
|
||||
namespace Titano.Core.Analysis.Deep;
|
||||
|
||||
/// <summary>
|
||||
/// The measurements of one frame that need no other frame (statistics, stars, sky/land luminance, clouds) plus the
|
||||
/// reduced planes the sequential stage of <see cref="DeepAnalyzer"/> compares with the previous frame. Frames are
|
||||
/// probed in parallel; the full analysis image is released before the probe is returned.
|
||||
/// </summary>
|
||||
internal sealed class FrameProbe : IDisposable
|
||||
{
|
||||
private FrameProbe(int index) => Index = index;
|
||||
|
||||
public int Index { get; }
|
||||
|
||||
/// <summary>Null when the frame could not be decoded.</summary>
|
||||
public FrameStatistics? Statistics { get; private set; }
|
||||
|
||||
/// <summary>Perceptual luminance at the correlation size, row-major.</summary>
|
||||
public float[]? Correlation { get; private set; }
|
||||
|
||||
public int CorrelationWidth { get; private set; }
|
||||
public int CorrelationHeight { get; private set; }
|
||||
|
||||
/// <summary>Source pixels per correlation-plane pixel.</summary>
|
||||
public double CorrelationScale { get; private set; } = 1;
|
||||
|
||||
/// <summary>Flow-sized image; only for frames that take part in a sampled flow pair.</summary>
|
||||
public ImageBuffer? Flow { get; private set; }
|
||||
|
||||
/// <summary>Source pixels per flow-image pixel.</summary>
|
||||
public double FlowScale { get; private set; } = 1;
|
||||
|
||||
/// <summary>Robust encoded-luminance noise σ (<see cref="StarFieldDetector.RobustNoise"/>); usable frames only.</summary>
|
||||
public double Noise { get; private set; } = double.NaN;
|
||||
|
||||
public double StarDensity { get; private set; } = double.NaN;
|
||||
public double CloudCoverage { get; private set; } = double.NaN;
|
||||
public double SkyLogLuminance { get; private set; } = double.NaN;
|
||||
public double LandLogLuminance { get; private set; } = double.NaN;
|
||||
|
||||
/// <summary>True when the frame is decoded and neither black nor white (it may update the sequential state).</summary>
|
||||
public bool IsUsable => Statistics is { } s && !s.IsBlack() && !s.IsWhite();
|
||||
|
||||
/// <summary>Whether frame <paramref name="index"/> takes part in a sampled optical-flow pair (k − 1, k), k divisible by <paramref name="every"/>.</summary>
|
||||
public static bool NeedsFlow(int index, int every) => index % every == 0 || (index + 1) % every == 0;
|
||||
|
||||
public static async Task<FrameProbe> RunAsync(IFrameSource source, int index, DeepAnalysisOptions options, RegionMask? mask, CancellationToken cancellationToken)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
var (sourceWidth, sourceHeight) = source.Metadata(index).OrientedSize;
|
||||
var edge = options.AnalysisLongEdge(int.Max(sourceWidth, sourceHeight));
|
||||
var loaded = await source.LoadAsync(index, edge, cancellationToken).ConfigureAwait(false);
|
||||
var probe = new FrameProbe(index);
|
||||
if (loaded is null) return probe;
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
using var analysis = int.Max(loaded.Width, loaded.Height) > edge ? Reduce(loaded, edge) : loaded;
|
||||
var sourceLong = sourceWidth > 0 && sourceHeight > 0 ? int.Max(sourceWidth, sourceHeight) : int.Max(analysis.Width, analysis.Height);
|
||||
probe.Measure(analysis, sourceLong, options, mask);
|
||||
return probe;
|
||||
}
|
||||
|
||||
/// <summary>Hands the flow image over to the caller, who then disposes it.</summary>
|
||||
public ImageBuffer? TakeFlow()
|
||||
{
|
||||
var flow = Flow;
|
||||
Flow = null;
|
||||
return flow;
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
Flow?.Dispose();
|
||||
Flow = null;
|
||||
}
|
||||
|
||||
private static ImageBuffer Reduce(ImageBuffer image, int edge)
|
||||
{
|
||||
using (image) return AnalysisImage.Downscale(image, edge);
|
||||
}
|
||||
|
||||
private void Measure(ImageBuffer analysis, int sourceLong, DeepAnalysisOptions options, RegionMask? mask)
|
||||
{
|
||||
var stats = FrameStatistics.Measure(analysis);
|
||||
Statistics = stats;
|
||||
if (!IsUsable) return;
|
||||
|
||||
var encoded = StarFieldDetector.EncodedLuminance(analysis);
|
||||
Noise = StarFieldDetector.RobustNoise(encoded, analysis.Width, analysis.Height);
|
||||
if (stats.MeanLogLuminance <= options.DarkLogLuminance) StarDensity = StarFieldDetector.Density(encoded, analysis.Width, analysis.Height, Noise);
|
||||
|
||||
if (mask is not null)
|
||||
{
|
||||
using var thumbnail = AnalysisImage.Downscale(analysis, options.ThumbnailLongEdge);
|
||||
var fitted = mask.Resample(thumbnail.Width, thumbnail.Height);
|
||||
(SkyLogLuminance, LandLogLuminance) = RegionDeflicker.Measure(thumbnail, fitted);
|
||||
CloudCoverage = Deep.CloudCoverage.Estimate(thumbnail, fitted.Sky);
|
||||
}
|
||||
|
||||
using (var correlation = AnalysisImage.Downscale(analysis, options.CorrelationLongEdge))
|
||||
{
|
||||
CorrelationWidth = correlation.Width;
|
||||
CorrelationHeight = correlation.Height;
|
||||
CorrelationScale = (double)sourceLong / int.Max(correlation.Width, correlation.Height);
|
||||
var plane = new float[correlation.PlaneLength];
|
||||
PlaneOps.PerceptualLuminance(correlation, plane);
|
||||
Correlation = plane;
|
||||
}
|
||||
|
||||
if (NeedsFlow(Index, options.FlowEvery))
|
||||
{
|
||||
Flow = AnalysisImage.Downscale(analysis, options.FlowLongEdge);
|
||||
FlowScale = (double)sourceLong / int.Max(Flow.Width, Flow.Height);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Loads and measures the region-mask sample (thumbnails of usable frames that share the first one's size).</summary>
|
||||
public static async Task<RegionMask?> SegmentRegionsAsync(IFrameSource source, DeepAnalysisOptions options, CancellationToken cancellationToken)
|
||||
{
|
||||
var n = source.Count;
|
||||
var count = int.Min(options.RegionSampleFrames, n);
|
||||
var thumbnails = new List<ImageBuffer>(count);
|
||||
try
|
||||
{
|
||||
for (var k = 0; k < count; k++)
|
||||
{
|
||||
var index = count > 1 ? (int)((long)k * (n - 1) / (count - 1)) : 0;
|
||||
var (w, h) = source.Metadata(index).OrientedSize;
|
||||
var edge = options.AnalysisLongEdge(int.Max(w, h));
|
||||
using var loaded = await source.LoadAsync(index, edge, cancellationToken).ConfigureAwait(false);
|
||||
if (loaded is null) continue;
|
||||
using var analysis = AnalysisImage.Downscale(loaded, edge);
|
||||
var stats = FrameStatistics.Measure(analysis);
|
||||
if (stats.IsBlack() || stats.IsWhite()) continue;
|
||||
var thumbnail = AnalysisImage.Downscale(analysis, options.ThumbnailLongEdge);
|
||||
if (thumbnails.Count > 0 && (thumbnail.Width != thumbnails[0].Width || thumbnail.Height != thumbnails[0].Height) || thumbnail.Height < 8)
|
||||
{
|
||||
thumbnail.Dispose();
|
||||
continue;
|
||||
}
|
||||
thumbnails.Add(thumbnail);
|
||||
}
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
return thumbnails.Count > 0 ? RegionSegmenter.Segment(thumbnails) : null;
|
||||
}
|
||||
finally
|
||||
{
|
||||
foreach (var t in thumbnails) t.Dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
namespace Titano.Core.Analysis.Deep;
|
||||
|
||||
/// <summary>Scene-change measure between two <see cref="FrameStatistics.Histogram"/>s.</summary>
|
||||
internal static class HistogramDistance
|
||||
{
|
||||
private const double SmoothingBins = 2;
|
||||
private const double BinsPerEv = FrameStatistics.HistogramBins / (FrameStatistics.HistogramMaxEv - FrameStatistics.HistogramMinEv);
|
||||
|
||||
/// <summary>
|
||||
/// Symmetric chi-square distance (0 = same, 1 = disjoint) after both histograms are smoothed with a Gaussian of
|
||||
/// σ = 2 bins (⅛ EV) and the current one is shifted by the change of mean log-luminance (linear interpolation),
|
||||
/// so flicker, exposure steps and brightness ramps score near zero while a new view scores high. Mass shifted out
|
||||
/// of range counts as disjoint.
|
||||
/// </summary>
|
||||
public static double ExposureAligned(FrameStatistics previous, FrameStatistics current)
|
||||
{
|
||||
var a = Smooth(previous.Histogram);
|
||||
var b = Smooth(current.Histogram);
|
||||
var delta = current.MeanLogLuminance - previous.MeanLogLuminance;
|
||||
var shift = double.IsFinite(delta) ? delta * BinsPerEv : 0;
|
||||
double sum = 0, matched = 0, total = 0;
|
||||
foreach (var v in b) total += v;
|
||||
for (var i = 0; i < a.Length; i++)
|
||||
{
|
||||
var x = i + shift;
|
||||
var j = (int)double.Floor(x);
|
||||
var t = x - j;
|
||||
var q = (1 - t) * At(b, j) + t * At(b, j + 1);
|
||||
matched += q;
|
||||
var both = a[i] + q;
|
||||
if (both > 0) sum += (a[i] - q) * (a[i] - q) / both;
|
||||
}
|
||||
sum += double.Max(0, total - matched);
|
||||
return 0.5 * sum;
|
||||
}
|
||||
|
||||
private static double At(double[] values, int index) => index >= 0 && index < values.Length ? values[index] : 0;
|
||||
|
||||
/// <summary>Gaussian smoothing that keeps the total mass (kernel renormalised at the edges).</summary>
|
||||
private static double[] Smooth(double[] histogram)
|
||||
{
|
||||
var radius = (int)double.Ceiling(3 * SmoothingBins);
|
||||
Span<double> kernel = stackalloc double[2 * radius + 1];
|
||||
for (var d = -radius; d <= radius; d++) kernel[d + radius] = double.Exp(-0.5 * d * d / (SmoothingBins * SmoothingBins));
|
||||
var result = new double[histogram.Length];
|
||||
for (var i = 0; i < histogram.Length; i++)
|
||||
{
|
||||
if (histogram[i] == 0) continue;
|
||||
double weight = 0;
|
||||
for (var d = -radius; d <= radius; d++)
|
||||
{
|
||||
if (i + d >= 0 && i + d < histogram.Length) weight += kernel[d + radius];
|
||||
}
|
||||
for (var d = -radius; d <= radius; d++)
|
||||
{
|
||||
if (i + d >= 0 && i + d < histogram.Length) result[i + d] += histogram[i] * kernel[d + radius] / weight;
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
using Titano.Core.Imaging;
|
||||
|
||||
namespace Titano.Core.Analysis.Deep;
|
||||
|
||||
/// <summary>
|
||||
/// The frames of one sequence as <see cref="DeepAnalyzer"/> reads them. Decoding is the implementer's job (archive
|
||||
/// decoder on the client, proxies on the server, <c>SyntheticSequence</c> in tests).
|
||||
/// </summary>
|
||||
public interface IFrameSource
|
||||
{
|
||||
int Count { get; }
|
||||
|
||||
/// <summary>Metadata of frame <paramref name="index"/> (capture time, exposure, size, GPS); cheap, no decoding.</summary>
|
||||
LightFrame Metadata(int index);
|
||||
|
||||
/// <summary>
|
||||
/// Decodes frame <paramref name="index"/> in linear light, oriented, with its long edge at most
|
||||
/// <paramref name="maxLongEdge"/> (a larger result is downscaled by the caller). The caller owns and disposes the
|
||||
/// buffer. Null when the frame cannot be decoded.
|
||||
/// </summary>
|
||||
ValueTask<ImageBuffer?> LoadAsync(int index, int maxLongEdge, CancellationToken cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>Progress of a deep analysis: frames done (including resumed ones), throughput of this run and its ETA.</summary>
|
||||
public readonly record struct AnalysisProgress(int Done, int Total, double FramesPerSecond, TimeSpan? Eta);
|
||||
@@ -0,0 +1,90 @@
|
||||
using Titano.Core.Imaging;
|
||||
using Titano.Core.Motion;
|
||||
|
||||
namespace Titano.Core.Analysis.Deep;
|
||||
|
||||
/// <summary>
|
||||
/// Star-field detection (BRIEF §10.2): counts small bright points on sRGB-encoded luminance. A point is a strict
|
||||
/// 3×3 local maximum that rises above the mean of the 5×5 ring around it by at least
|
||||
/// max(<see cref="NoiseFactor"/>·σ, <see cref="MinimumContrast"/>), whose 8 neighbours average less than half that
|
||||
/// rise and whose ring stays below half of it everywhere (point-like: lit windows, the moon and textured land fail;
|
||||
/// stars up to 2×2 pixels pass).
|
||||
/// </summary>
|
||||
public static class StarFieldDetector
|
||||
{
|
||||
public const double NoiseFactor = 6;
|
||||
public const double MinimumContrast = 0.05;
|
||||
|
||||
/// <summary>Point sources per megapixel of a linear-light image; <paramref name="noiseSigma"/> is the encoded-luminance noise σ.</summary>
|
||||
public static double Density(ImageBuffer image, double noiseSigma)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(image);
|
||||
return Density(EncodedLuminance(image), image.Width, image.Height, noiseSigma);
|
||||
}
|
||||
|
||||
/// <summary>Point sources per megapixel of a row-major sRGB-encoded luminance plane.</summary>
|
||||
public static double Density(ReadOnlySpan<float> e, int w, int h, double noiseSigma)
|
||||
{
|
||||
if (e.Length < w * h) throw new ArgumentException("The plane is smaller than width × height.", nameof(e));
|
||||
if (w < 5 || h < 5) return 0;
|
||||
var threshold = double.Max(NoiseFactor * (double.IsFinite(noiseSigma) ? noiseSigma : 0), MinimumContrast);
|
||||
var count = 0;
|
||||
for (var y = 2; y < h - 2; y++)
|
||||
{
|
||||
for (var x = 2; x < w - 2; x++)
|
||||
{
|
||||
var i = y * w + x;
|
||||
var c = e[i];
|
||||
// Ties go to the later pixel in raster order so a plateau counts once.
|
||||
if (!(c >= e[i - w - 1] && c >= e[i - w] && c >= e[i - w + 1] && c >= e[i - 1]
|
||||
&& c > e[i + 1] && c > e[i + w - 1] && c > e[i + w] && c > e[i + w + 1])) continue;
|
||||
double ring = 0, ringMax = 0;
|
||||
for (var d = -2; d <= 2; d++)
|
||||
{
|
||||
ring += e[i - 2 * w + d] + e[i + 2 * w + d];
|
||||
ringMax = double.Max(ringMax, double.Max(e[i - 2 * w + d], e[i + 2 * w + d]));
|
||||
if (d is <= -2 or >= 2) continue;
|
||||
ring += e[i + d * w - 2] + e[i + d * w + 2];
|
||||
ringMax = double.Max(ringMax, double.Max(e[i + d * w - 2], e[i + d * w + 2]));
|
||||
}
|
||||
var background = ring / 16;
|
||||
var rise = c - background;
|
||||
if (rise < threshold || ringMax - background >= 0.5 * rise) continue;
|
||||
double inner = e[i - w - 1] + e[i - w] + e[i - w + 1] + e[i - 1] + e[i + 1] + e[i + w - 1] + e[i + w] + e[i + w + 1];
|
||||
if (inner / 8 - background <= 0.5 * rise) count++;
|
||||
}
|
||||
}
|
||||
return count * 1e6 / ((double)w * h);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Noise σ of an encoded-luminance plane from the median |Immerkær (1996) response| on every second pixel of every
|
||||
/// second row: σ = 1.4826 · median / 6 (the kernel's L2 norm). Unlike the mean-based estimate, stars, edges and
|
||||
/// texture covering under half the image do not raise it.
|
||||
/// </summary>
|
||||
public static double RobustNoise(ReadOnlySpan<float> e, int w, int h)
|
||||
{
|
||||
if (w < 3 || h < 3) return 0;
|
||||
var responses = new float[((w - 1) / 2) * ((h - 1) / 2)];
|
||||
var n = 0;
|
||||
for (var y = 1; y < h - 1; y += 2)
|
||||
{
|
||||
for (var x = 1; x < w - 1; x += 2)
|
||||
{
|
||||
var i = y * w + x;
|
||||
responses[n++] = float.Abs(e[i - w - 1] + e[i - w + 1] + e[i + w - 1] + e[i + w + 1]
|
||||
- 2 * (e[i - w] + e[i + w] + e[i - 1] + e[i + 1]) + 4 * e[i]);
|
||||
}
|
||||
}
|
||||
return n > 0 ? 1.482602218505602 * PlaneOps.Median(responses.AsSpan(0, n)) / 6 : 0;
|
||||
}
|
||||
|
||||
/// <summary>sRGB-encoded Rec.709 luminance of an image.</summary>
|
||||
public static float[] EncodedLuminance(ImageBuffer image)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(image);
|
||||
var e = new float[image.PlaneLength];
|
||||
PlaneOps.PerceptualLuminance(image, e);
|
||||
return e;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
using System.Collections;
|
||||
using System.Globalization;
|
||||
using System.Reflection;
|
||||
using System.Resources;
|
||||
using System.Text.RegularExpressions;
|
||||
using Titano.Core.Advisor;
|
||||
using Titano.Core.Analysis;
|
||||
using Titano.Core.Analysis.Deep;
|
||||
using Titano.Core.Diagnostics.Synthetic;
|
||||
using Titano.Core.Localization;
|
||||
using Titano.Core.Project;
|
||||
using Titano.Core.Tests.Analysis.Deep;
|
||||
using Titano.Testing;
|
||||
|
||||
namespace Titano.Core.Tests.Advisor;
|
||||
|
||||
using AdvisorApi = Titano.Core.Advisor.Advisor;
|
||||
|
||||
public sealed partial class AdvisorLocalizationTests(TestContext context)
|
||||
{
|
||||
private static readonly CultureInfo English = CultureInfo.GetCultureInfo("en");
|
||||
private static readonly CultureInfo Italian = CultureInfo.GetCultureInfo("it");
|
||||
|
||||
[Test]
|
||||
public void EveryAdvisorKeyHasEnglishAndItalianTextWithTheSamePlaceholders()
|
||||
{
|
||||
var manager = new ResourceManager("Titano.Core.i18n.Advisor", typeof(Loc).Assembly);
|
||||
var english = Entries(manager.GetResourceSet(CultureInfo.InvariantCulture, createIfNotExists: true, tryParents: false)!);
|
||||
var italian = Entries(manager.GetResourceSet(Italian, createIfNotExists: true, tryParents: false)!);
|
||||
var keys = Keys(typeof(AdvisorKeys)).Concat(Keys(typeof(FindingKeys))).Concat(Keys(typeof(DeepFindingKeys))).ToList();
|
||||
Assert.Greater(keys.Count, 90);
|
||||
foreach (var key in keys)
|
||||
{
|
||||
Assert.True(english.TryGetValue(key, out var en), $"English text missing for {key}");
|
||||
Assert.True(italian.TryGetValue(key, out var it), $"Italian text missing for {key}");
|
||||
Assert.SequenceEqual(Placeholders(en!), Placeholders(it!), key);
|
||||
Assert.LessOrEqual(en!.Length, 200);
|
||||
}
|
||||
Assert.Equal(english.Count, keys.Count);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task EveryReasonAndFindingOfTheGoldenScenesFormatsInBothLanguages()
|
||||
{
|
||||
var scenes = new List<(SyntheticFrameSource Source, DeepAnalysisReport? Deep)>
|
||||
{
|
||||
(new SyntheticFrameSource(DeepScenes.NightSky()), await DeepReports.Night),
|
||||
(new SyntheticFrameSource(DeepScenes.NightSky(jitter: 2), 2), await DeepReports.NightJitter),
|
||||
(new SyntheticFrameSource(DeepScenes.HolyGrail()), await DeepReports.HolyGrail),
|
||||
(new SyntheticFrameSource(DeepScenes.HolyGrail()) { StripExposure = true }, null),
|
||||
};
|
||||
var rendered = 0;
|
||||
foreach (var (source, deep) in scenes)
|
||||
{
|
||||
var frames = Enumerable.Range(0, source.Count).Select(source.Metadata).ToList();
|
||||
var light = LightAnalyzer.Analyze(frames);
|
||||
var sequence = new SequenceContext { FrameCount = frames.Count, SourceWidth = 6000, SourceHeight = 4000, MedianExposureSeconds = 1.0 / 250 };
|
||||
var result = AdvisorApi.Recommend(light, deep, sequence);
|
||||
foreach (var r in result.Recommendations) rendered += Render(r.ReasonKey, [.. r.ReasonArgs]);
|
||||
foreach (var f in result.Findings) rendered += Render(f.Key, f.Arguments);
|
||||
foreach (var p in SequencePresets.Generate(light, deep, sequence))
|
||||
{
|
||||
rendered += Render(p.NameKey, [.. p.NameArgs]);
|
||||
rendered += Render(p.ReasonKey!, [.. p.ReasonArgs]);
|
||||
}
|
||||
// Stored reasons (culture-neutral strings) render with the current culture's numbers.
|
||||
var applied = AdvisorApi.Apply(new ProjectSettings(), result);
|
||||
Assert.DoesNotContain('⟦', AdvisorApi.Explain(applied.Exposure.HolyGrail.ReasonKey!, applied.Exposure.HolyGrail.ReasonArgs));
|
||||
}
|
||||
context.Log($"{rendered} texts rendered");
|
||||
Assert.Greater(rendered, 80);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void StoredNumericArgumentsAreLocalisedWhenExplained()
|
||||
{
|
||||
var text = Format(Loc.Get(AdvisorKeys.DeflickerOn, Italian)!, Italian, 0.125);
|
||||
Assert.Contains("0,125", text);
|
||||
Assert.Contains("0.125", Format(Loc.Get(AdvisorKeys.DeflickerOn, English)!, English, 0.125));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task PresetsRoundTripAsJsonAndSaveAsUserPresets()
|
||||
{
|
||||
var source = new SyntheticFrameSource(DeepScenes.NightSky(jitter: 2), 2);
|
||||
var frames = Enumerable.Range(0, source.Count).Select(source.Metadata).ToList();
|
||||
var presets = SequencePresets.Generate(LightAnalyzer.Analyze(frames), await DeepReports.NightJitter, new SequenceContext { SourceWidth = 6000, SourceHeight = 4000 });
|
||||
foreach (var preset in presets)
|
||||
{
|
||||
var json = preset.ToJson();
|
||||
Assert.Equal(json, SequencePreset.FromJson(json).ToJson());
|
||||
}
|
||||
var user = presets[0].AsUserPreset(" My night ");
|
||||
Assert.True(user.IsUser);
|
||||
Assert.Equal("My night", user.Name);
|
||||
Assert.NotEqual(presets[0].Id, user.Id);
|
||||
var restored = SequencePreset.FromJson(user.ToJson());
|
||||
Assert.Equal("My night", restored.DisplayName());
|
||||
Assert.Equal(presets[0].Settings.ToJson(), restored.Settings.ToJson());
|
||||
Assert.Equal(presets[0].ExportPresetId, restored.ExportPresetId);
|
||||
}
|
||||
|
||||
private static int Render(string key, object?[] args)
|
||||
{
|
||||
foreach (var culture in new[] { English, Italian })
|
||||
{
|
||||
var format = Loc.Get(key, culture);
|
||||
Assert.NotNull(format);
|
||||
var text = Format(format!, culture, args);
|
||||
Assert.False(text.Contains('{'), $"{key} left a placeholder: {text}");
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
private static string Format(string format, CultureInfo culture, params object?[] args) => string.Format(culture, format, args);
|
||||
|
||||
private static Dictionary<string, string> Entries(ResourceSet set)
|
||||
{
|
||||
var entries = new Dictionary<string, string>(StringComparer.Ordinal);
|
||||
foreach (DictionaryEntry entry in set) entries[(string)entry.Key] = (string)entry.Value!;
|
||||
return entries;
|
||||
}
|
||||
|
||||
private static IEnumerable<string> Keys(Type type) =>
|
||||
type.GetFields(BindingFlags.Public | BindingFlags.Static).Where(f => f.IsLiteral && f.FieldType == typeof(string) && f.Name != nameof(AdvisorKeys.MissingPrefix)).Select(f => (string)f.GetRawConstantValue()!)
|
||||
.Concat(type.GetProperties(BindingFlags.Public | BindingFlags.Static).Where(p => p.PropertyType == typeof(string)).Select(p => (string)p.GetValue(null)!));
|
||||
|
||||
private static IEnumerable<string> Placeholders(string text) => PlaceholderRegex().Matches(text).Select(m => m.Groups[1].Value).Order();
|
||||
|
||||
[GeneratedRegex(@"\{(\d+)(?:[,:][^}]*)?\}")]
|
||||
private static partial Regex PlaceholderRegex();
|
||||
}
|
||||
@@ -0,0 +1,349 @@
|
||||
using Titano.Core.Advisor;
|
||||
using Titano.Core.Analysis;
|
||||
using Titano.Core.Analysis.Deep;
|
||||
using Titano.Core.Diagnostics.Synthetic;
|
||||
using Titano.Core.Mathematics;
|
||||
using Titano.Core.Project;
|
||||
using Titano.Core.Tests.Analysis.Deep;
|
||||
using Titano.Core.Video;
|
||||
using Titano.Testing;
|
||||
|
||||
namespace Titano.Core.Tests.Advisor;
|
||||
|
||||
// The class shares its name with the namespace, which an enclosing Titano.Core.* namespace would resolve first.
|
||||
using AdvisorApi = Titano.Core.Advisor.Advisor;
|
||||
|
||||
public sealed class AdvisorTests(TestContext context)
|
||||
{
|
||||
[Test]
|
||||
public async Task NightSkyGetsTheNightPresetDeflickerAndNoStabilisation()
|
||||
{
|
||||
var (light, sequence) = Inputs(new SyntheticFrameSource(DeepScenes.NightSky()));
|
||||
var deep = await DeepReports.Night;
|
||||
var result = AdvisorApi.Recommend(light, deep, sequence);
|
||||
Log(result);
|
||||
|
||||
Assert.Equal(true, Value(result, AdvisorParameters.Deflicker));
|
||||
Assert.Equal(15, Value(result, AdvisorParameters.DeflickerWindow));
|
||||
Assert.Equal(false, Value(result, AdvisorParameters.Stabilize));
|
||||
Assert.Equal(AdvisorKeys.StabilizeOff, result.Find(AdvisorParameters.Stabilize)!.ReasonKey);
|
||||
Assert.Equal("3840x2160", Value(result, AdvisorParameters.Resolution));
|
||||
Assert.Equal("4k-hevc10-archive", Value(result, AdvisorParameters.ExportPreset));
|
||||
// 15 s exposures every 20 s are a 270° shutter: already beyond the 180° target.
|
||||
Assert.Equal(false, Value(result, AdvisorParameters.MotionBlur));
|
||||
Assert.Equal(AdvisorKeys.MotionBlurAlready, result.Find(AdvisorParameters.MotionBlur)!.ReasonKey);
|
||||
Assert.Equal(TimingMode.Constant, Value(result, AdvisorParameters.TimingMode));
|
||||
Assert.Equal("24", Value(result, AdvisorParameters.FrameRate));
|
||||
Assert.Equal(AdvisorKeys.WindowMinimum, result.Find(AdvisorParameters.DeflickerWindow)!.ReasonKey);
|
||||
|
||||
var presets = SequencePresets.Generate(light, deep, sequence);
|
||||
var night = presets[0];
|
||||
Assert.Equal("night-sky", night.Id);
|
||||
Assert.Equal(AdvisorKeys.PresetNightSky, night.NameKey);
|
||||
Assert.SequenceEqual(["4K", "HEVC Main10", "24", "15"], night.NameArgs);
|
||||
Assert.Equal("4k-hevc10-archive", night.ExportPresetId);
|
||||
Assert.Equal("24", night.Settings.Timing.FrameRate.Resolve("30"));
|
||||
Assert.True(night.Settings.Exposure.Deflicker.Resolve(false));
|
||||
Assert.False(night.Settings.Motion.Stabilize.Resolve(true));
|
||||
Assert.Equal("social-vertical", presets[^1].Id);
|
||||
Assert.DoesNotContain("holy-grail", presets.Select(p => p.Id));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task InjectedJitterTurnsStabilisationOn()
|
||||
{
|
||||
var (light, sequence) = Inputs(new SyntheticFrameSource(DeepScenes.NightSky(jitter: 2), 2));
|
||||
var deep = await DeepReports.NightJitter;
|
||||
var result = AdvisorApi.Recommend(light, deep, sequence);
|
||||
var stabilize = result.Find(AdvisorParameters.Stabilize)!;
|
||||
Assert.Equal(true, stabilize.Value);
|
||||
Assert.Equal(AdvisorKeys.StabilizeOn, stabilize.ReasonKey);
|
||||
// 2 px RMS on a 160-px source is 48 px at 3840 px.
|
||||
Assert.InRange((double)stabilize.ReasonArgs[0], 40, 60);
|
||||
Assert.Equal(12.0, Value(result, AdvisorParameters.StabilizeSmoothing));
|
||||
|
||||
var night = SequencePresets.Generate(light, deep, sequence)[0];
|
||||
Assert.Equal(AdvisorKeys.PresetNightSkyStabilised, night.NameKey);
|
||||
Assert.False(night.Settings.Motion.Stabilize.IsAuto);
|
||||
Assert.True(night.Settings.Motion.Stabilize.Manual);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task HolyGrailSunsetGetsTransitionsOfHalfTheStepSpacing()
|
||||
{
|
||||
var (light, sequence) = Inputs(new SyntheticFrameSource(DeepScenes.HolyGrail()));
|
||||
var deep = await DeepReports.HolyGrail;
|
||||
var result = AdvisorApi.Recommend(light, deep, sequence);
|
||||
Log(result);
|
||||
var holyGrail = result.Find(AdvisorParameters.HolyGrail)!;
|
||||
Assert.Equal(true, holyGrail.Value);
|
||||
Assert.Equal(AdvisorKeys.HolyGrailReceived, holyGrail.ReasonKey);
|
||||
Assert.SequenceEqual([5], holyGrail.ReasonArgs.Cast<int>());
|
||||
var transition = result.Find(AdvisorParameters.TransitionLength)!;
|
||||
Assert.Equal(20, transition.Value);
|
||||
Assert.Equal(AdvisorKeys.TransitionSpacing, transition.ReasonKey);
|
||||
Assert.SequenceEqual([40.0, 20.0], transition.ReasonArgs.Select(Convert.ToDouble));
|
||||
Assert.Equal(false, Value(result, AdvisorParameters.MotionBlur));
|
||||
Assert.Equal(AdvisorKeys.MotionBlurLittle, result.Find(AdvisorParameters.MotionBlur)!.ReasonKey);
|
||||
|
||||
var presets = SequencePresets.Generate(light, deep, sequence);
|
||||
var grail = presets[0];
|
||||
Assert.Equal("holy-grail", grail.Id);
|
||||
Assert.SequenceEqual(["4K", "HEVC", "30", "20"], grail.NameArgs);
|
||||
Assert.Equal("4k-hevc", grail.ExportPresetId);
|
||||
Assert.True(grail.Settings.Exposure.HolyGrail.Resolve(false));
|
||||
Assert.Equal(20, grail.Settings.Exposure.TransitionLength.Resolve(0));
|
||||
|
||||
// Without pixels the metadata steps are trusted, with the same spacing rule and less confidence.
|
||||
var metadataOnly = AdvisorApi.Recommend(light, null, sequence);
|
||||
Assert.Equal(AdvisorKeys.HolyGrailMetadata, metadataOnly.Find(AdvisorParameters.HolyGrail)!.ReasonKey);
|
||||
Assert.Equal(20, Value(metadataOnly, AdvisorParameters.TransitionLength));
|
||||
Assert.Less(metadataOnly.Find(AdvisorParameters.HolyGrail)!.Confidence, holyGrail.Confidence);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void IrregularCadenceWithNightlyPausesIsAdaptive()
|
||||
{
|
||||
const double night = 14 * 3600;
|
||||
var source = new SyntheticFrameSource(SyntheticSequence.Create(new SyntheticSequenceOptions
|
||||
{
|
||||
Width = 96, Height = 64, FrameCount = 300, IntervalSeconds = 600, IntervalJitterSeconds = 20,
|
||||
TimeShifts = [new(60, night), new(120, night), new(180, night), new(240, night)],
|
||||
}));
|
||||
var (light, sequence) = Inputs(source);
|
||||
var result = AdvisorApi.Recommend(light, null, sequence);
|
||||
Log(result);
|
||||
var mode = result.Find(AdvisorParameters.TimingMode)!;
|
||||
Assert.Equal(TimingMode.Adaptive, mode.Value);
|
||||
Assert.Equal(AdvisorKeys.TimingSessions, mode.ReasonKey);
|
||||
Assert.Equal(5, mode.ReasonArgs[0]);
|
||||
Assert.Approximately(14.2, (double)mode.ReasonArgs[1], 0.051);
|
||||
Assert.Equal("30", Value(result, AdvisorParameters.FrameRate));
|
||||
// Pixel-based parameters wait for the deep analysis.
|
||||
foreach (var parameter in new[] { AdvisorParameters.Deflicker, AdvisorParameters.Stabilize, AdvisorParameters.Regions, AdvisorParameters.Hero })
|
||||
{
|
||||
var missing = result.Find(parameter)!;
|
||||
Assert.True(missing.IsMissingData);
|
||||
Assert.Equal(AdvisorKeys.MissingDeep, missing.ReasonKey);
|
||||
}
|
||||
|
||||
var presets = SequencePresets.Generate(light, null, sequence);
|
||||
Assert.SequenceEqual(["construction", "social-vertical"], presets.Select(p => p.Id));
|
||||
Assert.Equal(TimingMode.Adaptive, presets[0].Settings.Timing.Mode.Resolve(TimingMode.Constant));
|
||||
Assert.Equal("1080p-h264", presets[0].ExportPresetId);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task SparseGapsWithStillContentAreInterpolated()
|
||||
{
|
||||
var gapped = SyntheticSequence.Create(DeepScenes.HolyGrail().Options with { TimeShifts = [new(100, 40)] });
|
||||
var (light, sequence) = Inputs(new SyntheticFrameSource(gapped));
|
||||
var result = AdvisorApi.Recommend(light, await DeepReports.HolyGrail, sequence);
|
||||
Assert.Equal(TimingMode.Interpolated, Value(result, AdvisorParameters.TimingMode));
|
||||
Assert.Equal(FlowQualitySetting.Best, Value(result, AdvisorParameters.FlowQuality));
|
||||
Assert.Equal(TimingMode.Constant, Value(AdvisorApi.Recommend(light, null, sequence), AdvisorParameters.TimingMode));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task PeriodicFlickerWindowIsFourPeriods()
|
||||
{
|
||||
var source = new SyntheticFrameSource(SyntheticSequence.Create(new SyntheticSequenceOptions
|
||||
{
|
||||
Width = 96, Height = 64, FrameCount = 240, FlickerEv = 0.15, FlickerPeriodFrames = 8,
|
||||
}));
|
||||
var deep = await DeepAnalyzer.AnalyzeAsync(source, DeepScenes.Options);
|
||||
var (light, sequence) = Inputs(source);
|
||||
var window = AdvisorApi.Recommend(light, deep, sequence).Find(AdvisorParameters.DeflickerWindow)!;
|
||||
Assert.Equal(33, window.Value);
|
||||
Assert.Equal(AdvisorKeys.WindowPeriod, window.ReasonKey);
|
||||
Assert.Equal(8.0, window.ReasonArgs[0]);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void MissingExposureMetadataIsReportedAndChangesNothing()
|
||||
{
|
||||
var (light, sequence) = Inputs(new SyntheticFrameSource(DeepScenes.HolyGrail()) { StripExposure = true });
|
||||
Assert.True(light.ExposureValues.All(v => v is null));
|
||||
var result = AdvisorApi.Recommend(light, null, sequence);
|
||||
foreach (var parameter in new[] { AdvisorParameters.HolyGrail, AdvisorParameters.TransitionLength, AdvisorParameters.TargetShutterAngle, AdvisorParameters.MotionBlur })
|
||||
{
|
||||
var missing = result.Find(parameter)!;
|
||||
Assert.Null(missing.Value);
|
||||
Assert.Equal(0.0, missing.Confidence);
|
||||
Assert.Equal(AdvisorKeys.MissingExposure, missing.ReasonKey);
|
||||
}
|
||||
|
||||
var advised = new ProjectSettings
|
||||
{
|
||||
Exposure = new ExposureSettings
|
||||
{
|
||||
HolyGrail = new Auto<bool>().WithAdvice(true, AdvisorKeys.HolyGrailReceived, "5"),
|
||||
TransitionLength = new Auto<int>().WithAdvice(20, AdvisorKeys.TransitionSpacing, "40", "20"),
|
||||
},
|
||||
};
|
||||
var applied = AdvisorApi.Apply(advised, result);
|
||||
Assert.Same(advised.Exposure.HolyGrail, applied.Exposure.HolyGrail);
|
||||
Assert.Same(advised.Exposure.TransitionLength, applied.Exposure.TransitionLength);
|
||||
Assert.Empty(AdvisorApi.Optimise(AdvisorSection.Exposure, advised, result).Changes.Where(c => c.Parameter is AdvisorParameters.HolyGrail or AdvisorParameters.TransitionLength));
|
||||
|
||||
// A fresh project keeps its values and learns why there is no advice.
|
||||
var fresh = AdvisorApi.Apply(new ProjectSettings(), result);
|
||||
Assert.False(fresh.Exposure.HolyGrail.AutoValue);
|
||||
Assert.Equal(AdvisorKeys.MissingExposure, fresh.Exposure.HolyGrail.ReasonKey);
|
||||
Assert.Equal(0, fresh.Exposure.TransitionLength.AutoValue);
|
||||
Assert.Equal(0.0, fresh.Motion.TargetShutterAngle.AutoValue);
|
||||
Assert.Equal(AdvisorKeys.MissingExposure, fresh.Motion.TargetShutterAngle.ReasonKey);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ApplyNeverOverwritesManualValues()
|
||||
{
|
||||
var (light, sequence) = Inputs(new SyntheticFrameSource(DeepScenes.NightSky()));
|
||||
var result = AdvisorApi.Recommend(light, await DeepReports.Night, sequence);
|
||||
var manual = new ProjectSettings
|
||||
{
|
||||
Timing = new TimingSettings { FrameRate = new Auto<string>().WithManual("50") },
|
||||
Exposure = new ExposureSettings
|
||||
{
|
||||
Deflicker = new Auto<bool>().WithManual(false),
|
||||
DeflickerWindow = new Auto<int>().WithManual(99),
|
||||
},
|
||||
HeroFrame = 7,
|
||||
ExcludedFrames = [3],
|
||||
};
|
||||
var applied = AdvisorApi.Apply(manual, result);
|
||||
Assert.False(applied.Exposure.Deflicker.IsAuto);
|
||||
Assert.False(applied.Exposure.Deflicker.Resolve(true));
|
||||
Assert.True(applied.Exposure.Deflicker.AutoValue);
|
||||
Assert.Equal(99, applied.Exposure.DeflickerWindow.Resolve(0));
|
||||
Assert.Equal(15, applied.Exposure.DeflickerWindow.AutoValue);
|
||||
Assert.Equal("50", applied.Timing.FrameRate.Resolve("30"));
|
||||
Assert.Equal("24", applied.Timing.FrameRate.AutoValue);
|
||||
Assert.Equal(7, applied.HeroFrame);
|
||||
Assert.SequenceEqual([3], applied.ExcludedFrames);
|
||||
// Auto values carry the reason with culture-neutral arguments.
|
||||
Assert.Equal(AdvisorKeys.WindowMinimum, applied.Exposure.DeflickerWindow.ReasonKey);
|
||||
Assert.SequenceEqual(["15"], applied.Exposure.DeflickerWindow.ReasonArgs!);
|
||||
Assert.True(applied.Motion.Stabilize.ReasonKey == AdvisorKeys.StabilizeOff && !applied.Motion.Stabilize.AutoValue);
|
||||
Assert.Equal(applied.ToJson(), ProjectSettings.FromJson(applied.ToJson()).ToJson());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task OptimiseTakesModuleDecisionsAndReportsChanges()
|
||||
{
|
||||
var (light, sequence) = Inputs(new SyntheticFrameSource(DeepScenes.NightSky(jitter: 2), 2));
|
||||
var result = AdvisorApi.Recommend(light, await DeepReports.NightJitter, sequence);
|
||||
var settings = new ProjectSettings
|
||||
{
|
||||
Motion = new MotionSettings { Stabilize = new Auto<bool>().WithManual(false), StabilizeSmoothing = new Auto<double>().WithManual(30) },
|
||||
ExcludedFrames = [3],
|
||||
};
|
||||
|
||||
var motion = AdvisorApi.Optimise(AdvisorSection.Motion, settings, result);
|
||||
Assert.True(motion.Settings.Motion.Stabilize.IsAuto);
|
||||
Assert.True(motion.Settings.Motion.Stabilize.Resolve(false));
|
||||
Assert.Equal(30.0, motion.Settings.Motion.StabilizeSmoothing.Resolve(12));
|
||||
var change = motion.Changes.Single(c => c.Parameter == AdvisorParameters.Stabilize);
|
||||
Assert.Equal(false, change.Before);
|
||||
Assert.Equal(true, change.After);
|
||||
Assert.Equal(AdvisorKeys.StabilizeOn, change.ReasonKey);
|
||||
Assert.DoesNotContain(AdvisorParameters.StabilizeSmoothing, motion.Changes.Select(c => c.Parameter));
|
||||
Assert.Null(motion.Settings.HeroFrame);
|
||||
|
||||
var frames = AdvisorApi.Optimise(AdvisorSection.Frames, settings, result);
|
||||
Assert.Equal(result.Find(AdvisorParameters.Hero)!.Value, frames.Settings.HeroFrame);
|
||||
Assert.SequenceEqual([AdvisorParameters.Hero], frames.Changes.Select(c => c.Parameter));
|
||||
Assert.SequenceEqual([3], frames.Settings.ExcludedFrames);
|
||||
|
||||
var exposure = AdvisorApi.Optimise(AdvisorSection.Exposure, settings, result);
|
||||
var deflicker = exposure.Changes.Single(c => c.Parameter == AdvisorParameters.Deflicker);
|
||||
Assert.Null(deflicker.Before);
|
||||
Assert.Equal(true, deflicker.After);
|
||||
Assert.Equal(settings.Motion, exposure.Settings.Motion);
|
||||
|
||||
// Optimising again changes nothing.
|
||||
Assert.Empty(AdvisorApi.Optimise(AdvisorSection.Motion, motion.Settings, result).Changes);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task OptimiseExcludesFlaggedFramesAndCapsTheOutput()
|
||||
{
|
||||
var source = new SyntheticFrameSource(SyntheticSequence.Create(new SyntheticSequenceOptions
|
||||
{
|
||||
Width = 96, Height = 64, FrameCount = 40, FlickerEv = 0.05, BlackFrames = [5], DuplicateFrames = [9],
|
||||
}));
|
||||
var deep = await DeepAnalyzer.AnalyzeAsync(source, DeepScenes.Options);
|
||||
var (light, sequence) = Inputs(source);
|
||||
var result = AdvisorApi.Recommend(light, deep, sequence with { PreviewOnlyCount = 12, PreviewWidth = 1620, PreviewHeight = 1080 });
|
||||
|
||||
var frames = AdvisorApi.Optimise(AdvisorSection.Frames, new ProjectSettings { ExcludedFrames = [2] }, result);
|
||||
Assert.SequenceEqual([2, 5, 9], frames.Settings.ExcludedFrames);
|
||||
Assert.Equal(AdvisorKeys.Exclude, frames.Changes.Single(c => c.Parameter == AdvisorParameters.Excluded).ReasonKey);
|
||||
|
||||
var resolution = result.Find(AdvisorParameters.Resolution)!;
|
||||
Assert.Equal("1280x720", resolution.Value);
|
||||
Assert.Equal(AdvisorKeys.ResolutionPreview, resolution.ReasonKey);
|
||||
var big = new ProjectSettings { Export = new ExportSettings { Preset = new Auto<string>().WithManual("4k-hevc") } };
|
||||
var export = AdvisorApi.Optimise(AdvisorSection.Export, big, result);
|
||||
Assert.Equal("720p-preview", export.Settings.Export.Preset.Resolve("4k-hevc"));
|
||||
Assert.Null(export.Settings.Export.Overrides.Width);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void OutputSizeFollowsSourceShapeAndEncoders()
|
||||
{
|
||||
var (light, sequence) = Inputs(new SyntheticFrameSource(DeepScenes.HolyGrail()));
|
||||
var h264Only = sequence with { Codecs = [new EncoderCapability(VideoCodec.H264, "Software H.264", false, 1920, 1088, false)] };
|
||||
var limited = AdvisorApi.Recommend(light, null, h264Only);
|
||||
Assert.Equal("1920x1080", Value(limited, AdvisorParameters.Resolution));
|
||||
Assert.Equal(AdvisorKeys.ResolutionCodec, limited.Find(AdvisorParameters.Resolution)!.ReasonKey);
|
||||
Assert.Equal("1080p-h264", Value(limited, AdvisorParameters.ExportPreset));
|
||||
|
||||
var portrait = AdvisorApi.Recommend(light, null, sequence with { SourceWidth = 4000, SourceHeight = 6000 });
|
||||
Assert.Equal("9:16", Value(portrait, AdvisorParameters.Aspect));
|
||||
Assert.Equal("1080x1920", Value(portrait, AdvisorParameters.Resolution));
|
||||
Assert.Equal("vertical-1080x1920", Value(portrait, AdvisorParameters.ExportPreset));
|
||||
|
||||
var landscape = AdvisorApi.Recommend(light, null, sequence);
|
||||
Assert.Equal("16:9", Value(landscape, AdvisorParameters.Aspect));
|
||||
Assert.SequenceEqual([6000.0, 4000.0, 84.0], landscape.Find(AdvisorParameters.Aspect)!.ReasonArgs.Select(Convert.ToDouble));
|
||||
|
||||
var wide = AdvisorApi.Recommend(light, null, sequence with { SourceWidth = 6000, SourceHeight = 2500 });
|
||||
Assert.Equal(AdvisorKeys.AspectWide, wide.Find(AdvisorParameters.Aspect)!.ReasonKey);
|
||||
Assert.Equal(74.0, wide.Find(AdvisorParameters.Aspect)!.ReasonArgs[2]);
|
||||
Assert.Equal("3840x2160", Value(wide, AdvisorParameters.Resolution));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task RecommendationsAreDeterministic()
|
||||
{
|
||||
var (light, sequence) = Inputs(new SyntheticFrameSource(DeepScenes.NightSky()));
|
||||
var deep = await DeepReports.Night;
|
||||
var first = AdvisorApi.Recommend(light, deep, sequence);
|
||||
var second = AdvisorApi.Recommend(light, DeepAnalysisReport.FromJson(deep.ToJson()), sequence);
|
||||
Assert.SequenceEqual(first.Recommendations.Select(Describe), second.Recommendations.Select(Describe));
|
||||
}
|
||||
|
||||
private static (LightAnalysisReport Light, SequenceContext Context) Inputs(SyntheticFrameSource source, int width = 6000, int height = 4000)
|
||||
{
|
||||
var frames = Enumerable.Range(0, source.Count).Select(source.Metadata).ToList();
|
||||
var exposures = frames.Where(f => f.ExposureTime is > 0).Select(f => f.ExposureTime!.Value).ToArray();
|
||||
return (LightAnalyzer.Analyze(frames), new SequenceContext
|
||||
{
|
||||
FrameCount = frames.Count,
|
||||
SourceWidth = width,
|
||||
SourceHeight = height,
|
||||
MedianExposureSeconds = exposures.Length > 0 ? Statistics.Median(exposures) : null,
|
||||
});
|
||||
}
|
||||
|
||||
private static object? Value(AdvisorResult result, string parameter) => (result.Find(parameter) ?? throw new InvalidOperationException(parameter + " not recommended")).Value;
|
||||
|
||||
private static string Describe(Recommendation r) =>
|
||||
$"{r.Parameter}={(r.Value is int[] list ? string.Join(",", list) : r.Value)} {r.Confidence} {r.ReasonKey} [{string.Join(";", r.ReasonArgs)}]";
|
||||
|
||||
private void Log(AdvisorResult result)
|
||||
{
|
||||
foreach (var r in result.Recommendations) context.Log(Describe(r));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,327 @@
|
||||
using Titano.Core.Analysis;
|
||||
using Titano.Core.Analysis.Deep;
|
||||
using Titano.Core.Diagnostics.Synthetic;
|
||||
using Titano.Core.Imaging;
|
||||
using Titano.Testing;
|
||||
|
||||
namespace Titano.Core.Tests.Analysis.Deep;
|
||||
|
||||
public sealed class DeepAnalyzerTests(TestContext context)
|
||||
{
|
||||
[Test]
|
||||
public async Task NightSkyShowsStarsDarknessFlickerAndNoShake()
|
||||
{
|
||||
var report = await DeepReports.Night;
|
||||
context.Log($"{report.Sky} {report.Flicker} {report.Shake}");
|
||||
Assert.True(report.Sky.StarField);
|
||||
Assert.Equal(DayNight.Night, report.Sky.Light);
|
||||
Assert.Equal(report.FrameCount, report.Sky.StarFrames);
|
||||
// Uniform ±0.12 EV flicker has an RMS of 0.069 EV.
|
||||
Assert.Approximately(0.069, report.Flicker.AmplitudeEv, 0.01);
|
||||
Assert.Equal(15, report.Flicker.RecommendedWindow);
|
||||
Assert.Less(report.Shake.RmsPx, 0.05);
|
||||
Assert.Equal(1.0, report.Shake.MeasuredFraction);
|
||||
Assert.Empty(report.Issues.SceneChanges);
|
||||
Assert.Equal(0.0, report.Motion.P95Px!.Value);
|
||||
Assert.Equal(RegionMethod.Horizon, report.Regions!.Method);
|
||||
Assert.Contains(report.Findings, f => f.Key == DeepFindingKeys.StarField);
|
||||
Assert.Contains(report.Findings, f => f.Key == DeepFindingKeys.Flicker);
|
||||
Assert.True(report.Frames.FlagsOf(0).HasFlag(DeepFrameFlags.StarField | DeepFrameFlags.Dark));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task InjectedCameraJitterIsMeasuredAsShake()
|
||||
{
|
||||
var report = await DeepReports.NightJitter;
|
||||
context.Log($"{report.Shake} {report.Motion}");
|
||||
// Integer offsets uniform in −2..2 per axis: 2 px RMS in 2D.
|
||||
Assert.InRange(report.Shake.RmsPx, 1.6, 2.4);
|
||||
Assert.InRange(report.Shake.CropCost, 0.02, 0.2);
|
||||
Assert.False(report.Shake.PanDetected);
|
||||
Assert.Greater(report.Motion.P95Px!.Value, 1);
|
||||
Assert.Contains(report.Findings, f => f.Key == DeepFindingKeys.Shake);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task HolyGrailStepsAreReceivedAndSpacedByHalfTheirDistance()
|
||||
{
|
||||
var report = await DeepReports.HolyGrail;
|
||||
Assert.Equal(5, report.Exposure.MetadataSteps);
|
||||
Assert.Equal(5, report.Exposure.ReceivedSteps);
|
||||
Assert.Equal(40.0, report.Exposure.TypicalSpacing);
|
||||
Assert.Equal(20, report.Exposure.TransitionLength);
|
||||
Assert.True(report.Exposure.Steps.All(s => s.MeasuredEv is > 0.9 and < 1.1));
|
||||
Assert.InRange(report.Exposure.SceneRangeEv, 5, 6);
|
||||
Assert.Equal(DayNight.DayToNight, report.Sky.Light);
|
||||
// Brightness ramps and steps are levelled before the flow, so the static scene shows no motion.
|
||||
Assert.Equal(0.0, report.Motion.P95Px!.Value);
|
||||
Assert.Empty(report.Issues.SceneChanges);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[Case(8.0, 33)]
|
||||
[Case(12.5, 51)]
|
||||
[Case(40.0, 151)]
|
||||
public async Task PeriodicFlickerGivesAWindowOfFourPeriods(double period, int window)
|
||||
{
|
||||
var sequence = SyntheticSequence.Create(new SyntheticSequenceOptions
|
||||
{
|
||||
Width = 96, Height = 64, FrameCount = 240, FlickerEv = 0.15, FlickerPeriodFrames = period,
|
||||
});
|
||||
var report = await DeepAnalyzer.AnalyzeAsync(new SyntheticFrameSource(sequence), DeepScenes.Options);
|
||||
Assert.Approximately(period, report.Flicker.PeriodFrames!.Value, 0.05 * period);
|
||||
Assert.Equal(window, report.Flicker.RecommendedWindow);
|
||||
Assert.Equal(1, window % 2);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task BlackWhiteDuplicateAndUnreadableFramesAreFlagged()
|
||||
{
|
||||
var sequence = SyntheticSequence.Create(new SyntheticSequenceOptions
|
||||
{
|
||||
Width = 96, Height = 64, FrameCount = 60, FlickerEv = 0.02, BlackFrames = [10], WhiteFrames = [20], DuplicateFrames = [30],
|
||||
});
|
||||
var report = await DeepAnalyzer.AnalyzeAsync(new SyntheticFrameSource(sequence) { Undecodable = [40] }, DeepScenes.Options);
|
||||
Assert.SequenceEqual([10], report.Issues.Black);
|
||||
Assert.SequenceEqual([20], report.Issues.White);
|
||||
Assert.SequenceEqual([30], report.Issues.Duplicate);
|
||||
Assert.SequenceEqual([40], report.Issues.Undecodable);
|
||||
Assert.SequenceEqual([10, 20, 30, 40], report.Issues.Excludable());
|
||||
Assert.Empty(report.Issues.SceneChanges);
|
||||
Assert.Null(report.Frames.LogLuminance[40]);
|
||||
Assert.True(report.Frames.FlagsOf(40).HasFlag(DeepFrameFlags.Undecodable));
|
||||
Assert.False(report.Issues.Excludable().Contains(report.HeroIndex!.Value));
|
||||
foreach (var key in new[] { DeepFindingKeys.BlackFrames, DeepFindingKeys.WhiteFrames, DeepFindingKeys.DuplicateFrames, DeepFindingKeys.UnreadableFrames })
|
||||
Assert.Equal(FindingSeverity.Warning, report.Findings.Single(f => f.Key == key).Severity);
|
||||
Assert.Equal(4, AnalysisSummary.From(report).WarningCount);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ACutToAnotherViewIsASceneChange()
|
||||
{
|
||||
var first = new SyntheticFrameSource(SyntheticSequence.Create(new SyntheticSequenceOptions { Width = 96, Height = 64, FrameCount = 50, FlickerEv = 0.05 }));
|
||||
var second = new SyntheticFrameSource(SyntheticSequence.Create(new SyntheticSequenceOptions
|
||||
{
|
||||
Width = 96, Height = 64, FrameCount = 50, FlickerEv = 0.05, Seed = 5, HorizonFraction = 0.75, SkyLevel = 0.6, LandLevel = 0.01,
|
||||
}));
|
||||
var report = await DeepAnalyzer.AnalyzeAsync(new SplicedSource(first, second, 30), DeepScenes.Options);
|
||||
Assert.SequenceEqual([30], report.Issues.SceneChanges);
|
||||
Assert.True(report.Frames.FlagsOf(30).HasFlag(DeepFrameFlags.SceneChange));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ResumingFromACheckpointGivesTheSameReport()
|
||||
{
|
||||
var expected = (await DeepReports.HolyGrail).ToJson();
|
||||
var checkpoint = new MemoryCheckpoint();
|
||||
var crashing = new SyntheticFrameSource(DeepScenes.HolyGrail())
|
||||
{
|
||||
OnLoad = i =>
|
||||
{
|
||||
if (i == 101) throw new IOException("simulated crash");
|
||||
},
|
||||
};
|
||||
await Assert.ThrowsAsync<IOException>(() => DeepAnalyzer.AnalyzeAsync(crashing, DeepScenes.Options, checkpoint));
|
||||
var persisted = checkpoint.Frames.Count;
|
||||
Assert.InRange(persisted, 90, 101);
|
||||
|
||||
var resumed = new SyntheticFrameSource(DeepScenes.HolyGrail());
|
||||
var report = await DeepAnalyzer.AnalyzeAsync(resumed, DeepScenes.Options, checkpoint);
|
||||
Assert.Equal(expected, report.ToJson());
|
||||
// Region sample + one priming frame + the frames not yet persisted.
|
||||
Assert.Equal(DeepScenes.Options.RegionSampleFrames + 1 + (240 - persisted), resumed.Loads);
|
||||
Assert.Equal(240, checkpoint.Frames.Count);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task FileCheckpointDropsATornLineAndResumes()
|
||||
{
|
||||
var path = Path.Combine(context.CreateTempDirectory(), ".titano", DeepAnalysisCheckpointFile.FileName);
|
||||
var sequence = SyntheticSequence.Create(new SyntheticSequenceOptions { Width = 96, Height = 64, FrameCount = 40, FlickerEv = 0.05, DuplicateFrames = [7] });
|
||||
var expected = (await DeepAnalyzer.AnalyzeAsync(new SyntheticFrameSource(sequence), DeepScenes.Options)).ToJson();
|
||||
var file = new DeepAnalysisCheckpointFile(path);
|
||||
var crashing = new SyntheticFrameSource(sequence) { OnLoad = i => { if (i == 21) throw new IOException("crash"); } };
|
||||
await Assert.ThrowsAsync<IOException>(() => DeepAnalyzer.AnalyzeAsync(crashing, DeepScenes.Options, file));
|
||||
await File.AppendAllTextAsync(path, "{\"index\":20,\"flags\":\"No", context.Cancellation);
|
||||
|
||||
var report = await DeepAnalyzer.AnalyzeAsync(new SyntheticFrameSource(sequence), DeepScenes.Options, file);
|
||||
Assert.Equal(expected, report.ToJson());
|
||||
Assert.Equal(41, File.ReadAllLines(path).Length);
|
||||
|
||||
// Other options: the stale checkpoint is discarded instead of mixed in.
|
||||
var other = DeepScenes.Options with { FlowEvery = 3 };
|
||||
var fresh = await new DeepAnalysisCheckpointFile(path).LoadAsync(DeepAnalyzer.Fingerprint(40, other), context.Cancellation);
|
||||
Assert.Empty(fresh);
|
||||
file.Delete();
|
||||
Assert.FileMissing(path);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ReportRoundTripsThroughJsonWithinTheSizeBudget()
|
||||
{
|
||||
var report = await DeepReports.NightJitter;
|
||||
var json = report.ToJson();
|
||||
var copy = DeepAnalysisReport.FromJson(json);
|
||||
Assert.Equal(json, copy.ToJson());
|
||||
var perFrame = (double)System.Text.Encoding.UTF8.GetByteCount(json) / report.FrameCount;
|
||||
context.Log($"{perFrame:0.0} bytes per frame");
|
||||
Assert.LessOrEqual(perFrame, 120);
|
||||
|
||||
var path = Path.Combine(context.CreateTempDirectory(), DeepAnalysisReport.FileName);
|
||||
report.Save(path);
|
||||
Assert.Equal(json, DeepAnalysisReport.Load(path).ToJson());
|
||||
|
||||
var summary = AnalysisSummary.From(report);
|
||||
Assert.Equal(summary, AnalysisSummary.FromJson(summary.ToJson()));
|
||||
Assert.True(summary.StarField);
|
||||
Assert.Equal(DayNight.Night, summary.Light);
|
||||
Assert.Equal(report.HeroIndex, summary.HeroIndex);
|
||||
Assert.Less(summary.ToJson().Length, 400);
|
||||
Assert.Throws<InvalidDataException>(() => DeepAnalysisReport.FromJson(json.Replace("\"version\":1", "\"version\":99", StringComparison.Ordinal)));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ResultsDoNotDependOnParallelism()
|
||||
{
|
||||
var sequence = DeepScenes.NightSky(frames: 40, jitter: 2);
|
||||
var serial = await DeepAnalyzer.AnalyzeAsync(new SyntheticFrameSource(sequence, 2), DeepScenes.Options with { MaxDegreeOfParallelism = 1 });
|
||||
var parallel = await DeepAnalyzer.AnalyzeAsync(new SyntheticFrameSource(sequence, 2), DeepScenes.Options with { MaxDegreeOfParallelism = 3 });
|
||||
Assert.Equal(serial.ToJson(), parallel.ToJson());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task CancellationStopsWithinOneBatch()
|
||||
{
|
||||
using var cancellation = new CancellationTokenSource();
|
||||
var checkpoint = new MemoryCheckpoint();
|
||||
var source = new SyntheticFrameSource(DeepScenes.HolyGrail())
|
||||
{
|
||||
OnLoad = i =>
|
||||
{
|
||||
if (i == 50) cancellation.Cancel();
|
||||
},
|
||||
};
|
||||
await Assert.ThrowsAsync<OperationCanceledException>(() => DeepAnalyzer.AnalyzeAsync(source, DeepScenes.Options, checkpoint, null, cancellation.Token));
|
||||
Assert.LessOrEqual(source.Loads, DeepScenes.Options.RegionSampleFrames + 52);
|
||||
Assert.Equal(50, checkpoint.Frames.Count);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ProgressCountsEveryFrameUpToTheTotal()
|
||||
{
|
||||
var sequence = SyntheticSequence.Create(new SyntheticSequenceOptions { Width = 64, Height = 48, FrameCount = 21 });
|
||||
var reports = new List<AnalysisProgress>();
|
||||
await DeepAnalyzer.AnalyzeAsync(new SyntheticFrameSource(sequence), DeepScenes.Options, progress: new SyncProgress(reports.Add));
|
||||
Assert.Equal(11, reports.Count);
|
||||
Assert.Monotonic(reports.Select(r => (double)r.Done), strict: true);
|
||||
Assert.Equal(21, reports[^1].Done);
|
||||
Assert.True(reports.All(r => r.Total == 21 && r.FramesPerSecond > 0));
|
||||
Assert.Equal(TimeSpan.Zero, reports[^1].Eta);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task EmptyAndUnreadableSequencesGiveEmptyReports()
|
||||
{
|
||||
var empty = await DeepAnalyzer.AnalyzeAsync(new SplicedSource(new SyntheticFrameSource(DeepScenes.HolyGrail()), null!, 0) { Count = 0 }, DeepScenes.Options);
|
||||
Assert.Equal(0, empty.FrameCount);
|
||||
Assert.Equal(DayNight.Unknown, empty.Sky.Light);
|
||||
Assert.Empty(empty.Findings);
|
||||
|
||||
var unreadable = await DeepAnalyzer.AnalyzeAsync(new SyntheticFrameSource(SyntheticSequence.Create(new SyntheticSequenceOptions { FrameCount = 3 })) { Undecodable = [0, 1, 2] }, DeepScenes.Options);
|
||||
Assert.Equal(DayNight.Unknown, unreadable.Sky.Light);
|
||||
Assert.Null(unreadable.HeroIndex);
|
||||
Assert.Null(unreadable.Regions);
|
||||
Assert.SequenceEqual([0, 1, 2], unreadable.Issues.Undecodable);
|
||||
Assert.Equal(unreadable.ToJson(), DeepAnalysisReport.FromJson(unreadable.ToJson()).ToJson());
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void StarDetectorCountsPointsButNotBlobs()
|
||||
{
|
||||
using var image = new ImageBuffer(128, 96, 3);
|
||||
image.Data.Fill(1f / 2048);
|
||||
var random = new Random(3);
|
||||
var stars = 0;
|
||||
for (var y = 6; y < 90; y += 12)
|
||||
{
|
||||
for (var x = 6; x < 122; x += 12)
|
||||
{
|
||||
var v = (float)(0.2 + 0.8 * random.NextDouble());
|
||||
for (var c = 0; c < 3; c++) image[c, x, y] = v;
|
||||
stars++;
|
||||
}
|
||||
}
|
||||
// A lit window: 4×4 bright block (extended, not a star).
|
||||
for (var y = 40; y < 44; y++)
|
||||
{
|
||||
for (var x = 60; x < 64; x++)
|
||||
{
|
||||
for (var c = 0; c < 3; c++) image[c, x, y] = 0.8f;
|
||||
}
|
||||
}
|
||||
var density = StarFieldDetector.Density(image, noiseSigma: 0);
|
||||
Assert.Approximately(stars * 1e6 / (128 * 96), density, 1e-6);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void CloudCoverageCountsTexturedSkyBlocks()
|
||||
{
|
||||
using var image = new ImageBuffer(128, 64, 3);
|
||||
var sky = new float[image.PlaneLength];
|
||||
var random = new Random(9);
|
||||
for (var y = 0; y < 64; y++)
|
||||
{
|
||||
for (var x = 0; x < 128; x++)
|
||||
{
|
||||
var i = y * 128 + x;
|
||||
sky[i] = y < 32 ? 1 : 0;
|
||||
// Smooth gradient everywhere; cloud texture on the left half of the sky.
|
||||
var v = 0.2 + 0.002 * y + (y < 32 && x < 64 ? 0.15 * random.NextDouble() : 0);
|
||||
for (var c = 0; c < 3; c++) image[c, x, y] = (float)v;
|
||||
}
|
||||
}
|
||||
Assert.Approximately(0.5, CloudCoverage.Estimate(image, sky), 1e-9);
|
||||
Assert.True(double.IsNaN(CloudCoverage.Estimate(image, new float[image.PlaneLength])));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void HistogramDistanceIgnoresExposureButNotContent()
|
||||
{
|
||||
using var scene = SyntheticSequence.Create(new SyntheticSequenceOptions { Width = 96, Height = 64 }).Render(0);
|
||||
using var brighter = scene.Clone();
|
||||
foreach (ref var v in brighter.Data) v *= 1.7f;
|
||||
using var other = SyntheticSequence.Create(new SyntheticSequenceOptions { Width = 96, Height = 64, HorizonFraction = 0.8, SkyLevel = 0.6 }).Render(0);
|
||||
var a = FrameStatistics.Measure(scene);
|
||||
Assert.Less(HistogramDistance.ExposureAligned(a, FrameStatistics.Measure(brighter)), 0.02);
|
||||
Assert.Greater(HistogramDistance.ExposureAligned(a, FrameStatistics.Measure(other)), 0.3);
|
||||
}
|
||||
|
||||
/// <summary>Frames of <paramref name="first"/> before <paramref name="cut"/>, then frames of <paramref name="second"/>.</summary>
|
||||
private sealed class SplicedSource(IFrameSource first, IFrameSource second, int cut) : IFrameSource
|
||||
{
|
||||
public int Count { get; init; } = first.Count;
|
||||
|
||||
public LightFrame Metadata(int index) => first.Metadata(index);
|
||||
|
||||
public ValueTask<ImageBuffer?> LoadAsync(int index, int maxLongEdge, CancellationToken cancellationToken) =>
|
||||
(index < cut ? first : second).LoadAsync(index, maxLongEdge, cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>Reports synchronously (Progress<T> posts to the thread pool and may reorder).</summary>
|
||||
private sealed class SyncProgress(Action<AnalysisProgress> report) : IProgress<AnalysisProgress>
|
||||
{
|
||||
public void Report(AnalysisProgress value) => report(value);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Deep reports of the shared scenes, computed once per test run.</summary>
|
||||
internal static class DeepReports
|
||||
{
|
||||
private static readonly Lazy<Task<DeepAnalysisReport>> NightReport = new(() => DeepAnalyzer.AnalyzeAsync(new SyntheticFrameSource(DeepScenes.NightSky()), DeepScenes.Options));
|
||||
private static readonly Lazy<Task<DeepAnalysisReport>> NightJitterReport = new(() => DeepAnalyzer.AnalyzeAsync(new SyntheticFrameSource(DeepScenes.NightSky(jitter: 2), 2), DeepScenes.Options));
|
||||
private static readonly Lazy<Task<DeepAnalysisReport>> HolyGrailReport = new(() => DeepAnalyzer.AnalyzeAsync(new SyntheticFrameSource(DeepScenes.HolyGrail()), DeepScenes.Options));
|
||||
|
||||
public static Task<DeepAnalysisReport> Night => NightReport.Value;
|
||||
public static Task<DeepAnalysisReport> NightJitter => NightJitterReport.Value;
|
||||
public static Task<DeepAnalysisReport> HolyGrail => HolyGrailReport.Value;
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
using Titano.Core.Analysis;
|
||||
using Titano.Core.Analysis.Deep;
|
||||
using Titano.Core.Diagnostics.Synthetic;
|
||||
using Titano.Core.Imaging;
|
||||
|
||||
namespace Titano.Core.Tests.Analysis.Deep;
|
||||
|
||||
/// <summary>
|
||||
/// <see cref="IFrameSource"/> over a <see cref="SyntheticSequence"/>. With <paramref name="jitter"/> > 0 the sequence is
|
||||
/// rendered <paramref name="jitter"/> pixels larger on every side and each frame is cropped at a seeded integer offset
|
||||
/// in ±jitter, which shakes the camera by a known amount.
|
||||
/// </summary>
|
||||
internal sealed class SyntheticFrameSource(SyntheticSequence sequence, int jitter = 0, int seed = 11) : IFrameSource
|
||||
{
|
||||
private readonly (int X, int Y)[] _offsets = Offsets(sequence.Count, jitter, seed);
|
||||
private int _loads;
|
||||
|
||||
public SyntheticSequence Sequence { get; } = sequence;
|
||||
|
||||
public int Width => Sequence.Options.Width - 2 * jitter;
|
||||
public int Height => Sequence.Options.Height - 2 * jitter;
|
||||
public int Count => Sequence.Count;
|
||||
|
||||
/// <summary>Total calls of <see cref="LoadAsync"/>.</summary>
|
||||
public int Loads => Volatile.Read(ref _loads);
|
||||
|
||||
/// <summary>Frames that "fail to decode".</summary>
|
||||
public HashSet<int> Undecodable { get; init; } = [];
|
||||
|
||||
/// <summary>Called on every load before decoding (may throw to simulate a crash, or cancel a token).</summary>
|
||||
public Action<int>? OnLoad { get; set; }
|
||||
|
||||
/// <summary>Metadata without shutter time and aperture when true.</summary>
|
||||
public bool StripExposure { get; init; }
|
||||
|
||||
public LightFrame Metadata(int index)
|
||||
{
|
||||
var frame = LightFrame.From(Sequence.Metadata[index], index) with { Width = Width, Height = Height };
|
||||
return StripExposure ? frame with { ExposureTime = null, FNumber = null } : frame;
|
||||
}
|
||||
|
||||
public ValueTask<ImageBuffer?> LoadAsync(int index, int maxLongEdge, CancellationToken cancellationToken)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
Interlocked.Increment(ref _loads);
|
||||
OnLoad?.Invoke(index);
|
||||
if (Undecodable.Contains(index)) return ValueTask.FromResult<ImageBuffer?>(null);
|
||||
using var full = Sequence.Render(index);
|
||||
var (dx, dy) = _offsets[index];
|
||||
var image = new ImageBuffer(Width, Height, 3, clear: false);
|
||||
for (var c = 0; c < 3; c++)
|
||||
{
|
||||
for (var y = 0; y < Height; y++)
|
||||
full.Row(c, y + jitter + dy).Slice(jitter + dx, Width).CopyTo(image.Row(c, y));
|
||||
}
|
||||
if (int.Max(Width, Height) <= maxLongEdge) return ValueTask.FromResult<ImageBuffer?>(image);
|
||||
using (image) return ValueTask.FromResult<ImageBuffer?>(AnalysisImage.Downscale(image, maxLongEdge));
|
||||
}
|
||||
|
||||
private static (int, int)[] Offsets(int count, int jitter, int seed)
|
||||
{
|
||||
var random = new Random(seed);
|
||||
var offsets = new (int, int)[count];
|
||||
for (var i = 0; i < count; i++) offsets[i] = jitter > 0 ? (random.Next(-jitter, jitter + 1), random.Next(-jitter, jitter + 1)) : (0, 0);
|
||||
return offsets;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>In-memory checkpoint that records what was persisted.</summary>
|
||||
internal sealed class MemoryCheckpoint : IDeepAnalysisCheckpoint
|
||||
{
|
||||
private string? _fingerprint;
|
||||
|
||||
public List<DeepFrame> Frames { get; } = [];
|
||||
|
||||
public ValueTask<IReadOnlyList<DeepFrame>> LoadAsync(string fingerprint, CancellationToken cancellationToken)
|
||||
{
|
||||
if (_fingerprint != fingerprint) Frames.Clear();
|
||||
_fingerprint = fingerprint;
|
||||
return ValueTask.FromResult<IReadOnlyList<DeepFrame>>([.. Frames]);
|
||||
}
|
||||
|
||||
public ValueTask AppendAsync(IReadOnlyList<DeepFrame> frames, CancellationToken cancellationToken)
|
||||
{
|
||||
Frames.AddRange(frames);
|
||||
return ValueTask.CompletedTask;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The synthetic scenes the deep-analysis and advisor tests share (small frames, fast).</summary>
|
||||
internal static class DeepScenes
|
||||
{
|
||||
/// <summary>Options for the tests: small sources are analysed at native size, flow on every 5th pair, two workers.</summary>
|
||||
public static DeepAnalysisOptions Options { get; } = new() { MinAnalysisLongEdge = 64, FlowEvery = 5, MaxDegreeOfParallelism = 2, RegionSampleFrames = 9 };
|
||||
|
||||
/// <summary>Night sky with stars over dark land and random flicker.</summary>
|
||||
public static SyntheticSequence NightSky(int frames = 90, int jitter = 0) => SyntheticSequence.Create(new SyntheticSequenceOptions
|
||||
{
|
||||
Width = 160 + 2 * jitter,
|
||||
Height = 112 + 2 * jitter,
|
||||
FrameCount = frames,
|
||||
IntervalSeconds = 20,
|
||||
BaseExposureTime = 15,
|
||||
BaseFNumber = 2.8,
|
||||
BaseIso = 3200,
|
||||
StarField = true,
|
||||
StarCount = 160,
|
||||
FlickerEv = 0.12,
|
||||
Start = new DateTime(2024, 8, 12, 23, 0, 0),
|
||||
});
|
||||
|
||||
/// <summary>Sunset: the scene darkens 6 EV while the camera opens up 1 EV every 40 frames.</summary>
|
||||
public static SyntheticSequence HolyGrail(int frames = 240) => SyntheticSequence.Create(new SyntheticSequenceOptions
|
||||
{
|
||||
Width = 160,
|
||||
Height = 112,
|
||||
FrameCount = frames,
|
||||
IntervalSeconds = 15,
|
||||
BaseExposureTime = 1.0 / 250,
|
||||
StartEv = 0.5,
|
||||
EndEv = -5.5,
|
||||
FlickerEv = 0.03,
|
||||
ExposureSteps = [new(40, -1), new(80, -1), new(120, -1), new(160, -1), new(200, -1)],
|
||||
});
|
||||
}
|
||||
Reference in new issue
Block a user