feat(editor): visual crop, rotate/mirror/flip/straighten, colour looks (owner review 1 phase 4) (#26)
CI / Build and test (push) Successful in 8m19s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 7s
Release / Build, test and publish (push) Successful in 12m9s
CI / PostgreSQL 16 integration (push) Successful in 7m49s
CI / PostgreSQL 17 integration (push) Successful in 7m19s
CI / Docker image (push) Successful in 46s
Release / Server image (push) Successful in 1m14s

Owner review 1 R5 + R6. Camera rotation, mirror, flip, straighten and crop handles locked to the output; an Exposure Look group; Export output size ("proportions win"); settings format 2 with older-node gates. Also fixes project text and hashes differing between Windows and Linux.

Closes #19
Closes #20

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Alberto Balbo <alberto.balbo.96@gmail.com>
This commit was merged in pull request #26.
This commit is contained in:
Alby96andClaude Opus 5.5 authored and Alby96 committed 2026-11-05 01:09:09 +01:00
1 parent db389a54f2
commit 188b2c2e55
355 files changed
+10549 -1061

No files matched your search

@@ -50,7 +50,8 @@ public sealed record SelfTestOptions
/// </summary>
public static partial class SelfTest
{
public static IReadOnlyList<SelfTestCheck> Checks { get; } = [.. PlanChecks(), .. ExportChecks(), .. CodecChecks(), .. RenderChecks(), .. ProcessingChecks(), .. RobustnessChecks()];
public static IReadOnlyList<SelfTestCheck> Checks { get; } = [.. PlanChecks(), .. ExportChecks(), .. CodecChecks(), .. RenderChecks(), .. ProcessingChecks(), .. GeometryChecks(),
.. ColourChecks(), .. RobustnessChecks()];
public static async Task<IReadOnlyList<SelfTestResult>> RunAsync(SelfTestOptions? options = null, IProgress<SelfTestResult>? progress = null,
CancellationToken cancellationToken = default)
@@ -0,0 +1,37 @@
using Chronos.Core.Imaging;
using Chronos.Core.Project;
namespace Chronos.Core.Render.Diagnostics;
/// <summary>Colour look checks (owner review 1, R6).</summary>
public static partial class SelfTest
{
private static IEnumerable<SelfTestCheck> ColourChecks()
{
yield return Check("proc.look", "The mono look renders grey at the picture's luminance and an unknown look renders nothing", async context =>
{
var source = Synthetic(2);
var plain = await RenderDecodedAsync(context, Input(source), name: "plain").ConfigureAwait(false);
var mono = await RenderDecodedAsync(context, Input(source, Plain with { Look = new LookSettings { Filter = "mono" } }), name: "mono").ConfigureAwait(false);
double grey = 0, luminance = 0;
var compared = 0;
for (var i = 0; i < plain[1].PlaneLength; i++)
{
var (r, g, b) = (mono[1].Plane(0)[i], mono[1].Plane(1)[i], mono[1].Plane(2)[i]);
grey = double.Max(grey, double.Max(double.Abs(r - g), double.Abs(g - b)));
var (pr, pg, pb) = (plain[1].Plane(0)[i], plain[1].Plane(1)[i], plain[1].Plane(2)[i]);
// Clipped highlights lose the luminance the look kept: only values the PNG holds are compared.
if (float.Max(pr, float.Max(pg, pb)) > 0.95f) continue;
luminance = double.Max(luminance, double.Abs(ColorSpace.Luminance(pr, pg, pb) - r));
compared++;
}
DisposeAll(plain);
DisposeAll(mono);
var warnings = new List<RenderWarning>();
var unknown = FrameFinish.Look(new LookSettings { Filter = "technicolor" }, warnings);
Require(grey == 0 && compared > 0 && luminance < 1e-3, Invariant($"mono channel spread {grey:0.######}, luminance error {luminance:0.######} over {compared} pixels"));
Require(unknown is null && warnings.Count == 1 && warnings[0].Key == "Export.Render.LookIgnored", "an unknown look is not ignored with a warning");
return Invariant($"luminance error {luminance:0.######}");
});
}
}
@@ -0,0 +1,67 @@
using Chronos.Core.Imaging;
using Chronos.Core.Imaging.Geometry;
using Chronos.Core.Project;
namespace Chronos.Core.Render.Diagnostics;
/// <summary>Orientation, straighten and output-proportion checks (owner review 1, R5/R6).</summary>
public static partial class SelfTest
{
private static IEnumerable<SelfTestCheck> GeometryChecks()
{
yield return Check("proc.orient", "A quarter turn with a mirror transposes the frame pixel for pixel", async context =>
{
var source = Synthetic(3);
var project = Plain with { Camera = new CameraSettings { Rotate = 90, Mirror = true } };
var frames = await RenderDecodedAsync(context, Input(source, project), Preset("png-sequence", 0, 0)).ConfigureAwait(false);
using var reference = source.Sequence.Render(1);
// A turn right then a mirror is the transpose: view (u, v) shows frame (v, u).
using var expected = new ImageBuffer(reference.Height, reference.Width, reference.Channels, clear: false);
for (var c = 0; c < reference.Channels; c++)
{
for (var v = 0; v < expected.Height; v++)
{
for (var u = 0; u < expected.Width; u++) expected[c, u, v] = reference[c, v, u];
}
}
var size = (frames[1].Width, frames[1].Height);
var psnr = size == (expected.Width, expected.Height) ? Psnr(expected, frames[1]) : 0;
DisposeAll(frames);
Require(size == (64, 96) && psnr > 60, Invariant($"{size}, PSNR {psnr:0.#} dB"));
return "transposed 64×96";
});
yield return Check("proc.straighten", "Straighten turns the view with no border and decodes larger by its cover zoom", async context =>
{
var source = Synthetic(3, o => o with { Width = 480, Height = 320 });
var project = Plain with { Camera = new CameraSettings { Straighten = 10 } };
var frames = await RenderDecodedAsync(context, Input(source, project), Preset("png-sequence", 96, 64)).ConfigureAwait(false);
var orientation = FrameOrientation.Of(project.Camera, 480, 320);
using var full = source.Sequence.Render(1);
var view = new GeometrySettings { OutputWidth = 96, OutputHeight = 64, Warp = orientation.ViewToFrame };
using var expected = GeometryStage.Apply(full, view);
// At full size (no minifying kernel), every pixel of the view is covered by the frame.
using var coverage = GeometryStage.Apply(full, view with { OutputWidth = 480, OutputHeight = 320, Border = BorderMode.Transparent });
var alpha = coverage.Plane(3).ToArray().Min();
var psnr = Psnr(expected, frames[1]);
DisposeAll(frames);
var edge = (int)double.Ceiling(96 * orientation.CoverZoom);
Require(psnr > 28 && alpha >= 1 - 1e-6 && source.LargestRenderRequest == edge,
Invariant($"PSNR {psnr:0.#} dB, coverage {alpha:0.######}, decoded at {source.LargestRenderRequest} px (expected {edge})"));
return Invariant($"PSNR {psnr:0.#} dB, zoom {orientation.CoverZoom:0.###}, decode {edge} px");
});
yield return Check("proc.portrait", "A 9:16 aspect turns a fixed-size preset to portrait (proportions win)", async context =>
{
var source = Synthetic(3);
var project = Plain with { Camera = new CameraSettings { Aspect = Manual("9:16") } };
var frames = await RenderDecodedAsync(context, Input(source, project), Preset("png-sequence", 96, 64)).ConfigureAwait(false);
using var reference = source.Sequence.Render(1);
var crop = AspectRatio.FitCrop(RectD.FromSize(96, 64), 9.0 / 16);
using var expected = GeometryStage.Apply(reference, new GeometrySettings { Crop = crop, OutputWidth = 54, OutputHeight = 96 });
var size = (frames[1].Width, frames[1].Height);
var psnr = size == (54, 96) ? Psnr(expected, frames[1]) : 0;
DisposeAll(frames);
Require(size == (54, 96) && psnr > 60, Invariant($"{size}, PSNR {psnr:0.#} dB"));
return "96×64 box → 54×96";
});
}
}
+61
View File
@@ -0,0 +1,61 @@
using System.Globalization;
using Chronos.Core.Analysis;
using Chronos.Core.Imaging;
using Chronos.Core.Imaging.Color;
using Chronos.Core.Project;
namespace Chronos.Core.Render;
/// <summary>
/// The last pixel step of every output frame (owner review 1, R6), shared by the render, the editor's preview, the server
/// and the render nodes: the colour look (<see cref="LookFilter"/>) and then the highlight knee, in linear light, after
/// stacking, interpolation and motion blur and before the encoder. The knee comes last so it compresses any overshoot the
/// look leaves. Measuring, flow and stacking never see either.
/// </summary>
public static class FrameFinish
{
/// <summary>
/// The knee a render applies: <paramref name="highlightKnee"/> when it lies in (0, 1), else none, with
/// <c>Export.Render.KneeIgnored</c> added to <paramref name="warnings"/> for a value out of range.
/// </summary>
public static double? Knee(double? highlightKnee, ICollection<RenderWarning>? warnings = null)
{
if (highlightKnee is not { } knee) return null;
if (knee is > 0 and < 1) return knee;
warnings?.Add(new RenderWarning("Export.Render.KneeIgnored", knee.ToString(CultureInfo.InvariantCulture)));
return null;
}
/// <summary>
/// The look a render applies: null for none, the identity, or a filter this Chronos does not know, which adds
/// <c>Export.Render.LookIgnored</c> to <paramref name="warnings"/>.
/// </summary>
public static LookSettings? Look(LookSettings? look, ICollection<RenderWarning>? warnings = null)
{
if (look is null || look.IsIdentity) return null;
if (LookFilter.IsKnown(look.Filter)) return look;
warnings?.Add(new RenderWarning("Export.Render.LookIgnored", look.Filter ?? string.Empty));
return null;
}
/// <summary>The share of a look applied: its strength clamped to 0..1, 1 when not given (or not finite).</summary>
public static double Strength(LookSettings look)
{
ArgumentNullException.ThrowIfNull(look);
return look.Strength is { } strength && double.IsFinite(strength) ? double.Clamp(strength, 0, 1) : 1;
}
/// <summary>Neither a look nor a knee would change a frame.</summary>
public static bool IsIdentity(LookSettings? look, double? knee) => (look is null || look.IsIdentity || !LookFilter.IsKnown(look.Filter)) && knee is not (> 0 and < 1);
/// <summary>
/// Finishes a linear-light output <paramref name="frame"/> in place: <paramref name="look"/> (none when null, the
/// identity or unknown), then the soft highlight knee when <paramref name="knee"/> lies in (0, 1).
/// </summary>
public static void Apply(ImageBuffer frame, LookSettings? look, double? knee)
{
ArgumentNullException.ThrowIfNull(frame);
if (look is { IsIdentity: false } && LookFilter.IsKnown(look.Filter)) LookFilter.Apply(frame, look.Filter, Strength(look));
if (knee is > 0 and < 1 and var k) ExposureProcessor.Apply(frame, 0, null, k);
}
}
+137 -44
View File
@@ -3,21 +3,24 @@ using Chronos.Core.Export;
using Chronos.Core.Imaging.Geometry;
using Chronos.Core.Motion;
using Chronos.Core.Project;
using Chronos.Core.Video;
namespace Chronos.Core.Render;
/// <summary>
/// Output size, decode size and per-frame warp of a render. <see cref="CameraSettings.Crop"/> is a normalised
/// [x, y, width, height] rectangle of the camera view; the output aspect is the export's when it fixes both dimensions,
/// otherwise the camera aspect (source = frame aspect). Virtual-camera keyframes are keyed to source frame positions, so
/// they stay attached to the content when timing, frame rate or fitting change. The stabiliser correction, the camera
/// pose (zoomed by the stabilisation zoom) and the crop become one output→source map, resampled once.
/// Output size, decode size and per-frame warp of a render. The decoded frame is turned, mirrored, flipped and
/// straightened into the view frame T (<see cref="FrameOrientation"/>); <see cref="CameraSettings.Crop"/> is a normalised
/// [x, y, width, height] rectangle of T and the keyframe centres are normalised in it. The chosen proportions win
/// (owner review 1, R5): the output ratio is the camera aspect, a fixed-size preset adapting its size to it
/// (<see cref="RenderSize"/>), and "source" keeps the preset's ratio (else the view's). Virtual-camera keyframes are keyed
/// to source frame positions, so they stay attached to the content when timing, frame rate or fitting change. The
/// stabiliser correction, the orientation, the camera pose (zoomed by the stabilisation zoom) and the crop become one
/// output→source map, <c>stab⁻¹ · O⁻¹ · V</c>, resampled once.
/// </summary>
public sealed class RenderGeometry
{
private static readonly CameraState Neutral = new(0.5, 0.5, 1, 0);
private readonly VirtualCamera? _camera;
private readonly FrameOrientation _orientation;
private readonly RectD _crop;
private readonly double _offsetX;
private readonly double _offsetY;
@@ -27,10 +30,13 @@ public sealed class RenderGeometry
private readonly double _maxZoom;
private readonly int _maxWorkingLongEdge;
private RenderGeometry(VirtualCamera? camera, RectD crop, double offsetX, double offsetY, double stabilizationZoom, int sourceWidth, int sourceHeight,
int outputWidth, int outputHeight, double fittedWidth, double fittedHeight, double maxZoom, int maxWorkingLongEdge, IReadOnlyList<RenderWarning> warnings)
private RenderGeometry(VirtualCamera? camera, FrameOrientation orientation, RectD crop, double offsetX, double offsetY, double stabilizationZoom, int sourceWidth, int sourceHeight,
int outputWidth, int outputHeight, double fittedWidth, double fittedHeight, double maxZoom, int maxWorkingLongEdge, IReadOnlyList<RenderWarning> warnings,
double outputRatio)
{
OutputRatio = outputRatio;
_camera = camera;
_orientation = orientation;
_crop = crop;
_offsetX = offsetX;
_offsetY = offsetY;
@@ -51,12 +57,40 @@ public sealed class RenderGeometry
public int OutputWidth { get; }
public int OutputHeight { get; }
/// <summary>
/// Width of the view frame T at full resolution (<see cref="FrameOrientation"/>): the source turned, mirrored and
/// straightened. <see cref="CameraSettings.Crop"/> and the keyframe centres are normalised in it.
/// </summary>
public int ViewWidth => _orientation.ViewWidth;
/// <inheritdoc cref="ViewWidth"/>
public int ViewHeight => _orientation.ViewHeight;
/// <summary>The camera's orientation at full resolution, its values as rendered (<see cref="FrameOrientation.Of(CameraSettings, int, int)"/>).</summary>
public FrameOrientation Orientation => _orientation;
/// <summary>The output ratio (width / height) the crop is fitted to (<see cref="RenderSize.Ratio"/>), before rounding to whole pixels.</summary>
public double OutputRatio { get; }
/// <summary>
/// The crop box's width over its height in normalised view units (<see cref="OutputRatio"/> × <see cref="ViewHeight"/> /
/// <see cref="ViewWidth"/>): the lock ratio of <see cref="CropFrame"/>.
/// </summary>
public double LockRatio => OutputRatio * ViewHeight / ViewWidth;
/// <summary>
/// The crop the editor shows and edits, normalised in the view frame and the same on every frame: the stored crop
/// fitted to the output ratio and placed by the offsets (<see cref="CropFrame.Locked"/>).
/// </summary>
public RectD EditableCrop => AspectRatio.FitCrop(_crop, LockRatio, _offsetX, _offsetY);
/// <summary>Remarks about ignored camera values.</summary>
public IReadOnlyList<RenderWarning> Warnings { get; }
/// <summary>
/// Long edge to decode source frames at: enough that the most zoomed-in view still has one source pixel per output
/// pixel, never more than the source, capped by <see cref="RenderOptions.MaxWorkingLongEdge"/>.
/// Long edge to decode source frames at: enough that the most zoomed-in view (keyframe zoom × stabilisation zoom ×
/// straighten cover zoom) still has one source pixel per output pixel, never more than the source, capped by
/// <see cref="RenderOptions.MaxWorkingLongEdge"/>. Quarter turns do not change the long edge.
/// </summary>
public int WorkingLongEdge
{
@@ -79,47 +113,28 @@ public sealed class RenderGeometry
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(sourceWidth);
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(sourceHeight);
var warnings = new List<RenderWarning>();
var orientation = OrientationOf(camera, sourceWidth, sourceHeight, warnings);
var crop = NormalisedCrop(camera.Crop, warnings);
if (!AspectRatio.TryParse(camera.Aspect.Resolve("source"), out var aspect))
{
if (!AspectRatio.TryParse(camera.Aspect.Resolve("source"), out _))
warnings.Add(new RenderWarning("Export.Render.AspectIgnored", camera.Aspect.Resolve(string.Empty)));
aspect = AspectRatio.Source;
}
var fixedSize = export.Width > 0 && export.Height > 0;
var ratio = fixedSize ? export.Width / (double)export.Height : aspect.Resolve(sourceWidth, sourceHeight);
if (fixedSize && !aspect.IsSource && double.Abs(aspect.Resolve(sourceWidth, sourceHeight) / ratio - 1) > 0.01)
warnings.Add(new RenderWarning("Export.Render.AspectFromPreset", aspect.ToString(), string.Create(CultureInfo.InvariantCulture, $"{export.Width}:{export.Height}")));
var cropPixels = new RectD(crop.X * sourceWidth, crop.Y * sourceHeight, crop.Width * sourceWidth, crop.Height * sourceHeight);
// The chosen proportions win: a fixed-size preset is a box the aspect is fitted in (RenderSize).
var ratio = RenderSize.Ratio(camera, export, sourceWidth, sourceHeight);
var (viewWidth, viewHeight) = (orientation.ViewWidth, orientation.ViewHeight);
var cropPixels = new RectD(crop.X * viewWidth, crop.Y * viewHeight, crop.Width * viewWidth, crop.Height * viewHeight);
var fitted = AspectRatio.FitCrop(cropPixels, ratio, camera.OffsetX, camera.OffsetY);
int width, height;
if (fixedSize) (width, height) = (export.Width, export.Height);
else if (export.Width > 0) (width, height) = (export.Width, (int)double.Round(export.Width / ratio));
else if (export.Height > 0) (width, height) = ((int)double.Round(export.Height * ratio), export.Height);
else
{
var scale = maxWorkingLongEdge > 0 ? double.Min(1, maxWorkingLongEdge / double.Max(fitted.Width, fitted.Height)) : 1;
(width, height) = ((int)double.Round(fitted.Width * scale), (int)double.Round(fitted.Height * scale));
}
if (!VideoCodecInfo.IsManaged(export.Codec))
{
width &= ~1;
height &= ~1;
}
width = int.Max(VideoCodecInfo.IsManaged(export.Codec) ? 1 : 2, width);
height = int.Max(VideoCodecInfo.IsManaged(export.Codec) ? 1 : 2, height);
var (width, height) = RenderSize.Of(camera, export, sourceWidth, sourceHeight, maxWorkingLongEdge);
var cameraPath = Camera(camera.Keyframes, warnings);
var maxZoom = (cameraPath?.Keyframes.Max(k => k.Zoom) ?? 1) * stabilizationZoom;
return new RenderGeometry(cameraPath, crop, camera.OffsetX, camera.OffsetY, stabilizationZoom, sourceWidth, sourceHeight, width, height,
fitted.Width, fitted.Height, maxZoom, maxWorkingLongEdge, warnings);
var maxZoom = (cameraPath?.Keyframes.Max(k => k.Zoom) ?? 1) * stabilizationZoom * orientation.CoverZoom;
return new RenderGeometry(cameraPath, orientation, crop, camera.OffsetX, camera.OffsetY, stabilizationZoom, sourceWidth, sourceHeight, width, height,
fitted.Width, fitted.Height, maxZoom, maxWorkingLongEdge, warnings, ratio);
}
/// <summary>The same geometry rendering into a different output size (e.g. capped by the encoder).</summary>
public RenderGeometry WithOutputSize(int width, int height) => width == OutputWidth && height == OutputHeight
? this
: new RenderGeometry(_camera, _crop, _offsetX, _offsetY, _stabilizationZoom, SourceWidth, SourceHeight, width, height, _fittedWidth, _fittedHeight,
_maxZoom, _maxWorkingLongEdge, Warnings);
: new RenderGeometry(_camera, _orientation, _crop, _offsetX, _offsetY, _stabilizationZoom, SourceWidth, SourceHeight, width, height, _fittedWidth, _fittedHeight,
_maxZoom, _maxWorkingLongEdge, Warnings, OutputRatio);
/// <summary>Camera pose at a (fractional) source position, including the stabilisation zoom.</summary>
public CameraState PoseAt(double sourcePosition)
@@ -128,14 +143,21 @@ public sealed class RenderGeometry
return pose with { Zoom = pose.Zoom * _stabilizationZoom };
}
/// <summary>Geometry of one decoded frame of <paramref name="frameWidth"/>×<paramref name="frameHeight"/> pixels.</summary>
/// <summary>
/// Geometry of one decoded frame of <paramref name="frameWidth"/>×<paramref name="frameHeight"/> pixels: the crop in the
/// view frame, and the warp <c>stab⁻¹ · O⁻¹ · V</c> from the camera view (the pose in the view frame) through the view
/// frame to the stabilised and then the decoded frame.
/// </summary>
/// <param name="stabilization">The frame's stabiliser correction at this frame size (source → stabilised).</param>
public GeometrySettings For(int frameWidth, int frameHeight, double sourcePosition, Affine2D stabilization)
{
var view = VirtualCamera.ViewToSource(PoseAt(sourcePosition), frameWidth, frameHeight);
var orientation = _orientation.Resized(frameWidth, frameHeight);
var (viewWidth, viewHeight) = (orientation.ViewWidth, orientation.ViewHeight);
var view = VirtualCamera.ViewToSource(PoseAt(sourcePosition), viewWidth, viewHeight);
if (!orientation.IsIdentity) view = orientation.ViewToFrame * view;
return new GeometrySettings
{
Crop = new RectD(_crop.X * frameWidth, _crop.Y * frameHeight, _crop.Width * frameWidth, _crop.Height * frameHeight),
Crop = new RectD(_crop.X * viewWidth, _crop.Y * viewHeight, _crop.Width * viewWidth, _crop.Height * viewHeight),
Aspect = AspectRatio.Source,
OffsetX = _offsetX,
OffsetY = _offsetY,
@@ -146,6 +168,77 @@ public sealed class RenderGeometry
};
}
/// <summary>
/// The view frame→decoded frame map (O⁻¹, <see cref="FrameOrientation.ViewToFrame"/>) for a frame of
/// <paramref name="frameWidth"/>×<paramref name="frameHeight"/> pixels, without stabilisation: what maps overlays
/// drawn in frame pixels (the horizon, the region mask) into the view through its inverse.
/// </summary>
public Affine2D ViewToFrame(int frameWidth, int frameHeight)
{
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(frameWidth);
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(frameHeight);
return _orientation.Resized(frameWidth, frameHeight).ViewToFrame;
}
/// <summary>
/// The whole view frame of one decoded frame at <paramref name="outputWidth"/>×<paramref name="outputHeight"/>
/// pixels, without crop, camera pose or stabilisation: the editor's Source framing of an oriented camera.
/// </summary>
public GeometrySettings ViewFor(int frameWidth, int frameHeight, int outputWidth, int outputHeight)
{
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(outputWidth);
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(outputHeight);
var orientation = _orientation.Resized(frameWidth, frameHeight);
return new GeometrySettings
{
Crop = RectD.FromSize(orientation.ViewWidth, orientation.ViewHeight),
Aspect = AspectRatio.Source,
OutputWidth = outputWidth,
OutputHeight = outputHeight,
Warp = orientation.ViewToFrame,
Border = BorderMode.Clamp,
};
}
/// <summary>
/// The footprint of a planned output frame (<see cref="GeometryStage.Plan"/> of <see cref="For"/> on a frame of
/// <paramref name="frameWidth"/>×<paramref name="frameHeight"/>) in the view frame: the bounding box of its warped
/// corners, normalised and clamped to [0,1]²; the whole view without a plan. The Export step's crop mask.
/// </summary>
public RectD FootprintInView(GeometryPlan? plan, int frameWidth, int frameHeight)
{
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(frameWidth);
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(frameHeight);
if (plan is not { } p) return new RectD(0, 0, 1, 1);
var orientation = _orientation.Resized(frameWidth, frameHeight);
var toView = orientation.FrameToView * p.OutputToSource;
double left = double.MaxValue, top = double.MaxValue, right = double.MinValue, bottom = double.MinValue;
foreach (var (u, v) in new[] { (-0.5, -0.5), (p.OutputWidth - 0.5, -0.5), (-0.5, p.OutputHeight - 0.5), (p.OutputWidth - 0.5, p.OutputHeight - 0.5) })
{
var (x, y) = toView.Apply(u, v);
(left, top, right, bottom) = (double.Min(left, x + 0.5), double.Min(top, y + 0.5), double.Max(right, x + 0.5), double.Max(bottom, y + 0.5));
}
var (viewWidth, viewHeight) = (orientation.ViewWidth, orientation.ViewHeight);
left = double.Clamp(left / viewWidth, 0, 1);
top = double.Clamp(top / viewHeight, 0, 1);
return new RectD(left, top, double.Clamp(right / viewWidth, 0, 1) - left, double.Clamp(bottom / viewHeight, 0, 1) - top);
}
/// <summary>
/// The camera's orientation as rendered: a rotation that is not a quarter turn counts as none
/// (<c>Export.Render.RotationIgnored</c>), a straighten beyond ±15° (or not finite) is clamped
/// (<c>Export.Render.StraightenClamped</c>).
/// </summary>
private static FrameOrientation OrientationOf(CameraSettings camera, int sourceWidth, int sourceHeight, List<RenderWarning> warnings)
{
if (!FrameOrientation.IsValidRotate(camera.Rotate))
warnings.Add(new RenderWarning("Export.Render.RotationIgnored", camera.Rotate.ToString(CultureInfo.InvariantCulture)));
if (!FrameOrientation.IsValidStraighten(camera.Straighten))
warnings.Add(new RenderWarning("Export.Render.StraightenClamped", camera.Straighten.ToString(CultureInfo.InvariantCulture),
FrameOrientation.StraightenOf(camera.Straighten).ToString(CultureInfo.InvariantCulture)));
return FrameOrientation.Of(camera, sourceWidth, sourceHeight);
}
private static RectD NormalisedCrop(double[]? crop, List<RenderWarning> warnings)
{
var full = new RectD(0, 0, 1, 1);
+7 -10
View File
@@ -16,7 +16,7 @@ namespace Chronos.Core.Render;
/// <see cref="IRenderFrameSource"/> at the working size; per-frame exposure corrections (deflicker, holy grail, white
/// balance, regions) are applied; stabilisation, virtual camera and crop are resampled once to the output size;
/// fractional positions are synthesised from the bidirectional flow; motion blur follows the flow with shutter-angle
/// composition; stacking (median, mean, star trails) and the highlight knee come last, then the encoder. Encoding of a
/// composition; stacking (median, mean, star trails) and the finish (look, then highlight knee: <see cref="FrameFinish"/>) come last, then the encoder. Encoding of a
/// frame overlaps the processing of the next. Cancellation and failures leave no output behind (sessions delete their
/// partial files on dispose) and every background task is awaited, so exceptions surface exactly once.
/// </summary>
@@ -111,7 +111,8 @@ internal sealed class RenderRun : IDisposable
private readonly List<RenderWarning> _warnings = [];
private readonly Stopwatch _clock = new();
private readonly int _workingEdge;
private readonly float? _knee;
private readonly double? _knee;
private readonly LookSettings? _look;
private readonly double _targetShutter;
private readonly FlowQuality _flowQuality;
private OpticalFlowEngine? _flowEngine;
@@ -131,12 +132,8 @@ internal sealed class RenderRun : IDisposable
_geometry = setup.Geometry;
_prepared = new PreparedFrameCache(int.Max(3, options.CacheFrames));
_workingEdge = _geometry.WorkingLongEdge;
var exposure = input.Project.Exposure;
if (exposure.HighlightKnee is { } knee)
{
if (knee is > 0 and < 1) _knee = (float)knee;
else _warnings.Add(new RenderWarning("Export.Render.KneeIgnored", knee.ToString(CultureInfo.InvariantCulture)));
}
_knee = FrameFinish.Knee(input.Project.Exposure.HighlightKnee, _warnings);
_look = FrameFinish.Look(input.Project.Look, _warnings);
var motion = input.Project.Motion;
_targetShutter = double.Clamp(motion.TargetShutterAngle.Resolve(180.0), 0, 360);
_flowQuality = motion.FlowQuality.Resolve(options.DefaultFlowQuality) switch
@@ -403,14 +400,14 @@ internal sealed class RenderRun : IDisposable
if (ev != 0 || (gains is { } g && g != ChannelGains.Identity)) ExposureProcessor.Apply(frame, ev, gains);
}
/// <summary>Applies the knee and hands the frame to the encoder once the previous frame is encoded; owns <paramref name="frame"/>.</summary>
/// <summary>Finishes the frame (look, then knee) and hands it to the encoder once the previous frame is encoded; owns <paramref name="frame"/>.</summary>
private async Task EmitAsync(ImageBuffer frame, long duration90k)
{
ImageBuffer? preview = null;
try
{
await FlushEncodingAsync().ConfigureAwait(false);
if (_knee is { } knee) ExposureProcessor.Apply(frame, 0, null, knee);
FrameFinish.Apply(frame, _look, _knee);
_done++;
if (_options.PreviewInterval > 0 && (_done - 1) % _options.PreviewInterval == 0) preview = Resampler.Thumbnail(frame, _options.PreviewLongEdge);
}
+32
View File
@@ -0,0 +1,32 @@
using Chronos.Core.Export;
using Chronos.Core.Project;
namespace Chronos.Core.Render;
/// <summary>
/// What a render needs of the program that runs it (owner review 1, phase 4): the settings format a render node or server
/// must read to render a job as this Chronos would. Computed for routing and gating only, never written into the settings.
/// </summary>
public static class RenderRules
{
/// <summary>
/// The settings format a render of <paramref name="settings"/> with <paramref name="export"/> on a source of the given
/// (Exif-oriented) size needs: the format the settings are written in (<see cref="ProjectSettings.WrittenFormat"/>), and
/// at least 2 when the chosen proportions change a fixed-size preset's size (<see cref="RenderSize"/>), which a format-1
/// program would render at the preset's own ratio.
/// </summary>
public static int RequiredFormat(ProjectSettings settings, ResolvedExport export, int sourceWidth, int sourceHeight)
{
ArgumentNullException.ThrowIfNull(settings);
ArgumentNullException.ThrowIfNull(export);
var format = settings.WrittenFormat;
if (export.Width > 0 && export.Height > 0 && sourceWidth > 0 && sourceHeight > 0 && !RenderSize.IsSource(settings.Camera)
&& RenderSize.Of(settings.Camera, export, sourceWidth, sourceHeight) != PresetSize(export))
format = int.Max(format, 2);
return format;
}
/// <summary>A fixed-size preset's size as a format-1 program renders it (even for codecs that are not managed).</summary>
private static (int Width, int Height) PresetSize(ResolvedExport export) =>
RenderSize.Of(new CameraSettings(), export, 1, 1);
}
+96
View File
@@ -0,0 +1,96 @@
using Chronos.Core.Export;
using Chronos.Core.Imaging.Geometry;
using Chronos.Core.Project;
using Chronos.Core.Video;
namespace Chronos.Core.Render;
/// <summary>
/// The output size of a render (owner review 1, R5: "the chosen proportions win"), before the encoder caps it
/// (<see cref="EncoderSelector"/>): one pure function shared by the render (<see cref="RenderGeometry"/>), the editor's
/// Export step and the server's job routing.
/// <list type="table">
/// <item><term>Fixed-size preset, aspect not "source"</term><description>The aspect fitted in the preset's box, the box turned to portrait for a ratio below 1 (<see cref="Adapt"/>): 4K at 9:16 = 2160×3840.</description></item>
/// <item><term>Fixed-size preset, "source"</term><description>The preset's size.</description></item>
/// <item><term>One side given</term><description>The other side from the ratio.</description></item>
/// <item><term>No side given</term><description>The aspect-fitted crop of the view, scaled down to the decode cap.</description></item>
/// </list>
/// Sizes are made even for codecs that are not managed (H.264, HEVC, AV1), and at least 2 (1 for managed codecs).
/// </summary>
public static class RenderSize
{
/// <summary>The output size of <paramref name="export"/> for <paramref name="camera"/> on a source of the given Exif-oriented size.</summary>
/// <param name="maxWorkingLongEdge">Decode-size cap (0 = none); it also caps source-sized outputs, as in <see cref="RenderGeometry.Create"/>.</param>
public static (int Width, int Height) Of(CameraSettings camera, ResolvedExport export, int sourceWidth, int sourceHeight, int maxWorkingLongEdge = 0)
{
ArgumentNullException.ThrowIfNull(camera);
ArgumentNullException.ThrowIfNull(export);
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(sourceWidth);
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(sourceHeight);
var ratio = Ratio(camera, export, sourceWidth, sourceHeight);
int width, height;
if (export.Width > 0 && export.Height > 0) (width, height) = IsSource(camera) ? (export.Width, export.Height) : Adapt(export.Width, export.Height, ratio);
else if (export.Width > 0) (width, height) = (export.Width, (int)double.Round(export.Width / ratio));
else if (export.Height > 0) (width, height) = ((int)double.Round(export.Height * ratio), export.Height);
else
{
var (viewWidth, viewHeight) = ViewSize(camera, sourceWidth, sourceHeight);
var crop = CropFrame.Of(camera.Crop);
var fitted = AspectRatio.FitCrop(new RectD(crop.X * viewWidth, crop.Y * viewHeight, crop.Width * viewWidth, crop.Height * viewHeight), ratio,
camera.OffsetX, camera.OffsetY);
var scale = maxWorkingLongEdge > 0 ? double.Min(1, maxWorkingLongEdge / double.Max(fitted.Width, fitted.Height)) : 1;
(width, height) = ((int)double.Round(fitted.Width * scale), (int)double.Round(fitted.Height * scale));
}
var managed = VideoCodecInfo.IsManaged(export.Codec);
if (!managed)
{
width &= ~1;
height &= ~1;
}
return (int.Max(managed ? 1 : 2, width), int.Max(managed ? 1 : 2, height));
}
/// <summary>
/// The output ratio (width / height) the crop is fitted to: the aspect's, or for "source" (and an aspect that cannot be
/// read) the fixed-size preset's ratio, else the view's (the source turned by <see cref="CameraSettings.Rotate"/>).
/// </summary>
public static double Ratio(CameraSettings camera, ResolvedExport export, int sourceWidth, int sourceHeight)
{
ArgumentNullException.ThrowIfNull(camera);
ArgumentNullException.ThrowIfNull(export);
if (Aspect(camera) is { IsSource: false } aspect) return aspect.Width / (double)aspect.Height;
if (export.Width > 0 && export.Height > 0) return export.Width / (double)export.Height;
var (viewWidth, viewHeight) = ViewSize(camera, sourceWidth, sourceHeight);
return viewWidth / (double)viewHeight;
}
/// <summary>The view frame's size for a source of the given size: swapped for an odd number of quarter turns.</summary>
public static (int Width, int Height) ViewSize(CameraSettings camera, int sourceWidth, int sourceHeight)
{
ArgumentNullException.ThrowIfNull(camera);
return FrameOrientation.TurnsOf(camera.Rotate) % 2 == 1 ? (sourceHeight, sourceWidth) : (sourceWidth, sourceHeight);
}
/// <summary>
/// The largest size of <paramref name="ratio"/> inside the box <paramref name="boxWidth"/>×<paramref name="boxHeight"/>
/// turned to landscape for a ratio of 1 or more and to portrait below 1, rounded to whole pixels: 3840×2160 gives
/// 2160×3840 at 9:16, 2160×2160 at 1:1, 2160×2700 at 4:5 and 3840×1646 at 21:9; 1080×1920 gives 1920×1080 at 16:9.
/// </summary>
public static (int Width, int Height) Adapt(int boxWidth, int boxHeight, double ratio)
{
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(boxWidth);
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(boxHeight);
if (!(ratio > 0) || double.IsInfinity(ratio)) throw new ArgumentOutOfRangeException(nameof(ratio));
var (longEdge, shortEdge) = (int.Max(boxWidth, boxHeight), int.Min(boxWidth, boxHeight));
var (width, height) = ratio < 1 ? (shortEdge, longEdge) : (longEdge, shortEdge);
return width / (double)height > ratio
? (int.Max(1, (int)double.Round(height * ratio)), height)
: (width, int.Max(1, (int)double.Round(width / ratio)));
}
/// <summary>The camera's aspect resolves to "source" (or to text that cannot be read, which renders as source).</summary>
public static bool IsSource(CameraSettings camera) => Aspect(camera) is not { IsSource: false };
private static AspectRatio? Aspect(CameraSettings camera) =>
AspectRatio.TryParse(camera.Aspect.Resolve("source"), out var aspect) ? aspect : null;
}