diff --git a/Inflate/InflateEffect.cs b/Inflate/InflateEffect.cs new file mode 100644 index 0000000..70f1115 --- /dev/null +++ b/Inflate/InflateEffect.cs @@ -0,0 +1,88 @@ +using System.ComponentModel; +using System.ComponentModel.DataAnnotations; +using YukkuriMovieMaker.Commons; +using YukkuriMovieMaker.Controls; +using YukkuriMovieMaker.Exo; +using YukkuriMovieMaker.Player.Video; +using YukkuriMovieMaker.Plugin; +using YukkuriMovieMaker.Plugin.Effects; + +namespace Inflate; + +[PluginDetails(AuthorName = "routersys")] +[VideoEffect(nameof(Texts.Inflate), [VideoEffectCategories.Filtering, VideoEffectCategories.Decoration], [nameof(Texts.TagInflate), nameof(Texts.TagThreeDimensional), nameof(Texts.TagGloss)], IsAviUtlSupported = false, ResourceType = typeof(Texts))] +public sealed class InflateEffect : VideoEffectBase +{ + public override string Label => Texts.Inflate; + + public InflateEffect() + { + InflateTelemetry.EnsureStartedOnce(); + InflateUpdateNotifier.EnsureCheckedOnce(); + } + + [Display(GroupName = nameof(Texts.BasicGroup), Name = nameof(Texts.Amount), Description = nameof(Texts.AmountDescription), Order = 0, ResourceType = typeof(Texts))] + [AnimationSlider("F1", "%", 0, 100)] + public Animation Amount { get; } = new Animation(100, 0, 100); + + [Display(GroupName = nameof(Texts.BasicGroup), Name = nameof(Texts.Height), Description = nameof(Texts.HeightDescription), Order = 1, ResourceType = typeof(Texts))] + [AnimationSlider("F1", "%", 0, 300)] + public Animation Height { get; } = new Animation(100, 0, 300); + + [Display(GroupName = nameof(Texts.BasicGroup), Name = nameof(Texts.Quality), Description = nameof(Texts.QualityDescription), Order = 2, ResourceType = typeof(Texts))] + [EnumComboBox] + public InflateQuality Quality { get => _quality; set => Set(ref _quality, value); } + private InflateQuality _quality = InflateQuality.High; + + [Display(GroupName = nameof(Texts.LightGroup), Name = nameof(Texts.LightDirection), Description = nameof(Texts.LightDirectionDescription), Order = 10, ResourceType = typeof(Texts))] + [AnimationSlider("F1", "°", -180, 180)] + public Animation LightDirection { get; } = new Animation(-45, -180, 180); + + [Display(GroupName = nameof(Texts.LightGroup), Name = nameof(Texts.LightElevation), Description = nameof(Texts.LightElevationDescription), Order = 11, ResourceType = typeof(Texts))] + [AnimationSlider("F1", "°", 0, 90)] + public Animation LightElevation { get; } = new Animation(50, 0, 90); + + [Display(GroupName = nameof(Texts.LightGroup), Name = nameof(Texts.Ambient), Description = nameof(Texts.AmbientDescription), Order = 12, ResourceType = typeof(Texts))] + [AnimationSlider("F1", "%", 0, 100)] + public Animation Ambient { get; } = new Animation(30, 0, 100); + + [Display(GroupName = nameof(Texts.MaterialGroup), Name = nameof(Texts.Specular), Description = nameof(Texts.SpecularDescription), Order = 20, ResourceType = typeof(Texts))] + [AnimationSlider("F1", "%", 0, 200)] + public Animation Specular { get; } = new Animation(80, 0, 200); + + [Display(GroupName = nameof(Texts.MaterialGroup), Name = nameof(Texts.Sharpness), Description = nameof(Texts.SharpnessDescription), Order = 21, ResourceType = typeof(Texts))] + [AnimationSlider("F1", "%", 0, 100)] + public Animation Sharpness { get; } = new Animation(50, 0, 100); + + [Display(GroupName = nameof(Texts.MaterialGroup), Name = nameof(Texts.Reflection), Description = nameof(Texts.ReflectionDescription), Order = 22, ResourceType = typeof(Texts))] + [AnimationSlider("F1", "%", 0, 100)] + public Animation Reflection { get; } = new Animation(30, 0, 100); + + [Display(GroupName = nameof(Texts.MaterialGroup), Name = nameof(Texts.Rim), Description = nameof(Texts.RimDescription), Order = 23, ResourceType = typeof(Texts))] + [AnimationSlider("F1", "%", 0, 100)] + public Animation Rim { get; } = new Animation(20, 0, 100); + + [Display(GroupName = nameof(Texts.MaterialGroup), Name = nameof(Texts.ColorKeep), Description = nameof(Texts.ColorKeepDescription), Order = 24, ResourceType = typeof(Texts))] + [AnimationSlider("F1", "%", 0, 100)] + public Animation ColorKeep { get; } = new Animation(100, 0, 100); + + private IAnimatable[]? _animatables; + + public override IEnumerable CreateExoVideoFilters(int keyFrameIndex, ExoOutputDescription exoOutputDescription) => []; + + public override IVideoEffectProcessor CreateVideoEffect(IGraphicsDevicesAndContext devices) + { + try + { + return new InflateEffectProcessor(devices, this); + } + catch (Exception exception) + { + InflateTelemetry.Report(exception); + throw; + } + } + + protected override IEnumerable GetAnimatables() + => _animatables ??= [Amount, Height, LightDirection, LightElevation, Ambient, Specular, Sharpness, Reflection, Rim, ColorKeep]; +} diff --git a/Inflate/InflateEffectProcessor.cs b/Inflate/InflateEffectProcessor.cs new file mode 100644 index 0000000..3d8b8b5 --- /dev/null +++ b/Inflate/InflateEffectProcessor.cs @@ -0,0 +1,376 @@ +using System.ComponentModel; +using System.Numerics; +using ComputeWeave; +using Vortice.Direct2D1; +using Vortice.Direct2D1.Effects; +using YukkuriMovieMaker.Commons; +using YukkuriMovieMaker.Player.Video; +using YukkuriMovieMaker.Player.Video.Effects; + +namespace Inflate; + +internal sealed class InflateEffectProcessor : VideoEffectProcessorBase +{ + private readonly IGraphicsDevicesAndContext _devices; + private readonly InflateEffect _item; + private ComputeExternalQueueScheduler? _scheduler; + private InflateInteropProvider? _interopProvider; + private ComputeInteropDomain? _interopDomain; + private InflateResourceSet? _resourceSet; + private ExternalTextureLease? _outputLease; + private InflatePipeline? _pipeline; + private InflateCustomEffect? _effect; + private Crop? _outputCrop; + private ID2D1Image? _outputCropOutput; + private AffineTransform2D? _outputTransform; + private ID2D1Image? _outputTransformOutput; + private bool _isFirst = true; + private bool _hasOutput; + private bool _hasOutputOffset; + private bool _hasCropRect; + private bool _hasRenderState; + private Vector2 _outputOffset; + private Vector4 _cropRect; + private float _amount; + private RenderState _renderState; + + public InflateEffectProcessor(IGraphicsDevicesAndContext devices, InflateEffect item) + : base(devices) + { + _devices = devices; + _item = item; + } + + public override DrawDescription Update(EffectDescription effectDescription) + { + try + { + return UpdateCore(effectDescription); + } + catch (Exception exception) + { + InflateTelemetry.Report(exception); + throw; + } + } + + private DrawDescription UpdateCore(EffectDescription effectDescription) + { + if (IsPassThroughEffect || _effect is null || _outputCrop is null || _outputTransform is null || _outputTransformOutput is null || _resourceSet is null || _interopProvider is null || _pipeline is null || input is null) + return effectDescription.DrawDescription; + + var frame = effectDescription.ItemPosition.Frame; + var length = effectDescription.ItemDuration.Frame; + var fps = effectDescription.FPS; + var amount = (float)(_item.Amount.GetValue(frame, length, fps) / 100.0); + var parameters = new InflatePipeline.Parameters( + _item.Quality, + (float)(_item.Height.GetValue(frame, length, fps) / 100.0), + (float)_item.LightDirection.GetValue(frame, length, fps), + (float)_item.LightElevation.GetValue(frame, length, fps), + (float)(_item.Ambient.GetValue(frame, length, fps) / 100.0), + (float)(_item.Specular.GetValue(frame, length, fps) / 100.0), + (float)(_item.Sharpness.GetValue(frame, length, fps) / 100.0), + (float)(_item.Reflection.GetValue(frame, length, fps) / 100.0), + (float)(_item.Rim.GetValue(frame, length, fps) / 100.0), + (float)(_item.ColorKeep.GetValue(frame, length, fps) / 100.0)); + + if (_isFirst || _amount != amount) + _effect.Amount = amount; + _amount = amount; + + if (amount <= 0f) + { + _isFirst = false; + return effectDescription.DrawDescription; + } + + var bounds = _devices.DeviceContext.GetImageLocalBounds(input); + var widthValue = Math.Ceiling((double)bounds.Right - bounds.Left); + var heightValue = Math.Ceiling((double)bounds.Bottom - bounds.Top); + if (!float.IsFinite(bounds.Left) || !float.IsFinite(bounds.Top) || + !InflateSettings.IsSupportedSize(widthValue, heightValue)) + { + _effect.Amount = 0f; + _isFirst = true; + return effectDescription.DrawDescription; + } + var width = (int)widthValue; + var height = (int)heightValue; + + if (!_resourceSet.TryEnsureSource(width, height, out _)) + { + _effect.Amount = 0f; + _isFirst = true; + return effectDescription.DrawDescription; + } + + RenderInput(new Vortice.RawRectF(bounds.Left, bounds.Top, bounds.Left + width, bounds.Top + height)); + + var pipelineParameters = new InflatePipeline.Parameters( + parameters.Quality, + Math.Clamp(parameters.Height, 0f, 3f), + Math.Clamp(parameters.LightAzimuth, -180f, 180f), + Math.Clamp(parameters.LightElevation, 0f, 90f), + Math.Clamp(parameters.Ambient, 0f, 1f), + Math.Clamp(parameters.Specular, 0f, 2f), + Math.Clamp(parameters.Sharpness, 0f, 1f), + Math.Clamp(parameters.Reflection, 0f, 1f), + Math.Clamp(parameters.Rim, 0f, 1f), + Math.Clamp(parameters.ColorKeep, 0f, 1f)); + + var simulation = _pipeline.Simulate( + _resourceSet.GetSourceComputeBinding(), + width, + height, + in pipelineParameters); + + if (!OutputCovers(width, height)) + _outputCrop.SetInput(0, null, true); + if (!EnsureOutput(width, height, out var outputChanged)) + { + _effect.Amount = 0f; + _isFirst = true; + _hasOutput = false; + _hasRenderState = false; + return effectDescription.DrawDescription; + } + + var renderState = new RenderState(pipelineParameters, simulation.Content, width, height); + if (simulation.StructureChanged || outputChanged || !_hasOutput || !_hasRenderState || simulation.Content is null || _renderState != renderState) + { + _pipeline.Render( + _resourceSet.GetSourceComputeBinding(), + _resourceSet.GetOutputComputeBinding(), + width, + height, + in pipelineParameters); + _renderState = renderState; + _hasRenderState = true; + } + + _outputLease ??= _resourceSet.AcquireOutputExternalViewLease(); + + if (outputChanged || !_hasOutput) + { + using var outputBitmap = new ID2D1Bitmap1(_outputLease.DangerousGetView().AddRefBitmap()); + _outputCrop.SetInput(0, outputBitmap, true); + _effect.SetInput(1, _outputTransformOutput, true); + } + var cropRect = new Vector4(0f, 0f, width, height); + if (!_hasCropRect || _cropRect != cropRect) + { + _outputCrop.Rectangle = cropRect; + _cropRect = cropRect; + _hasCropRect = true; + } + var outputOffset = new Vector2(bounds.Left, bounds.Top); + if (!_hasOutputOffset || _outputOffset != outputOffset) + { + _outputTransform.TransformMatrix = Matrix3x2.CreateTranslation(outputOffset); + _outputOffset = outputOffset; + _hasOutputOffset = true; + } + _hasOutput = true; + _isFirst = false; + return effectDescription.DrawDescription; + } + + private bool OutputCovers(int width, int height) + => _outputLease is { IsDisposed: false } lease && + lease.Width >= width && + lease.Height >= height; + + private bool EnsureOutput(int width, int height, out bool changed) + { + changed = false; + if (OutputCovers(width, height)) + return true; + + _outputLease?.Dispose(); + _outputLease = null; + return _resourceSet!.TryEnsureOutput(width, height, out changed); + } + + private void RenderInput(Vortice.RawRectF bounds) + { + var renderContext = _interopProvider!.RenderContext; + using var borrow = _resourceSet!.BeginSourceExternalOperation(); + var previousTarget = renderContext.Target; + using var sourceBitmap = new ID2D1Bitmap1(borrow.DangerousGetView().AddRefBitmap()); + renderContext.Target = sourceBitmap; + renderContext.BeginDraw(); + renderContext.Clear(null); + renderContext.DrawImage( + input, + new Vector2(-bounds.Left, -bounds.Top), + null, + InterpolationMode.NearestNeighbor, + CompositeMode.SourceCopy); + renderContext.EndDraw(); + renderContext.Target = previousTarget; + } + + private void ReleaseInterop() + { + _outputLease?.Dispose(); + _outputLease = null; + _pipeline?.Dispose(); + _pipeline = null; + _resourceSet?.Dispose(); + _resourceSet?.WaitForDisposal(); + _resourceSet = null; + _interopDomain?.Dispose(); + _interopDomain?.WaitForDisposal(); + _interopDomain = null; + _interopProvider?.Dispose(); + _interopProvider = null; + _scheduler?.Dispose(); + _scheduler = null; + } + + protected override ID2D1Image? CreateEffect(IGraphicsDevicesAndContext devices) + { + var scheduler = ComputeExternalQueueScheduler.Create(); + var interopProvider = InflateInteropProvider.TryCreate(devices, scheduler, out var interopDevice); + if (interopProvider is null || interopDevice is null) + { + scheduler.Dispose(); + return null; + } + + _scheduler = scheduler; + + try + { + _interopProvider = interopProvider; + _interopDomain = interopDevice.RegisterExternalDomain(interopProvider); + _resourceSet = InflateResourceSet.Create(interopDevice, _interopDomain); + _pipeline = InflatePipeline.TryCreate(interopDevice); + } + catch (Win32Exception) + { + ReleaseInterop(); + return null; + } + catch + { + ReleaseInterop(); + throw; + } + + if (_pipeline is null) + { + ReleaseInterop(); + return null; + } + + InflateCustomEffect? effect = null; + Crop? outputCrop = null; + ID2D1Image? outputCropOutput = null; + AffineTransform2D? outputTransform = null; + ID2D1Image? outputTransformOutput = null; + ID2D1Image? output = null; + try + { + effect = new InflateCustomEffect(devices); + if (!effect.IsEnabled) + { + effect.Dispose(); + ReleaseInterop(); + return null; + } + outputCrop = new Crop(devices.DeviceContext); + outputCropOutput = outputCrop.Output; + outputTransform = new AffineTransform2D(devices.DeviceContext) + { + BorderMode = BorderMode.Hard, + }; + outputTransform.SetInput(0, outputCropOutput, true); + outputTransformOutput = outputTransform.Output; + output = effect.Output; + _effect = effect; + _outputCrop = outputCrop; + _outputCropOutput = outputCropOutput; + _outputTransform = outputTransform; + _outputTransformOutput = outputTransformOutput; + disposer.Collect(effect); + disposer.Collect(outputCrop); + disposer.Collect(outputCropOutput); + disposer.Collect(outputTransform); + disposer.Collect(outputTransformOutput); + disposer.Collect(output); + return output; + } + catch + { + output?.Dispose(); + outputTransformOutput?.Dispose(); + outputTransform?.Dispose(); + outputCropOutput?.Dispose(); + outputCrop?.Dispose(); + effect?.Dispose(); + ReleaseInterop(); + throw; + } + } + + protected override void setInput(ID2D1Image? inputImage) + { + try + { + SetInputCore(inputImage); + } + catch (Exception exception) + { + InflateTelemetry.Report(exception); + throw; + } + } + + private void SetInputCore(ID2D1Image? inputImage) + { + _effect?.SetInput(0, inputImage, true); + if (!_hasOutput) + _effect?.SetInput(1, inputImage, true); + } + + protected override void ClearEffectChain() + { + _effect?.SetInput(0, null, true); + _effect?.SetInput(1, null, true); + _outputCrop?.SetInput(0, null, true); + _isFirst = true; + _hasOutput = false; + _hasOutputOffset = false; + _hasCropRect = false; + _hasRenderState = false; + } + + protected override void Dispose(bool disposing) + { + try + { + if (disposing) + { + ClearEffectChain(); + ReleaseInterop(); + } + } + catch (Exception exception) + { + InflateTelemetry.Report(exception); + throw; + } + finally + { + base.Dispose(disposing); + } + } + + private readonly record struct RenderState( + InflatePipeline.Parameters Parameters, + InflatePipeline.ContentHash? Content, + int Width, + int Height); +}