diff --git a/i18n/en/Advisor.resx b/i18n/en/Advisor.resx
new file mode 100644
index 00000000..fad2d883
--- /dev/null
+++ b/i18n/en/Advisor.resx
@@ -0,0 +1,107 @@
+
+
+ text/microsoft-resx
+ 2.0
+ System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+ {0} frames are black (lens cap or missed exposure).{0} frame count
+ The camera body changes {0} times.{0} change count
+ The camera clock jumps {0} times (largest jump {1:0} s).{0} jump count; {1} largest jump in seconds, signed
+ Clouds cover about {0:0}% of the sky on average.{0} mean cloud coverage in percent
+ Covers day and night: {0} day, {1} twilight and {2} night frames.{0} day frames; {1} twilight frames; {2} night frames
+ {0} frames repeat the previous frame.{0} frame count
+ {0} frames share their capture time with the previous frame.{0} frame count
+ {0} exposure changes, typically {1:0} frames apart, {2:+0.0;-0.0;0} EV in total.{0} step count; {1} median frames between steps (0 with one step); {2} summed camera EV change
+ Brightness flickers by {0:0.###} EV around its smooth course.{0} RMS flicker in EV
+ {0} gaps in the cadence; the longest lasts {1:0} s.{0} gap count; {1} longest gap in seconds
+ Intervals vary by {0:0.##} s around {1:0.##} s.{0} interval jitter (median absolute deviation) in seconds; {1} median interval in seconds
+ The lens changes {0} times.{0} change count
+ {0} frames have no shutter time or aperture in their metadata.{0} frame count
+ {0} frames have a different orientation.{0} frame count
+ {0} frames differ from the main size {1}×{2}.{0} frame count; {1} main width in pixels; {2} main height in pixels
+ Only {0} of {1} frames have a capture time, so cadence and gaps cannot be measured.{0} frames with a capture time; {1} frames in total
+ {0} frames are out of time order.{0} frame count
+ The view drifts by {0:0.##} px per frame (pan or slider).{0} drift in source pixels per frame
+ The view jumps at {0} frames (camera moved or bumped).{0} frame count
+ Shot in {0} separate sessions.{0} session count
+ The camera shakes by {0:0.##} px RMS; hiding it costs {1:0.#}% of the frame.{0} shake RMS in source pixels; {1} crop cost in percent of the area
+ Stars are visible on {0} frames.{0} frame count
+ {0} logged exposure changes never reached the pixels.{0} step count
+ No time zone recorded; a UTC offset of {0} min was estimated from the longitude.{0} UTC offset in minutes
+ {0} frames could not be decoded.{0} frame count
+ Colour balance jumps by {0:0.#}% between frames.{0} RMS colour-ratio jitter in percent
+ {0} frames are blown out to white.{0} frame count
+ Needs the deep analysis of the pixels, which has not run yet; nothing was changed.no placeholders
+ Shutter time or aperture is missing from the metadata, so this cannot be decided; nothing was changed.no placeholders
+ Too few frame pairs to measure motion; nothing was changed.no placeholders
+ Shake was measurable on only {0}% of the frames (too little texture); nothing was changed.{0} percent of frame pairs with a measured shift
+ The source resolution is unknown; nothing was changed.no placeholders
+ Only {0} of {1} frames have a capture time, so this cannot be measured; nothing was changed.{0} frames with a capture time; {1} frames in total
+ Construction cam — {0} {1} {2} fps, adaptive timing{0} resolution label such as 1080p; {1} codec label such as H.264; {2} frame rate
+ Holy grail sunset — {0} {1} {2} fps, transitions {3}{0} resolution label such as 4K; {1} codec label such as HEVC; {2} frame rate; {3} transition length in frames
+ Night sky — {0} {1} {2} fps, deflicker {3}{0} resolution label such as 4K; {1} codec label such as HEVC Main10; {2} frame rate; {3} deflicker window in frames
+ Night sky — {0} {1} {2} fps, deflicker {3}, stabilise{0} resolution label such as 4K; {1} codec label such as HEVC Main10; {2} frame rate; {3} deflicker window in frames
+ Social vertical {0}×{1}{0} width in pixels; {1} height in pixels
+ Standard — {0} {1} {2} fps{0} resolution label such as 1080p; {1} codec label such as H.264; {2} frame rate
+ {0} sessions over {1} days with pauses: adaptive timing in a widely compatible 1080p file.{0} session count; {1} capture span in days
+ {0} exposure steps across a {1} EV change of light: smooth day-to-night transitions.{0} received step count; {1} change of scene brightness in EV
+ Stars or a dark sky on {0}% of the frames: dark gradients need 10 bits and steady brightness.{0} percent of frames with stars, or of dark frames
+ A 9:16 crop for phones and social feeds.no placeholders
+ General settings for this sequence.no placeholders
+ The {0}×{1} source cropped to 16:9 keeps {2}% of its height.{0} source width in pixels; {1} source height in pixels; {2} kept height in percent
+ The source is already 16:9.no placeholders
+ Portrait source: 9:16 fills a phone screen.no placeholders
+ The {0}×{1} source cropped to 16:9 keeps {2}% of its width.{0} source width in pixels; {1} source height in pixels; {2} kept width in percent
+ Flicker is {0} EV, below the visible 0.02 EV: deflicker stays off.{0} RMS flicker in EV
+ Brightness deviates by {0} EV from its smooth course: deflicker removes the flicker.{0} RMS flicker in EV
+ {0} black, white, duplicate or unreadable frames would flash or stutter in the video: excluded.{0} frame count
+ Night sky: 10-bit HEVC keeps dark gradients free of banding.no placeholders
+ Best preset for a {0}×{1} output with the available encoders.{0} output width in pixels; {1} output height in pixels
+ Portrait framing: vertical 1080×1920 for phones.no placeholders
+ The plan is scaled so the {0} frames last {1} s at {2} fps.{0} frame count; {1} target duration in seconds; {2} frame rate
+ Balanced flow quality is enough for motion blur and previews.no placeholders
+ Interpolated frames need per-pixel motion: best flow quality.no placeholders
+ Moderate motion ({0} px per frame): the 24 fps cinema rate gives a {1} s clip.{0} speed of moving content in output pixels per frame; {1} clip duration in seconds
+ Slow or unmeasured motion: 30 fps gives a {0} s clip.{0} clip duration in seconds
+ Fast motion ({0} px per frame): 24 fps slows it down; the clip lasts {1} s.{0} speed of moving content in output pixels per frame; {1} clip duration in seconds
+ {0} frames fill {1} s best at {2} fps.{0} frame count; {1} target duration in seconds; {2} frame rate
+ {0} frames: 60 fps keeps the clip to {1} s.{0} frame count; {1} clip duration in seconds
+ Capture over several sessions: 30 fps gives a {0} s clip.{0} clip duration in seconds
+ Only {0} frames: 24 fps keeps the clip {1} s long.{0} frame count; {1} clip duration in seconds
+ The horizon sits {0}% from the top: the crop places it on the nearest third.{0} horizon position in percent of the source height
+ Frame {0} is sharp and well exposed, without clipped highlights.{0} frame number, counted from 1
+ {0} exposure changes in the metadata (pixels not checked yet): each is spread over a smooth transition.{0} logged step count
+ Exposure settings never change: no transitions needed.no placeholders
+ The camera logged {0} exposure changes but the pixels show none: no transitions needed.{0} logged step count
+ {0} exposure changes reached the pixels: each is spread over a smooth transition.{0} received step count
+ The exposure already gives a {0}° shutter angle, at least the {1}° target: no synthetic blur needed.{0} real shutter angle in degrees; {1} target angle in degrees
+ Content moves only {0} px per frame: blur would be invisible, so it stays off.{0} speed of moving content in output pixels per frame
+ Real shutter angle {0}° and motion of {1} px per frame: blurring to {2}° adds {3} px trails that hide strobing.{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
+ Horizon found with {0}% confidence: sky and land are deflickered separately.{0} mask confidence in percent
+ Sky separated by brightness with {0}% confidence: sky and land are deflickered separately.{0} mask confidence in percent
+ The sky/land split is only {0}% reliable: one curve for the whole frame is safer.{0} mask confidence in percent
+ The {0} encoder handles at most {1}×{2}.{0} encoder name; {1} maximum width in pixels; {2} maximum height in pixels
+ {0} frames decode only as {1}×{2} embedded previews, which cap the output.{0} frame count; {1} preview width in pixels; {2} preview height in pixels
+ Largest standard size within the {0}×{1} source.{0} source width in pixels; {1} source height in pixels
+ 180° is the film look; the real shutter angle is {0}° ({1} s exposure every {2} s).{0} real shutter angle in degrees; {1} median exposure time in seconds; {2} median interval in seconds
+ Shake of {0} px at output size, but hiding it crops {1}% of the frame: check the framing.{0} shake RMS in output pixels; {1} crop cost in percent of the area
+ Measured shake of {0} px at output size (0.3 px or less): the camera was steady.{0} shake RMS in output pixels
+ Measured shake of {0} px at output size (above 0.3 px): stabilisation crops {1}% of the frame area.{0} shake RMS in output pixels; {1} crop cost in percent of the area
+ Smoothing the camera path over {0} frames removes shake and keeps deliberate pans.{0} smoothing sigma in frames
+ Strong flicker ({0} EV): every frame lands on the smooth curve.{0} RMS flicker in EV
+ Mild flicker ({0} EV): reliable frames keep 20% of their own variation.{0} RMS flicker in EV
+ Intervals vary by {0} s around {1} s: adaptive timing follows the capture clock so motion stays even.{0} interval jitter in seconds; {1} median interval in seconds
+ {0} gaps in the cadence: adaptive timing keeps the output pace true to capture time.{0} gap count
+ Steady {0} s interval (jitter {1} s): each photo becomes one video frame.{0} median interval in seconds; {1} jitter in seconds
+ Shot in {0} sessions with pauses up to {1} h: adaptive timing keeps the pauses short and the pace even.{0} session count; {1} longest pause in hours
+ {0} short gaps, but motion is unmeasured or fast: constant timing skips them cleanly.{0} gap count
+ {0} short gaps and smooth motion ({1} px per frame): interpolated frames fill the gaps.{0} gap count; {1} speed of moving content in output pixels per frame
+ A single exposure step: a {0}-frame transition keeps the change gentle.{0} transition length in frames
+ Exposure steps are {0} frames apart: transitions of half that ({1} frames) never overlap.{0} median frames between steps; {1} transition length in frames
+ Colour balance is steady ({0}% from frame to frame): no smoothing needed.{0} RMS colour-ratio jitter in percent
+ Colour balance jumps by {0}% from frame to frame: smoothing steadies it and keeps the slow drift.{0} RMS colour-ratio jitter in percent
+ Flicker stays correlated over {0} frames: a {1}-frame window spans four times that.{0} correlation length in frames; {1} window in frames
+ Flicker drifts over {0} frames: the window is capped at {1} frames so real changes of light survive.{0} flicker period or correlation length in frames; {1} window in frames
+ Flicker changes from frame to frame without a rhythm: the shortest robust window, {0} frames, removes it.{0} window in frames
+ Flicker repeats every {0} frames: a {1}-frame window averages four cycles.{0} flicker period in frames; {1} window in frames
+
diff --git a/i18n/it/Advisor.it.resx b/i18n/it/Advisor.it.resx
new file mode 100644
index 00000000..88685171
--- /dev/null
+++ b/i18n/it/Advisor.it.resx
@@ -0,0 +1,107 @@
+
+
+ text/microsoft-resx
+ 2.0
+ System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+ {0} fotogrammi sono neri (tappo sull'obiettivo o scatto mancato).
+ Il corpo macchina cambia {0} volte.
+ L'orologio della fotocamera salta {0} volte (salto maggiore {1:0} s).
+ Le nuvole coprono in media circa il {0:0}% del cielo.
+ Copre giorno e notte: {0} fotogrammi di giorno, {1} al crepuscolo e {2} di notte.
+ {0} fotogrammi ripetono il precedente.
+ {0} fotogrammi hanno lo stesso orario di scatto del precedente.
+ {0} cambi di esposizione, di solito ogni {1:0} fotogrammi, {2:+0.0;-0.0;0} EV in totale.
+ La luminosità sfarfalla di {0:0.###} EV attorno al suo andamento regolare.
+ {0} pause nella cadenza; la più lunga dura {1:0} s.
+ Gli intervalli variano di {0:0.##} s attorno a {1:0.##} s.
+ L'obiettivo cambia {0} volte.
+ {0} fotogrammi non hanno tempo di scatto o diaframma nei metadati.
+ {0} fotogrammi hanno un orientamento diverso.
+ {0} fotogrammi hanno dimensioni diverse da {1}×{2}.
+ Solo {0} fotogrammi su {1} hanno un orario di scatto: cadenza e pause non sono misurabili.
+ {0} fotogrammi sono fuori ordine temporale.
+ L'inquadratura scorre di {0:0.##} px per fotogramma (panoramica o slider).
+ L'inquadratura salta in {0} fotogrammi (fotocamera spostata o urtata).
+ Ripreso in {0} sessioni separate.
+ La fotocamera vibra di {0:0.##} px RMS; compensarla costa il {1:0.#}% dell'inquadratura.
+ Le stelle sono visibili in {0} fotogrammi.
+ {0} cambi di esposizione registrati non hanno raggiunto i pixel.
+ Fuso orario non registrato; uno scostamento UTC di {0} min è stato stimato dalla longitudine.
+ {0} fotogrammi non sono decodificabili.
+ Il bilanciamento del colore varia del {0:0.#}% tra un fotogramma e l'altro.
+ {0} fotogrammi sono completamente bruciati.
+ Serve l'analisi approfondita dei pixel, non ancora eseguita; nulla è stato cambiato.
+ Tempo di scatto o diaframma mancano nei metadati, quindi non si può decidere; nulla è stato cambiato.
+ Troppo poche coppie di fotogrammi per misurare il movimento; nulla è stato cambiato.
+ La vibrazione era misurabile solo sul {0}% dei fotogrammi (poca texture); nulla è stato cambiato.
+ La risoluzione della sorgente è sconosciuta; nulla è stato cambiato.
+ Solo {0} fotogrammi su {1} hanno un orario di scatto, quindi non è misurabile; nulla è stato cambiato.
+ Cantiere — {0} {1} {2} fps, temporizzazione adattiva
+ Tramonto holy grail — {0} {1} {2} fps, transizioni {3}
+ Cielo notturno — {0} {1} {2} fps, deflicker {3}
+ Cielo notturno — {0} {1} {2} fps, deflicker {3}, stabilizza
+ Social verticale {0}×{1}
+ Standard — {0} {1} {2} fps
+ {0} sessioni in {1} giorni con pause: temporizzazione adattiva in un file 1080p ampiamente compatibile.
+ {0} cambi di esposizione su una variazione di luce di {1} EV: transizioni morbide tra giorno e notte.
+ Stelle o cielo scuro nel {0}% dei fotogrammi: i gradienti scuri richiedono 10 bit e luminosità stabile.
+ Un ritaglio 9:16 per telefoni e social.
+ Impostazioni generali per questa sequenza.
+ La sorgente {0}×{1} ritagliata a 16:9 conserva il {2}% dell'altezza.
+ La sorgente è già in 16:9.
+ Sorgente verticale: il 9:16 riempie lo schermo di un telefono.
+ La sorgente {0}×{1} ritagliata a 16:9 conserva il {2}% della larghezza.
+ Lo sfarfallio è di {0} EV, sotto gli 0,02 EV visibili: il deflicker resta spento.
+ La luminosità si discosta di {0} EV dal suo andamento regolare: il deflicker elimina lo sfarfallio.
+ {0} fotogrammi neri, bianchi, duplicati o illeggibili lampeggerebbero o farebbero scattare il video: esclusi.
+ Cielo notturno: HEVC a 10 bit evita le bande nei gradienti scuri.
+ Il preset migliore per un'uscita {0}×{1} con i codificatori disponibili.
+ Inquadratura verticale: 1080×1920 per telefoni.
+ Il piano viene scalato perché i {0} fotogrammi durino {1} s a {2} fps.
+ La qualità del flusso bilanciata basta per la sfocatura di movimento e le anteprime.
+ I fotogrammi interpolati richiedono il movimento per pixel: qualità del flusso massima.
+ Movimento moderato ({0} px per fotogramma): la cadenza cinema di 24 fps dà una clip di {1} s.
+ Movimento lento o non misurato: a 30 fps la clip dura {0} s.
+ Movimento rapido ({0} px per fotogramma): a 24 fps rallenta; la clip dura {1} s.
+ {0} fotogrammi riempiono al meglio {1} s a {2} fps.
+ {0} fotogrammi: a 60 fps la clip dura {1} s.
+ Ripresa in più sessioni: a 30 fps la clip dura {0} s.
+ Solo {0} fotogrammi: a 24 fps la clip dura {1} s.
+ L'orizzonte è al {0}% dall'alto: il ritaglio lo porta sul terzo più vicino.
+ Il fotogramma {0} è nitido e ben esposto, senza alte luci bruciate.
+ {0} cambi di esposizione nei metadati (pixel non ancora verificati): ognuno viene distribuito su una transizione morbida.
+ Le impostazioni di esposizione non cambiano mai: nessuna transizione necessaria.
+ La fotocamera ha registrato {0} cambi di esposizione ma i pixel non ne mostrano: nessuna transizione necessaria.
+ {0} cambi di esposizione hanno raggiunto i pixel: ognuno viene distribuito su una transizione morbida.
+ L'esposizione dà già un angolo di {0}°, almeno i {1}° previsti: nessuna sfocatura sintetica necessaria.
+ Il contenuto si sposta solo di {0} px per fotogramma: la sfocatura sarebbe invisibile, quindi resta spenta.
+ Angolo reale {0}° e movimento di {1} px per fotogramma: la sfocatura a {2}° aggiunge scie di {3} px che nascondono gli scatti.
+ Orizzonte trovato con affidabilità del {0}%: cielo e terreno vengono corretti separatamente.
+ Cielo separato per luminosità con affidabilità del {0}%: cielo e terreno vengono corretti separatamente.
+ La separazione cielo/terreno è affidabile solo al {0}%: una curva unica per tutta l'immagine è più sicura.
+ Il codificatore {0} gestisce al massimo {1}×{2}.
+ {0} fotogrammi si decodificano solo come anteprime incorporate {1}×{2}, che limitano l'uscita.
+ La dimensione standard più grande entro la sorgente {0}×{1}.
+ 180° è l'aspetto cinematografico; l'angolo d'otturatore reale è {0}° (esposizione di {1} s ogni {2} s).
+ Vibrazione di {0} px alla risoluzione di uscita, ma compensarla ritaglia il {1}% dell'inquadratura: controlla il taglio.
+ Vibrazione misurata di {0} px alla risoluzione di uscita (al massimo 0,3 px): la fotocamera era stabile.
+ Vibrazione misurata di {0} px alla risoluzione di uscita (oltre 0,3 px): la stabilizzazione ritaglia il {1}% dell'area.
+ Smussare il percorso della fotocamera su {0} fotogrammi elimina la vibrazione e conserva le panoramiche volute.
+ Sfarfallio forte ({0} EV): ogni fotogramma viene portato sulla curva regolare.
+ Sfarfallio lieve ({0} EV): i fotogrammi affidabili conservano il 20% della propria variazione.
+ Gli intervalli variano di {0} s attorno a {1} s: la temporizzazione adattiva segue l'orario di scatto e rende il movimento uniforme.
+ {0} pause nella cadenza: la temporizzazione adattiva mantiene il ritmo fedele all'orario di scatto.
+ Intervallo costante di {0} s (variazione {1} s): ogni foto diventa un fotogramma del video.
+ Ripreso in {0} sessioni con pause fino a {1} h: la temporizzazione adattiva accorcia le pause e mantiene il ritmo.
+ {0} brevi pause, ma il movimento non è misurato o è rapido: la temporizzazione costante le salta in modo pulito.
+ {0} brevi pause e movimento regolare ({1} px per fotogramma): i fotogrammi interpolati riempiono le pause.
+ Un solo cambio di esposizione: una transizione di {0} fotogrammi lo rende graduale.
+ I cambi di esposizione distano {0} fotogrammi: transizioni lunghe la metà ({1} fotogrammi) non si sovrappongono mai.
+ Il bilanciamento del colore è stabile ({0}% tra fotogrammi): nessuno smussamento necessario.
+ Il bilanciamento del colore varia del {0}% tra fotogrammi: lo smussamento lo stabilizza e mantiene la deriva lenta.
+ Lo sfarfallio resta correlato per {0} fotogrammi: una finestra di {1} fotogrammi ne copre quattro volte tanto.
+ Lo sfarfallio varia su {0} fotogrammi: la finestra è limitata a {1} fotogrammi per conservare i veri cambi di luce.
+ Lo sfarfallio cambia da un fotogramma all'altro senza ritmo: la finestra robusta più corta, {0} fotogrammi, lo elimina.
+ Lo sfarfallio si ripete ogni {0} fotogrammi: una finestra di {1} fotogrammi media quattro cicli.
+
diff --git a/src/Titano.Core/Advisor/Advisor.cs b/src/Titano.Core/Advisor/Advisor.cs
new file mode 100644
index 00000000..40eca224
--- /dev/null
+++ b/src/Titano.Core/Advisor/Advisor.cs
@@ -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;
+
+///
+/// The analysis advisor (BRIEF §10.3, §10.4): turns the light and deep analyses into explained recommendations
+/// (), stores them as Auto values without touching manual ones (), and takes
+/// the heavier per-section decisions on request (). Deterministic; every reason is a resource
+/// key plus arguments.
+///
+public static class Advisor
+{
+ ///
+ /// Recommendations for every parameter the rules cover (see ), in section order, plus
+ /// every finding of both analyses. Without a deep report, pixel-based parameters get missing-data recommendations.
+ ///
+ public static AdvisorResult Recommend(LightAnalysisReport light, DeepAnalysisReport? deep, SequenceContext context)
+ {
+ ArgumentNullException.ThrowIfNull(light);
+ ArgumentNullException.ThrowIfNull(context);
+ var findings = new List(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);
+ }
+
+ ///
+ /// Fills , and 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 .
+ ///
+ 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;
+ }
+
+ ///
+ /// "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.
+ ///
+ public static OptimiseResult Optimise(AdvisorSection section, ProjectSettings settings, AdvisorResult result)
+ {
+ ArgumentNullException.ThrowIfNull(settings);
+ ArgumentNullException.ThrowIfNull(result);
+ var optimised = settings;
+ var changes = new List();
+ 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);
+ }
+
+ /// Localised text of a recommendation in the current UI culture.
+ public static string Explain(Recommendation recommendation)
+ {
+ ArgumentNullException.ThrowIfNull(recommendation);
+ return Loc.L(recommendation.ReasonKey, [.. recommendation.ReasonArgs]);
+ }
+
+ ///
+ /// Localised text of a stored reason (/): numeric
+ /// arguments, stored culture-neutral, are parsed back so they format with the current culture.
+ ///
+ public static string Explain(string reasonKey, IReadOnlyList? 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);
+ }
+}
diff --git a/src/Titano.Core/Advisor/AdvisorKeys.cs b/src/Titano.Core/Advisor/AdvisorKeys.cs
new file mode 100644
index 00000000..26688e9a
--- /dev/null
+++ b/src/Titano.Core/Advisor/AdvisorKeys.cs
@@ -0,0 +1,97 @@
+namespace Titano.Core.Advisor;
+
+///
+/// Resource keys (area Advisor) of the advisor's reasons, missing-data notes and sequence presets. Each key is
+/// written through LocKey(…) so Titano.Tools i18n check verifies it exists in every required culture;
+/// the resx comment of each key says what its placeholders hold.
+///
+public static class AdvisorKeys
+{
+ /// Every missing-data key starts with this; such a reason never carries a value.
+ 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");
+
+ /// Identity function that marks a literal as a resource key for the i18n check.
+ private static string LocKey(string key) => key;
+}
diff --git a/src/Titano.Core/Advisor/AdvisorRules.cs b/src/Titano.Core/Advisor/AdvisorRules.cs
new file mode 100644
index 00000000..4c3888ab
--- /dev/null
+++ b/src/Titano.Core/Advisor/AdvisorRules.cs
@@ -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;
+
+///
+/// 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
+/// reason.
+///
+internal sealed class AdvisorRules
+{
+ /// Visible shake threshold in output pixels (BRIEF §10.3).
+ public const double ShakeThresholdPx = 0.3;
+
+ /// Film-look target shutter angle in degrees.
+ public const double TargetShutterAngle = 180;
+
+ /// Path smoothing σ in frames (as StabilizerOptions.SmoothingSigma).
+ 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 _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 Run()
+ {
+ Export();
+ Frames();
+ Timing();
+ Exposure();
+ Motion();
+ Camera();
+ return [.. _result.OrderBy(r => r.Section)];
+ }
+
+ /// Converts deep-analysis pixels (source resolution) to output pixels.
+ 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);
+
+ ///
+ /// 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.
+ ///
+ 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);
+ }
+
+ /// Presets for one output size in order of preference, with the reason each one carries.
+ 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);
+ }
+
+ /// Whether an encoder for handles the size (either orientation); with no
+ /// capability list everything fits. is the codec's largest capability, if any.
+ 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));
+ }
+
+ /// Hero frame from the deep analysis; exclusion of undecodable, black, white and duplicate frames.
+ 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);
+ }
+
+ ///
+ /// 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.
+ ///
+ 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));
+ }
+
+ ///
+ /// 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.
+ ///
+ 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);
+ }
+
+ ///
+ /// 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.
+ ///
+ 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);
+ }
+
+ ///
+ /// 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).
+ ///
+ 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));
+ }
+
+ /// Night content: a star field, or a sequence the deep analysis or GPS phases call night.
+ private bool IsNightSky() => _deep is { } d && (d.Sky.StarField || d.Sky.Light == DayNight.Night);
+
+ /// Speed of moving content as a fraction of the frame's long edge per frame; null without motion data.
+ 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;
+ }
+}
diff --git a/src/Titano.Core/Advisor/AdvisorTypes.cs b/src/Titano.Core/Advisor/AdvisorTypes.cs
new file mode 100644
index 00000000..427dca10
--- /dev/null
+++ b/src/Titano.Core/Advisor/AdvisorTypes.cs
@@ -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;
+
+/// Sequence-editor section a recommendation belongs to (BRIEF §12.3).
+public enum AdvisorSection
+{
+ Frames,
+ Timing,
+ Exposure,
+ Motion,
+ Camera,
+
+ /// No automatic advice: a temporal median erases stars that move between frames, so stacking stays a user choice.
+ Stack,
+
+ Export,
+}
+
+///
+/// Stable ids of the parameters the advisor decides, named after their path.
+/// Value types: see each constant.
+///
+public static class AdvisorParameters
+{
+ /// frame index.
+ public const string Hero = "Frames.Hero";
+
+ /// [] frame indices to exclude.
+ public const string Excluded = "Frames.Excluded";
+
+ /// .
+ public const string TimingMode = "Timing.Mode";
+
+ /// frame rate ("24", "25", "30", "60").
+ public const string FrameRate = "Timing.FrameRate";
+
+ /// seconds.
+ public const string FitToSeconds = "Timing.FitToSeconds";
+
+ /// .
+ public const string Deflicker = "Exposure.Deflicker";
+
+ /// frames (odd).
+ public const string DeflickerWindow = "Exposure.DeflickerWindow";
+
+ /// 0..1.
+ public const string DeflickerStrength = "Exposure.DeflickerStrength";
+
+ /// .
+ public const string Regions = "Exposure.Regions";
+
+ /// .
+ public const string HolyGrail = "Exposure.HolyGrail";
+
+ /// frames.
+ public const string TransitionLength = "Exposure.TransitionLength";
+
+ /// .
+ public const string WhiteBalanceSmoothing = "Exposure.WhiteBalanceSmoothing";
+
+ /// .
+ public const string MotionBlur = "Motion.MotionBlur";
+
+ /// degrees.
+ public const string TargetShutterAngle = "Motion.TargetShutterAngle";
+
+ /// .
+ public const string FlowQuality = "Motion.FlowQuality";
+
+ /// .
+ public const string Stabilize = "Motion.Stabilize";
+
+ /// σ in frames.
+ public const string StabilizeSmoothing = "Motion.StabilizeSmoothing";
+
+ /// aspect ("16:9", "9:16", …).
+ public const string Aspect = "Camera.Aspect";
+
+ /// crop placement −1..1 (0 = centred).
+ public const string OffsetY = "Camera.OffsetY";
+
+ /// built-in export preset id.
+ public const string ExportPreset = "Export.Preset";
+
+ /// output size "WxH" (the cap from source, previews and encoder).
+ public const string Resolution = "Export.Resolution";
+}
+
+///
+/// One advisor decision (BRIEF §10.3). is null when data is missing; the reason then says what is
+/// missing and nothing is changed. are numbers (already rounded for display) or plain tokens,
+/// formatted by the caller with its culture: Loc.L(ReasonKey, [.. ReasonArgs]).
+///
+/// 0..1: how strongly the measurements support the value.
+public sealed record Recommendation(
+ AdvisorSection Section,
+ string Parameter,
+ object? Value,
+ double Confidence,
+ string ReasonKey,
+ IReadOnlyList