ファイル
YMM4-LuaScript/LuaScript/Effects/LuaScriptEffectProcessor.cs
T

1399 行
55 KiB
C#

using System.Collections.Immutable;
using System.IO;
using System.Numerics;
using System.Runtime.InteropServices;
using LuaScript.Anchor;
using LuaScript.Compat;
using LuaScript.Diagnostics;
using LuaScript.Engine;
using LuaScript.Engine.Kernel;
using LuaScript.Engine.Processing;
using LuaScript.Engine.Shader;
using Vortice;
using Vortice.DCommon;
using Vortice.Direct2D1;
using Vortice.Direct2D1.Effects;
using Vortice.DXGI;
using Vortice.Mathematics;
using YukkuriMovieMaker.Commons;
using YukkuriMovieMaker.Player.Video;
using YukkuriMovieMaker.Player.Video.Effects;
using YukkuriMovieMaker.Project;
using YukkuriMovieMaker.Project.Items;
namespace LuaScript
{
internal sealed class LuaScriptEffectProcessor(IGraphicsDevicesAndContext devices, LuaScriptEffect item) : VideoEffectProcessorBase(devices)
{
private readonly record struct RenderKey(
int Frame,
double Time,
int Length,
int Fps,
double Track0,
double Track1,
double Track2,
double Track3,
double Slider0,
double Slider1,
double Slider2,
double Slider3,
bool Check0,
bool Check1,
bool Check2,
bool Check3,
bool HasColor,
int Color,
int ScriptVersion,
int StringsVersion,
TimelineSourceUsage Usage,
Guid SceneId,
int TimelineFrame,
double TimelineTime,
int SceneWidth,
int SceneHeight,
int Layer,
int InputIndex,
int InputCount,
int GroupIndex,
int GroupCount,
int TimelineTotalFrame,
double TimelineTotalTime,
double Bpm,
int BpmBeat,
double BpmOffset,
int AnchorVersion,
DrawDescription InputDesc
);
private const int NativeTimeoutMilliseconds = 5000;
private static string PluginDirectory =>
Path.GetDirectoryName(typeof(LuaScriptEffectProcessor).Assembly.Location) ?? AppContext.BaseDirectory;
private static string NativeDirectory => Path.Combine(PluginDirectory, "native");
private static readonly string s_scriptPath = PluginDirectory + Path.DirectorySeparatorChar;
private static readonly double s_hostVersion = EncodeVersion(AppVersion.Current);
private static double EncodeVersion(Version version) =>
version.Major * 10000 + version.Minor * 100 + Math.Max(0, version.Build);
private readonly LuaScriptEngine _engine = new(static () => new MediaSourceLoader());
private readonly SemaphoreSlim _pixelLoaderSemaphore = new(1, 1);
private AviUtlScriptContext _context = new();
private LuaJitWorker? _nativeWorker;
private double[]? _nativeFields;
private bool _nativeWarned;
private bool _effectChainWarned;
private bool _gpuWarned;
private string? _scriptKeyRef;
private int _scriptKeyVersion;
private string _kernelSource = string.Empty;
private bool _kernelResolved;
private KernelProgram? _kernelProgram;
private CpuKernel? _cpuKernel;
private GpuKernel? _gpuKernel;
private bool _gpuKernelChecked;
private double[]? _kernelUniforms;
private EffectDescription? _frameDesc;
private SceneObjectResolver? _frameResolver;
private bool _frameResolverBuilt;
private Guid _lastSceneGuid;
private string _lastSceneId = string.Empty;
private bool _sceneIdCached;
private IGraphicsDevicesAndContext? _hostDevices;
private GraphicsDevicesAndContext? _ownCtx;
private PixelBufferManager? _pixelManager;
private RawRectF _pixelBounds;
private int _pixelWidth;
private int _pixelHeight;
private Func<byte[]>? _pixelLoader;
private string _directiveSource = string.Empty;
private bool _directiveCached;
private ScriptEngineKind _autoKind;
private bool _hasExplicitDirective;
private ScriptEngineKind _explicitDirectiveKind;
private PixelRegionAccess? _nativeUpload;
private PixelRegionAccess? _nativeReadIntoResult;
private PixelRegionAccess? _nativeWriteOutput;
private byte[]? _nativeResultBuffer;
private int _nativeReadLength;
private int _nativeOutputWidth;
private int _nativeOutputHeight;
private bool _nativeUploaded;
private Func<string, int, SceneObjectInfo?>? _nativeResolveObject;
private Func<string, int, double, double, double, (byte[] buffer, int w, int h)>? _nativeLoadFigure;
private Func<string, string, double, bool, bool, int, (byte[] buffer, int w, int h)>? _nativeLoadText;
private Func<string, (byte[] buffer, int w, int h)>? _nativeLoadImage;
private Func<string, double, (byte[] buffer, int w, int h)>? _nativeLoadMovie;
private Func<string, double, (byte[] Buffer, int Width, int Height)>? _loadSceneImage;
private Func<string, double, double, IReadOnlyList<KeyValuePair<string, object>>, (byte[] Buffer, int Width, int Height)>? _loadBrushImage;
private SceneImageRenderer? _sceneImageRenderer;
private BrushImageRenderer? _brushImageRenderer;
private bool _sceneImageLoaded;
private Func<string, string, int, (int Count, int Rate, double[] Data)>? _loadAudio;
private AudioSampleProvider? _audioProvider;
private bool _audioLoaded;
private Action<string, IReadOnlyList<KeyValuePair<string, object>>>? _nativeAddEffect;
private Action<DrawCommand>? _nativeAddDraw;
private Action<string, int, bool, int, double[]>? _nativeSetAnchor;
private Func<string, SceneValue>? _nativeSceneGet;
private Action<string, SceneValue>? _nativeSceneSet;
private PixelShaderInvoke? _nativeRunPixelShader;
private bool _isFirst = true;
private string _sourceScript = string.Empty;
private string _runnableScript = string.Empty;
private int[] _runnableLineMap = [];
private int[] _runnableChangedLines = [];
private bool _runnableCached;
private ID2D1Image? _cachedInput;
private RenderKey _cachedKey;
private SceneObjectQuery[] _cachedQueries = [];
private SceneValueQuery[] _cachedSceneValueQueries = [];
private DrawDescription? _cachedOutputDesc;
private ID2D1Image? _cachedEffectOutput;
private PixelShaderRunner? _pixelShaderRunner;
private GpuPixelBufferProcessor? _pixelProcessor;
private AviUtlPixelShaderLibrary _pixelShaderLibrary = AviUtlPixelShaderLibrary.Empty;
private string? _pixelShaderSourceRef;
private VideoEffectChain? _effectChain;
private DrawCompositor? _drawCompositor;
private FallbackCompositor? _bufferCompositor;
private TextRenderer? _nativeTextRenderer;
private ImageDecoder? _nativeImageDecoder;
private MovieDecoder? _nativeMovieDecoder;
protected override ID2D1Image? CreateEffect(IGraphicsDevicesAndContext devices)
{
_hostDevices = devices;
_ownCtx = new GraphicsDevicesAndContext(devices);
disposer.Collect(_ownCtx);
_pixelManager = new PixelBufferManager(_ownCtx);
_bufferCompositor = new FallbackCompositor(
new SynchronizedCompositor(new HardwareCompositor(_ownCtx), _pixelLoaderSemaphore),
SoftwareCompositor.Instance,
WarnBufferCompositorDegraded);
_pixelShaderRunner = new PixelShaderRunner { Compositor = _bufferCompositor, Logger = WriteGpuLog };
_pixelProcessor = new GpuPixelBufferProcessor(_pixelShaderRunner);
_context.ResolverProvider = GetFrameResolver;
_context.Compositor = _bufferCompositor;
_context.PixelProcessor = _pixelProcessor;
_context.SceneImageLoader = _loadSceneImage ??= LoadSceneImage;
_context.BrushImageLoader = _loadBrushImage ??= LoadBrushImage;
_context.AudioLoader = _loadAudio ??= LoadAudio;
return null;
}
private static void WarnBufferCompositorDegraded(Exception ex) =>
Log.Default.Write("LuaScript: hardware buffer compositing failed; falling back to the software compositor.", ex);
private static void WriteGpuLog(string message, Exception? exception)
{
if (exception is null)
Log.Default.Write(message);
else
Log.Default.Write(message, exception);
}
private AviUtlScriptContext CreateScriptContext()
{
var context = new AviUtlScriptContext { ResolverProvider = GetFrameResolver };
if (_bufferCompositor is not null)
context.Compositor = _bufferCompositor;
if (_pixelProcessor is not null)
context.PixelProcessor = _pixelProcessor;
context.SceneImageLoader = _loadSceneImage ??= LoadSceneImage;
context.BrushImageLoader = _loadBrushImage ??= LoadBrushImage;
context.AudioLoader = _loadAudio ??= LoadAudio;
return context;
}
private SceneObjectResolver GetFrameResolver()
{
if (!_frameResolverBuilt)
{
_frameResolver = BuildSceneObjectResolver(_frameDesc!);
_frameResolverBuilt = true;
}
return _frameResolver!;
}
private string ResolveSceneId(Guid sceneId)
{
if (!_sceneIdCached || sceneId != _lastSceneGuid)
{
_lastSceneId = sceneId.ToString();
_lastSceneGuid = sceneId;
_sceneIdCached = true;
}
return _lastSceneId;
}
private string GetRunnableScript(string source)
{
if (_runnableCached && ReferenceEquals(source, _sourceScript))
return _runnableScript;
var (code, lineMap, changedLines) = AviUtlScript.TransformWithMap(source);
_runnableScript = code;
_runnableLineMap = lineMap;
_runnableChangedLines = changedLines;
_sourceScript = source;
_runnableCached = true;
return _runnableScript;
}
private AviUtlPixelShaderLibrary GetPixelShaderLibrary(string source)
{
if (!ReferenceEquals(_pixelShaderSourceRef, source))
{
_pixelShaderLibrary = AviUtlPixelShaderLibrary.Parse(source);
_pixelShaderSourceRef = source;
_pixelShaderRunner?.Invalidate();
}
return _pixelShaderLibrary;
}
private static LuaScriptDiagnosticKind ClassifyDiagnostic(LuaScriptException exception) => exception switch
{
LuaScriptCompilationException => LuaScriptDiagnosticKind.Compile,
LuaScriptTimeoutException => LuaScriptDiagnosticKind.Timeout,
_ => LuaScriptDiagnosticKind.Runtime,
};
private LuaScriptDiagnostic CreateDiagnostic(LuaScriptDiagnosticKind kind, string message)
{
var diagnostic = LuaScriptDiagnosticParser.Parse(kind, message);
if (diagnostic.Line <= 0)
return diagnostic;
if (IsRunnableLineRewritten(diagnostic.Line))
diagnostic = diagnostic with { Column = 0, Length = 0 };
return diagnostic with { Line = MapRunnableLine(diagnostic.Line) };
}
private bool IsRunnableLineRewritten(int runnableLine)
=> _runnableChangedLines.Length != 0
&& Array.BinarySearch(_runnableChangedLines, runnableLine) >= 0;
private int MapRunnableLine(int runnableLine)
{
int index = runnableLine - 1;
if (index < 0 || index >= _runnableLineMap.Length)
return runnableLine;
int sourceLine = _runnableLineMap[index];
return sourceLine >= 0 ? sourceLine + 1 : 0;
}
protected override void setInput(ID2D1Image? input)
{
if (!ReferenceEquals(_cachedInput, input))
_isFirst = true;
_cachedInput = input;
}
protected override void ClearEffectChain()
{
effectOutput = null;
}
public override DrawDescription Update(EffectDescription desc)
{
if (input is null || _ownCtx is null)
return desc.DrawDescription;
var frame = desc.ItemPosition.Frame;
var length = desc.ItemDuration.Frame;
var fps = desc.FPS;
var time = desc.ItemPosition.Time.TotalSeconds;
var script = item.Script ?? string.Empty;
if (!ReferenceEquals(script, _scriptKeyRef))
{
_scriptKeyRef = script;
_scriptKeyVersion++;
}
var layout = item.Layout;
var t0 = ClampTrack(item.Track0.GetValue(frame, length, fps), layout, 0);
var t1 = ClampTrack(item.Track1.GetValue(frame, length, fps), layout, 1);
var t2 = ClampTrack(item.Track2.GetValue(frame, length, fps), layout, 2);
var t3 = ClampTrack(item.Track3.GetValue(frame, length, fps), layout, 3);
bool c0 = item.Check0, c1 = item.Check1, c2 = item.Check2, c3 = item.Check3;
double s0 = item.Slider0, s1 = item.Slider1, s2 = item.Slider2, s3 = item.Slider3;
bool hasColor = item.IsColorVisible;
int colorRgb = hasColor ? (item.Color.R << 16) | (item.Color.G << 8) | item.Color.B : 0;
var inDesc = desc.DrawDescription;
var (bpm, bpmBeat, bpmOffset) = ResolveBpm(desc);
var key = new RenderKey(
frame, time, length, fps,
t0, t1, t2, t3,
s0, s1, s2, s3,
c0, c1, c2, c3, hasColor, colorRgb,
_scriptKeyVersion, RefreshStringParameters(),
desc.Usage, desc.SceneId,
desc.TimelinePosition.Frame,
desc.TimelinePosition.Time.TotalSeconds,
desc.ScreenSize.Width, desc.ScreenSize.Height,
desc.Layer, desc.InputIndex, desc.InputCount,
desc.GroupIndex, desc.GroupCount,
desc.TimelineDuration.Frame,
desc.TimelineDuration.Time.TotalSeconds,
bpm, bpmBeat, bpmOffset,
item.AnchorVersion,
inDesc);
_frameDesc = desc;
_frameResolver = null;
_frameResolverBuilt = false;
if (!_isFirst && key == _cachedKey &&
(_cachedQueries.Length == 0 || QueriesMatch(_cachedQueries, GetFrameResolver())) &&
(_cachedSceneValueQueries.Length == 0 || SceneValuesMatch(
_cachedSceneValueQueries,
SceneSharedValues.ForScene(_hostDevices!, ResolveSceneId(key.SceneId)),
key.TimelineFrame)))
{
effectOutput = _cachedEffectOutput;
return _cachedOutputDesc ?? inDesc;
}
var bounds = _ownCtx.DeviceContext.GetImageLocalBounds(input);
int imgW = Math.Max(1, (int)Math.Ceiling(bounds.Right - bounds.Left));
int imgH = Math.Max(1, (int)Math.Ceiling(bounds.Bottom - bounds.Top));
var ctx = _context;
PopulateContext(ctx, in key, imgW, imgH);
_pixelBounds = bounds;
_pixelWidth = imgW;
_pixelHeight = imgH;
ctx.SetPixelLoader(_pixelLoader ??= LoadPendingInputPixels);
ctx.ShaderRunner = _pixelShaderRunner;
ctx.PixelShaders = GetPixelShaderLibrary(script);
DrawDescription outDesc = inDesc;
IReadOnlyList<LuaScriptDiagnostic> diagnostics = [];
try
{
string runnable = GetRunnableScript(script);
EnsureKernel(runnable);
EnsureDirective(runnable);
if (ExecuteKernelLane(ctx, bounds, imgW, imgH))
{
outDesc = inDesc;
}
else
{
bool wantNative = _autoKind == ScriptEngineKind.Native;
bool nativeReady = wantNative && LuaJitWorker.IsAvailable(NativeDirectory);
if (wantNative && !nativeReady)
WarnNativeUnavailableOnce();
if (nativeReady)
{
ExecuteNative(runnable, ctx, bounds, imgW, imgH);
}
else
{
_engine.Execute(runnable, ctx);
if (ctx.IsPixelsDirty)
{
int bufW = ctx.ImageWidth;
int bufH = ctx.ImageHeight;
_pixelManager!.WritePixelsToOutput(ctx.GetPixelBuffer()!, bufW, bufH);
if (ctx.BufferReplaced)
effectOutput = _pixelManager.GetTransformOutput(-bufW / 2f, -bufH / 2f);
else
effectOutput = _pixelManager.GetTransformOutput(bounds.Left, bounds.Top);
}
else
{
effectOutput = null;
}
}
ctx.PublishSceneValues();
if (ctx.DrawCommands.Count > 0)
{
ctx.EnsurePixelBuffer();
var drawBuffer = ctx.GetPixelBuffer();
if (drawBuffer is not null)
{
_drawCompositor ??= new DrawCompositor(_ownCtx);
effectOutput = _drawCompositor.Compose(drawBuffer, ctx.ImageWidth, ctx.ImageHeight, ctx.DrawCommands);
}
}
ApplyDrawState(ctx, bounds);
outDesc = BuildOutputDesc(inDesc, ctx);
if (ctx.EffectRequests.Count > 0)
{
var source = effectOutput ?? input;
try
{
effectOutput = ApplyEffectChain(source, ctx.EffectRequests, desc, ref outDesc);
}
catch (Exception ex)
{
effectOutput = source;
WarnEffectChainFailureOnce(ex);
}
}
outDesc = AddAnchorControllers(outDesc, ctx);
}
}
catch (LuaScriptTimeoutException ex)
{
effectOutput = null;
_context = CreateScriptContext();
_isFirst = true;
DebugOutput.Write(ex.Message);
Log.Default.Write(ex.Message, ex);
LuaScriptDiagnostics.Instance.Report(script, [CreateDiagnostic(LuaScriptDiagnosticKind.Timeout, ex.Message)]);
return inDesc;
}
catch (LuaScriptException ex)
{
effectOutput = null;
outDesc = inDesc;
DebugOutput.Write(ex.Message);
Log.Default.Write(ex.Message, ex);
diagnostics = [CreateDiagnostic(ClassifyDiagnostic(ex), ex.Message)];
}
finally
{
_pixelLoaderSemaphore.Wait();
_pixelLoaderSemaphore.Release();
}
LuaScriptDiagnostics.Instance.Report(script, diagnostics);
_isFirst = false;
if (_sceneImageLoaded)
{
_sceneImageLoaded = false;
_isFirst = true;
}
if (_audioLoaded)
{
_audioLoaded = false;
_isFirst = true;
}
_cachedKey = key;
_cachedQueries = SnapshotQueries(ctx.ObjectQueries, _cachedQueries);
_cachedSceneValueQueries = SnapshotQueries(ctx.SceneValueQueries, _cachedSceneValueQueries);
_cachedOutputDesc = outDesc;
_cachedEffectOutput = effectOutput;
return outDesc;
}
private string? _effectTargetSource;
private AviUtlEngine _effectTarget;
private AviUtlEngine ResolveEffectTarget(string? script)
{
if (!ReferenceEquals(_effectTargetSource, script) || _effectTargetSource is null)
{
_effectTarget = AviUtlCompatMap.ResolveTarget(script);
_effectTargetSource = script;
}
return _effectTarget;
}
private ID2D1Image ApplyEffectChain(ID2D1Image source, IReadOnlyList<AviUtlEffectRequest> requests, EffectDescription desc, ref DrawDescription drawDescription)
{
_effectChain ??= new VideoEffectChain(_ownCtx!);
return _effectChain.Apply(source, requests, desc, ResolveEffectTarget(item.Script), ref drawDescription);
}
private static (double Bpm, int Beat, double Offset) ResolveBpm(EffectDescription desc)
{
var scenes = desc.Scenes;
if (scenes is not null)
{
foreach (var info in scenes)
{
if (info is Scene scene && scene.ID == desc.SceneId)
{
var line = scene.Timeline.VerticalLine;
double tempo = line.Line is VerticalBPMLine bpm ? bpm.BPM : 0d;
double offset = desc.FPS > 0 ? line.StartFrame / (double)desc.FPS : 0d;
return (tempo, line.Group, offset);
}
}
}
return (0d, 0, 0d);
}
private static SceneObjectResolver BuildSceneObjectResolver(EffectDescription desc)
{
var scenes = desc.Scenes;
if (scenes is null)
return new SceneObjectResolver([], desc.FPS);
Scene? scene = null;
foreach (var info in scenes)
{
if (info is Scene candidate && candidate.ID == desc.SceneId)
{
scene = candidate;
break;
}
}
if (scene is null)
return new SceneObjectResolver([], desc.FPS);
var items = scene.Timeline.Items;
var entries = new List<SceneObjectResolver.Entry>(items.Count);
foreach (var item in items)
{
if (item is not IVideoItem video)
continue;
var tag = item.Remark;
if (string.IsNullOrEmpty(tag))
continue;
var (character, text, kind, volume) = ExtractItemMetadata(item);
entries.Add(new SceneObjectResolver.Entry(tag, item.Frame, item.Length, item.Layer, video, volume, character, text, kind));
}
return new SceneObjectResolver([.. entries], desc.FPS);
}
private static (string Character, string Text, string Kind, Animation? Volume) ExtractItemMetadata(IItem item)
{
string character = string.Empty;
string text = string.Empty;
string kind = string.Empty;
Animation? volume = null;
try
{
kind = item.GetType().Name;
switch (item)
{
case VoiceItem voice:
character = voice.CharacterName ?? string.Empty;
text = voice.Serif ?? string.Empty;
volume = voice.Volume;
break;
case TextItem textItem:
text = textItem.Text ?? string.Empty;
break;
}
}
catch
{
character = string.Empty;
text = string.Empty;
volume = null;
}
return (character, text, kind, volume);
}
private static bool SceneValuesMatch(SceneValueQuery[] queries, SceneSharedValues values, long generation)
{
for (int i = 0; i < queries.Length; i++)
{
if (values.Read(generation, queries[i].Name) != queries[i].Result)
return false;
}
return true;
}
private static T[] SnapshotQueries<T>(IReadOnlyList<T> source, T[] existing)
{
int count = source.Count;
if (count == 0)
return [];
var target = existing.Length == count ? existing : new T[count];
for (int i = 0; i < count; i++)
target[i] = source[i];
return target;
}
private static bool QueriesMatch(SceneObjectQuery[] queries, SceneObjectResolver resolver)
{
for (int i = 0; i < queries.Length; i++)
{
var query = queries[i];
SceneObjectInfo? current = resolver.TryResolve(query.Tag, query.Frame, out var info) ? info : null;
if (!Nullable.Equals(current, query.Result))
return false;
}
return true;
}
private static readonly string[] s_stringParameterNames =
[
"text", "font", "dir",
"file_video", "file_audio", "file_image", "file_project",
"file_mp4", "file_exo", "file_subtitle", "file_shader",
];
private readonly string?[] _stringParameterValues = new string?[s_stringParameterNames.Length];
private int _stringParametersVersion;
private int RefreshStringParameters()
{
var values = _stringParameterValues;
bool changed = false;
changed |= UpdateStringSlot(values, 0, item.Text);
changed |= UpdateStringSlot(values, 1, item.Font);
changed |= UpdateStringSlot(values, 2, item.Directory);
changed |= UpdateStringSlot(values, 3, item.FileVideo);
changed |= UpdateStringSlot(values, 4, item.FileAudio);
changed |= UpdateStringSlot(values, 5, item.FileImage);
changed |= UpdateStringSlot(values, 6, item.FileProject);
changed |= UpdateStringSlot(values, 7, item.FileMp4);
changed |= UpdateStringSlot(values, 8, item.FileExo);
changed |= UpdateStringSlot(values, 9, item.FileSubtitle);
changed |= UpdateStringSlot(values, 10, item.FileShader);
if (changed)
_stringParametersVersion++;
return _stringParametersVersion;
}
private static bool UpdateStringSlot(string?[] values, int index, string value)
{
if (ReferenceEquals(values[index], value))
return false;
values[index] = value;
return true;
}
private void PopulateStringParameters(AviUtlScriptContext ctx)
{
var names = s_stringParameterNames;
var values = _stringParameterValues;
for (int i = 0; i < names.Length; i++)
ctx.SetStringParameter(names[i], values[i]);
}
private void PopulateContext(AviUtlScriptContext ctx, in RenderKey key, int imgW, int imgH)
{
var zoom = key.InputDesc.Zoom;
double zoomAvg = (zoom.X + zoom.Y) / 2d;
double aspect = zoomAvg > 0d
? (zoom.X - zoom.Y) / (zoom.X + zoom.Y)
: 0d;
ctx.ClearQueries();
ctx.ClearEffects();
ctx.ClearDraws();
ctx.ClearAnchorRequests();
ctx.AnchorSource = item.Anchors;
ctx.DrawStateOverride = null;
ctx.ResetDrawTarget();
ctx.ResetFrameBuffer();
ctx.ImageWidth = imgW;
ctx.ImageHeight = imgH;
ctx.X = key.InputDesc.Draw.X;
ctx.Y = key.InputDesc.Draw.Y;
ctx.Z = key.InputDesc.Draw.Z;
ctx.Ox = key.InputDesc.CenterPoint.X;
ctx.Oy = key.InputDesc.CenterPoint.Y;
ctx.Oz = 0d;
ctx.Sx = zoom.X;
ctx.Sy = zoom.Y;
ctx.Zoom = zoomAvg;
ctx.Aspect = aspect;
ctx.Alpha = key.InputDesc.Opacity * 255d;
ctx.Rx = key.InputDesc.Rotation.X;
ctx.Ry = key.InputDesc.Rotation.Y;
ctx.Rz = key.InputDesc.Rotation.Z;
ctx.Track0 = key.Track0;
ctx.Track1 = key.Track1;
ctx.Track2 = key.Track2;
ctx.Track3 = key.Track3;
ctx.Slider0 = key.Slider0;
ctx.Slider1 = key.Slider1;
ctx.Slider2 = key.Slider2;
ctx.Slider3 = key.Slider3;
ctx.Check0 = key.Check0;
ctx.Check1 = key.Check1;
ctx.Check2 = key.Check2;
ctx.Check3 = key.Check3;
ctx.HasColor = key.HasColor;
ctx.ColorValue = key.Color;
ctx.Time = key.Time;
ctx.Frame = key.Frame;
ctx.TotalFrame = key.Length;
ctx.TotalTime = key.Fps > 0 ? key.Length / (double)key.Fps : 0d;
ctx.Framerate = key.Fps;
ctx.TimelineFrame = key.TimelineFrame;
ctx.TimelineTime = key.TimelineTime;
ctx.SceneWidth = key.SceneWidth;
ctx.SceneHeight = key.SceneHeight;
ctx.Layer = key.Layer;
ctx.Index = key.InputIndex;
ctx.Num = key.InputCount;
ctx.GroupIndex = key.GroupIndex;
ctx.GroupCount = key.GroupCount;
ctx.TimelineTotalFrame = key.TimelineTotalFrame;
ctx.TimelineTotalTime = key.TimelineTotalTime;
ctx.IsSaving = key.Usage == TimelineSourceUsage.Exporting;
ctx.IsPlaying = key.Usage == TimelineSourceUsage.Playing;
ctx.IsPaused = key.Usage == TimelineSourceUsage.Paused;
ctx.SceneId = ResolveSceneId(key.SceneId);
ctx.TimeRatio = key.Length > 0 ? key.Frame / (double)key.Length : 0d;
ctx.ScriptPath = s_scriptPath;
ctx.HostVersion = s_hostVersion;
ctx.Bpm = key.Bpm;
ctx.BpmBeat = key.BpmBeat;
ctx.BpmOffset = key.BpmOffset;
PopulateStringParameters(ctx);
ctx.SceneScope = _hostDevices;
ctx.BeginSceneValues();
}
private static double ClampTrack(double value, AviUtlParameterLayout layout, int index)
{
return layout.GetTrack(index) is { } p ? Math.Clamp(value, p.Min, p.Max) : value;
}
private ImmutableList<VideoEffectController> _anchorControllers = ImmutableList<VideoEffectController>.Empty;
private AnchorRequestData[] _anchorSignature = [];
private IReadOnlyList<LuaAnchorPoint>? _anchorSignatureSource;
private ImmutableList<VideoEffectController> ResolveAnchorControllers(AviUtlScriptContext ctx)
{
var requests = ctx.AnchorRequests;
if (requests.Count == 0)
{
_anchorControllers = ImmutableList<VideoEffectController>.Empty;
_anchorSignature = [];
_anchorSignatureSource = null;
return _anchorControllers;
}
if (ReferenceEquals(_anchorSignatureSource, ctx.AnchorSource) && AnchorSignatureMatches(requests))
return _anchorControllers;
_anchorControllers = BuildAnchorControllers(ctx.AnchorSource, requests);
_anchorSignature = new AnchorRequestData[requests.Count];
for (int i = 0; i < requests.Count; i++)
_anchorSignature[i] = requests[i];
_anchorSignatureSource = ctx.AnchorSource;
return _anchorControllers;
}
private bool AnchorSignatureMatches(IReadOnlyList<AnchorRequestData> requests)
{
if (_anchorSignature.Length != requests.Count)
return false;
for (int i = 0; i < requests.Count; i++)
if (!_anchorSignature[i].Equals(requests[i]))
return false;
return true;
}
private DrawDescription AddAnchorControllers(DrawDescription desc, AviUtlScriptContext ctx)
{
var controllers = ResolveAnchorControllers(ctx);
return controllers.Count == 0 ? desc : desc with { Controllers = desc.Controllers.AddRange(controllers) };
}
private ImmutableList<VideoEffectController> BuildAnchorControllers(
IReadOnlyList<LuaAnchorPoint>? source, IReadOnlyList<AnchorRequestData> requests)
{
var builder = ImmutableList.CreateBuilder<VideoEffectController>();
foreach (var request in requests)
{
if (request.Count <= 0)
continue;
AddConnectionControllers(builder, source, request);
var group = request.Group;
bool is3D = request.Is3D;
for (int i = 0; i < request.Count; i++)
{
AnchorSupport.ResolvePosition(source, group, i, out double x, out double y, out double z);
int index = i;
var point = new ControllerPoint(
new Vector3((float)x, (float)y, (float)(is3D ? z : 0d)),
arg => item.ApplyAnchorDrag(group, index, arg.Delta.X, arg.Delta.Y, is3D ? arg.Delta.Z : 0d))
{
Shape = VideoControllerPointShape.Circle,
OnDragStart = _ => item.BeginAnchorEdit(group, index, is3D),
};
builder.Add(new VideoEffectController(item, [point]));
}
}
return builder.ToImmutable();
}
private void AddConnectionControllers(
ImmutableList<VideoEffectController>.Builder builder, IReadOnlyList<LuaAnchorPoint>? source, in AnchorRequestData request)
{
switch (request.Connection)
{
case AnchorConnection.Line:
for (int i = 0; i + 1 < request.Count; i++)
AddEdge(builder, ConnectionPoint(source, request, i), ConnectionPoint(source, request, i + 1));
break;
case AnchorConnection.Loop:
for (int i = 0; i + 1 < request.Count; i++)
AddEdge(builder, ConnectionPoint(source, request, i), ConnectionPoint(source, request, i + 1));
if (request.Count >= 2)
AddEdge(builder, ConnectionPoint(source, request, request.Count - 1), ConnectionPoint(source, request, 0));
break;
case AnchorConnection.Star:
for (int i = 0; i < request.Count; i++)
AddEdge(builder, CenterPoint(), ConnectionPoint(source, request, i));
break;
case AnchorConnection.Arm:
if (request.Count >= 1)
AddEdge(builder, CenterPoint(), ConnectionPoint(source, request, 0));
for (int i = 0; i + 1 < request.Count; i++)
AddEdge(builder, ConnectionPoint(source, request, i), ConnectionPoint(source, request, i + 1));
break;
}
}
private void AddEdge(ImmutableList<VideoEffectController>.Builder builder, ControllerPoint a, ControllerPoint b) =>
builder.Add(new VideoEffectController(item, [a, b]) { Connection = VideoControllerPointConnection.Line });
private static ControllerPoint CenterPoint() =>
new(Vector3.Zero) { Shape = VideoControllerPointShape.None };
private static ControllerPoint ConnectionPoint(IReadOnlyList<LuaAnchorPoint>? source, in AnchorRequestData request, int index)
{
AnchorSupport.ResolvePosition(source, request.Group, index, out double x, out double y, out double z);
return new ControllerPoint(new Vector3((float)x, (float)y, (float)(request.Is3D ? z : 0d)))
{
Shape = VideoControllerPointShape.None,
};
}
private void ApplyDrawState(AviUtlScriptContext ctx, RawRectF bounds)
{
if (ctx.DrawStateOverride is not { } drawn)
return;
if (!drawn)
{
effectOutput = null;
return;
}
if (effectOutput is not null)
return;
ctx.EnsurePixelBuffer();
var buffer = ctx.GetPixelBuffer();
if (buffer is null)
return;
_pixelManager!.WritePixelsToOutput(buffer, ctx.ImageWidth, ctx.ImageHeight);
effectOutput = _pixelManager.GetTransformOutput(bounds.Left, bounds.Top);
}
private static DrawDescription BuildOutputDesc(DrawDescription inDesc, AviUtlScriptContext ctx)
{
return inDesc with
{
Draw = new Vector3((float)ctx.X, (float)ctx.Y, (float)ctx.Z),
CenterPoint = new Vector2((float)ctx.Ox, (float)ctx.Oy),
Zoom = new Vector2((float)ctx.Sx, (float)ctx.Sy),
Opacity = Math.Clamp(ctx.Alpha / 255d, 0d, 1d),
Rotation = new Vector3((float)ctx.Rx, (float)ctx.Ry, (float)ctx.Rz),
};
}
private void EnsureKernel(string runnable)
{
if (_kernelResolved && ReferenceEquals(runnable, _kernelSource))
return;
_kernelSource = runnable;
_kernelResolved = true;
_kernelProgram = KernelExtractor.TryExtract(runnable);
_cpuKernel = _kernelProgram is null ? null : CpuKernelCompiler.Compile(_kernelProgram);
_gpuKernel?.Dispose();
_gpuKernel = null;
_gpuKernelChecked = false;
}
private void EnsureDirective(string runnable)
{
if (_directiveCached && ReferenceEquals(runnable, _directiveSource))
return;
_directiveSource = runnable;
_directiveCached = true;
_hasExplicitDirective = ScriptDirective.TryResolveExplicit(runnable, out _explicitDirectiveKind);
_autoKind = ScriptDirective.ResolveAuto(runnable);
}
private bool ExecuteKernelLane(AviUtlScriptContext ctx, RawRectF bounds, int imgW, int imgH)
{
if (_kernelProgram is null || _cpuKernel is null)
return false;
bool explicitDirective = _hasExplicitDirective;
var kind = _explicitDirectiveKind;
if (explicitDirective && kind is not (ScriptEngineKind.Gpu or ScriptEngineKind.Cpu))
return false;
_kernelUniforms ??= KernelUniformBinding.Create();
KernelUniformBinding.Fill(ctx, _kernelUniforms);
if (!explicitDirective || kind == ScriptEngineKind.Gpu)
{
var gpu = GetGpuKernel();
if (gpu is not null)
{
effectOutput = gpu.Apply(input!, _kernelUniforms);
return true;
}
if (explicitDirective)
WarnGpuUnavailableOnce();
}
byte[] buffer = LoadInputPixels(bounds, imgW, imgH);
_cpuKernel.Execute(buffer, imgW, imgH, _kernelUniforms);
_pixelManager!.WritePixelsToOutput(buffer, imgW, imgH);
effectOutput = _pixelManager.GetTransformOutput(bounds.Left, bounds.Top);
return true;
}
private GpuKernel? GetGpuKernel()
{
if (_gpuKernelChecked)
return _gpuKernel;
_gpuKernelChecked = true;
if (_kernelProgram is null || _cpuKernel is null)
return null;
try
{
var kernel = new GpuKernel(_ownCtx!, _kernelProgram);
if (kernel.IsReady && kernel.Verify(_cpuKernel))
{
_gpuKernel = kernel;
}
else
{
if (kernel.IsReady)
Log.Default.Write("LuaScript: GPU kernel output diverges from the CPU kernel beyond tolerance; using the CPU kernel.");
kernel.Dispose();
}
}
catch (Exception ex)
{
Log.Default.Write("LuaScript: GPU kernel initialization failed; falling back to CPU.", ex);
}
return _gpuKernel;
}
private void WarnGpuUnavailableOnce()
{
if (_gpuWarned) return;
_gpuWarned = true;
Log.Default.Write("LuaScript: GPU kernel unavailable; using the CPU kernel lane instead.");
}
private void WarnNativeUnavailableOnce()
{
if (_nativeWarned) return;
_nativeWarned = true;
Log.Default.Write($"LuaScript: native runtime not found at '{NativeDirectory}'. Falling back to MoonSharp (slow). Deploy the 'native' folder next to the plugin.");
}
private void WarnEffectChainFailureOnce(Exception ex)
{
if (_effectChainWarned) return;
_effectChainWarned = true;
Log.Default.Write("LuaScript: obj.effect chain failed and was skipped for this frame. The source image is passed through unchanged.", ex);
}
private bool ExecuteNative(string script, AviUtlScriptContext ctx, RawRectF bounds, int imgW, int imgH)
{
_nativeWorker ??= new LuaJitWorker(NativeDirectory, s_scriptPath);
_nativeFields ??= new double[NativeProtocol.FieldCount];
_nativeUpload ??= UploadNativeInputPixels;
_nativeResolveObject ??= (tag, frame) => _context.ResolveObject(tag, frame, out var info) ? info : null;
_nativeLoadFigure ??= NativeLoadFigure;
_nativeLoadText ??= NativeLoadText;
_nativeLoadImage ??= NativeLoadImage;
_nativeLoadMovie ??= NativeLoadMovie;
_loadSceneImage ??= LoadSceneImage;
_loadBrushImage ??= LoadBrushImage;
_loadAudio ??= LoadAudio;
_nativeAddEffect ??= (name, args) => _context.AddEffect(new AviUtlEffectRequest(name, args));
_nativeAddDraw ??= command => _context.AddDraw(command);
_nativeSetAnchor ??= ResolveNativeAnchor;
_nativeSceneGet ??= name => _context.GetSceneValue(name);
_nativeSceneSet ??= (name, value) => _context.SetSceneValue(name, value);
_nativeRunPixelShader ??= NativeRunPixelShader;
NativeFieldMap.ToFields(ctx, _nativeFields);
_nativeUploaded = false;
bool ok = _nativeWorker.Execute(
script, _nativeFields, ctx.StringParameters, _nativeUpload, imgW, imgH, NativeTimeoutMilliseconds,
_nativeResolveObject,
_nativeLoadFigure,
_nativeLoadText,
_nativeLoadImage,
_nativeLoadMovie,
_loadSceneImage,
_loadBrushImage,
_nativeAddEffect,
_nativeAddDraw,
_nativeSetAnchor,
_nativeSceneGet,
_nativeSceneSet,
_loadAudio,
_nativeRunPixelShader,
out bool dirty, out bool bufferReplaced,
out int resultW, out int resultH, out string? error);
if (!ok)
{
if (error is not null && error.Contains("timed out", StringComparison.Ordinal))
throw new LuaScriptTimeoutException(error);
throw new LuaScriptRuntimeException(error ?? "Native script execution failed.");
}
NativeFieldMap.FromFields(_nativeFields, ctx);
bool hasDraws = ctx.DrawCommands.Count > 0;
if (dirty)
{
int outW = bufferReplaced ? resultW : imgW;
int outH = bufferReplaced ? resultH : imgH;
if (hasDraws)
{
var result = ReadNativeResultPixels(outW, outH);
if (bufferReplaced)
ctx.ReplaceBuffer(result, outW, outH);
else
ctx.SetResolvedBuffer(result, outW, outH);
return true;
}
_nativeOutputWidth = outW;
_nativeOutputHeight = outH;
_nativeWorker.ReadPixels(_nativeWriteOutput ??= WriteNativeOutputPixels);
if (bufferReplaced)
effectOutput = _pixelManager!.GetTransformOutput(-outW / 2f, -outH / 2f);
else
effectOutput = _pixelManager!.GetTransformOutput(bounds.Left, bounds.Top);
return true;
}
if (hasDraws)
{
if (_nativeUploaded)
ctx.SetResolvedBuffer(ReadNativeResultPixels(imgW, imgH), imgW, imgH);
return false;
}
effectOutput = null;
return false;
}
private PixelShaderRunStatus NativeRunPixelShader(
string name,
ReadOnlySpan<PixelShaderInput> resources,
ReadOnlySpan<float> constants,
PixelShaderBlend blend,
PixelShaderSampler sampler,
byte[] target,
int targetWidth,
int targetHeight,
out string? error)
{
error = null;
if (!_context.PixelShaders.TryGet(name, out string hlsl))
{
error = $"obj.pixelshader: shader '{name}' is not defined in this script.";
return PixelShaderRunStatus.CompileError;
}
var runner = _pixelShaderRunner;
if (runner is null)
return PixelShaderRunStatus.Unavailable;
var status = runner.TryRun(
hlsl,
AviUtlPixelShaderLibrary.EntryPointOf(name),
resources, constants, blend, sampler,
target, targetWidth, targetHeight,
out error);
if (status == PixelShaderRunStatus.CompileError)
error = $"obj.pixelshader: shader '{name}' failed to compile.\n{error}";
return status;
}
private void UploadNativeInputPixels(nint address, long capacity)
{
_nativeUploaded = true;
_pixelLoaderSemaphore.Wait();
try
{
_pixelManager!.LoadInputPixelsInto(input!, _pixelBounds, _pixelWidth, _pixelHeight, address, capacity);
}
finally
{
_pixelLoaderSemaphore.Release();
}
}
private byte[] ReadNativeResultPixels(int width, int height)
{
int length = width * height * 4;
if (_nativeResultBuffer is null || _nativeResultBuffer.Length < length)
_nativeResultBuffer = new byte[length];
_nativeReadLength = length;
_nativeWorker!.ReadPixels(_nativeReadIntoResult ??= ReadNativePixelsIntoResult);
return _nativeResultBuffer;
}
private unsafe void ReadNativePixelsIntoResult(nint address, long capacity)
{
fixed (byte* destination = _nativeResultBuffer)
Buffer.MemoryCopy((void*)address, destination, _nativeResultBuffer!.Length, Math.Min(_nativeReadLength, capacity));
}
private void WriteNativeOutputPixels(nint address, long capacity)
{
_pixelManager!.WritePixelsToOutput(address, _nativeOutputWidth, _nativeOutputHeight);
}
private void ResolveNativeAnchor(string group, int count, bool is3D, int connection, double[] positions)
{
_context.AddAnchorRequest(new AnchorRequestData(group, count, (AnchorConnection)connection, is3D));
int stride = is3D ? 3 : 2;
var source = _context.AnchorSource;
for (int i = 0; i < count; i++)
{
AnchorSupport.ResolvePosition(source, group, i, out double x, out double y, out double z);
positions[i * stride + 0] = x;
positions[i * stride + 1] = y;
if (is3D)
positions[i * stride + 2] = z;
}
}
private (byte[] buffer, int w, int h) NativeLoadText(string family, string text, double size, bool bold, bool italic, int color)
{
_nativeTextRenderer ??= new TextRenderer();
var buffer = _nativeTextRenderer.Render(text, family, size, bold, italic, color, out int w, out int h);
return (buffer, w, h);
}
private (byte[] buffer, int w, int h) NativeLoadImage(string path)
{
_nativeImageDecoder ??= new ImageDecoder();
var buffer = _nativeImageDecoder.Decode(path, out int w, out int h);
return (buffer, w, h);
}
private static readonly (byte[] Buffer, int Width, int Height) s_noLoadedImage = ([], 0, 0);
private (byte[] Buffer, int Width, int Height) LoadSceneImage(string name, double time)
{
var desc = _frameDesc;
var devices = _hostDevices;
if (desc is null || devices is null)
return s_noLoadedImage;
_pixelLoaderSemaphore.Wait();
try
{
_sceneImageRenderer ??= new SceneImageRenderer(devices);
if (!_sceneImageRenderer.TryRender(desc, name, time, out var pixels, out int width, out int height))
return s_noLoadedImage;
_sceneImageLoaded = true;
return (pixels, width, height);
}
finally
{
_pixelLoaderSemaphore.Release();
}
}
private (byte[] Buffer, int Width, int Height) LoadBrushImage(string name, double width, double height, IReadOnlyList<KeyValuePair<string, object>> arguments)
{
var desc = _frameDesc;
var devices = _hostDevices;
if (desc is null || devices is null)
return s_noLoadedImage;
int w = (int)Math.Round(width);
int h = (int)Math.Round(height);
_pixelLoaderSemaphore.Wait();
try
{
_brushImageRenderer ??= new BrushImageRenderer(devices);
if (!_brushImageRenderer.TryRender(desc, name, w, h, arguments, out var pixels, out int outWidth, out int outHeight))
return s_noLoadedImage;
return (pixels, outWidth, outHeight);
}
finally
{
_pixelLoaderSemaphore.Release();
}
}
private static readonly (int Count, int Rate, double[] Data) s_noAudio = (0, 0, []);
private (int Count, int Rate, double[] Data) LoadAudio(string file, string type, int size)
{
var desc = _frameDesc;
if (desc is null)
return s_noAudio;
_audioProvider ??= new AudioSampleProvider();
(int Count, int Rate) result;
if (string.Equals(file, "audiobuffer", StringComparison.Ordinal))
{
result = _audioProvider.ReadScene(FindOwnScene(desc), desc.TimelinePosition.Time.TotalSeconds, type, size);
}
else if (string.Equals(file, "itembuffer", StringComparison.Ordinal))
{
var (audioItem, scene) = ResolveOwnAudioItem(desc);
result = _audioProvider.ReadItem(audioItem, scene, desc.ItemPosition.Time.TotalSeconds, type, size);
}
else
{
result = _audioProvider.ReadFile(file, desc.ItemPosition.Time.TotalSeconds, type, size);
}
if (result.Count > 0)
_audioLoaded = true;
return (result.Count, result.Rate, _audioProvider.Data);
}
private static Scene? FindOwnScene(EffectDescription desc)
{
var scenes = desc.Scenes;
if (scenes is null)
return null;
foreach (var info in scenes)
{
if (info is Scene scene && scene.ID == desc.SceneId)
return scene;
}
return null;
}
private (IAudioItem? Item, Scene? Scene) ResolveOwnAudioItem(EffectDescription desc)
{
var scene = FindOwnScene(desc);
if (scene is null)
return (null, null);
var items = scene.Timeline.Items;
for (int i = 0; i < items.Count; i++)
{
if (items[i] is not IVideoItem video)
continue;
var effects = video.VideoEffects;
for (int k = 0; k < effects.Count; k++)
{
if (ReferenceEquals(effects[k], item))
return (items[i] as IAudioItem, scene);
}
}
return (null, scene);
}
private (byte[] buffer, int w, int h) NativeLoadMovie(string path, double time)
{
_nativeMovieDecoder ??= new MovieDecoder();
var buffer = _nativeMovieDecoder.Decode(path, time, out int w, out int h);
return (buffer, w, h);
}
private static (byte[] buffer, int w, int h) NativeLoadFigure(string name, int color, double size, double lineWidth, double aspect)
{
aspect = Math.Clamp(aspect, -1d, 1d);
int boundingSize = Math.Max(1, (int)Math.Round(size));
double w = aspect >= 0d ? boundingSize * (1d - aspect) : boundingSize;
double h = aspect <= 0d ? boundingSize * (1d + aspect) : boundingSize;
int fw = Math.Max(1, (int)Math.Round(w));
int fh = Math.Max(1, (int)Math.Round(h));
var buffer = FigureRenderer.Render(name, fw, fh, color, lineWidth);
return (buffer, fw, fh);
}
private byte[] LoadPendingInputPixels() => LoadInputPixels(_pixelBounds, _pixelWidth, _pixelHeight);
private byte[] LoadInputPixels(RawRectF bounds, int width, int height)
{
_pixelLoaderSemaphore.Wait();
try
{
return _pixelManager!.LoadInputPixels(input!, bounds, width, height);
}
finally
{
_pixelLoaderSemaphore.Release();
}
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
_engine.Dispose();
_gpuKernel?.Dispose();
_pixelShaderRunner?.Dispose();
_nativeWorker?.Dispose();
_effectChain?.Dispose();
_drawCompositor?.Dispose();
_bufferCompositor?.Dispose();
_nativeTextRenderer?.Dispose();
_nativeImageDecoder?.Dispose();
_sceneImageRenderer?.Dispose();
_brushImageRenderer?.Dispose();
_audioProvider?.Dispose();
_pixelLoaderSemaphore.Dispose();
_pixelManager?.Dispose();
_pixelManager = null;
}
base.Dispose(disposing);
}
}
}