毎フレーム処理のアロケーションを削減し動画出力を高速化

このコミットが含まれているのは:
routersys committed 2026-06-26 20:25:58 +09:00
1 親 21615a5461
コミット 6e29bf08b0
4ファイル変更
+187 -141

検索条件に一致するファイルはありません

+32 -29
ファイルの表示
@@ -2,12 +2,12 @@ namespace LuaScript
{ {
internal sealed class AviUtlScriptContext internal sealed class AviUtlScriptContext
{ {
public bool IsPlaying { get; init; } public bool IsPlaying { get; set; }
public bool IsPaused { get; init; } public bool IsPaused { get; set; }
public string SceneId { get; init; } = string.Empty; public string SceneId { get; set; } = string.Empty;
public int ImageWidth { get; init; } public int ImageWidth { get; set; }
public int ImageHeight { get; init; } public int ImageHeight { get; set; }
public double X { get; set; } public double X { get; set; }
public double Y { get; set; } public double Y { get; set; }
@@ -24,25 +24,25 @@ namespace LuaScript
public double Ry { get; set; } public double Ry { get; set; }
public double Rz { get; set; } public double Rz { get; set; }
public double Track0 { get; init; } public double Track0 { get; set; }
public double Track1 { get; init; } public double Track1 { get; set; }
public double Track2 { get; init; } public double Track2 { get; set; }
public double Track3 { get; init; } public double Track3 { get; set; }
public double Time { get; init; } public double Time { get; set; }
public int Frame { get; init; } public int Frame { get; set; }
public int TotalFrame { get; init; } public int TotalFrame { get; set; }
public double TotalTime { get; init; } public double TotalTime { get; set; }
public int Framerate { get; init; } public int Framerate { get; set; }
public int TimelineFrame { get; init; } public int TimelineFrame { get; set; }
public double TimelineTime { get; init; } public double TimelineTime { get; set; }
public int SceneWidth { get; init; } public int SceneWidth { get; set; }
public int SceneHeight { get; init; } public int SceneHeight { get; set; }
public int Layer { get; init; } public int Layer { get; set; }
public int Index { get; init; } public int Index { get; set; }
public int Num { get; init; } public int Num { get; set; }
public SceneObjectResolver? Resolver { get; init; } public Func<SceneObjectResolver>? ResolverProvider { get; set; }
private readonly List<SceneObjectQuery> _objectQueries = []; private readonly List<SceneObjectQuery> _objectQueries = [];
@@ -52,12 +52,12 @@ namespace LuaScript
public double RyRad => Ry * Math.PI / 180d; public double RyRad => Ry * Math.PI / 180d;
public double RzRad => Rz * Math.PI / 180d; public double RzRad => Rz * Math.PI / 180d;
public int GroupIndex { get; init; } public int GroupIndex { get; set; }
public int GroupCount { get; init; } public int GroupCount { get; set; }
public int TimelineTotalFrame { get; init; } public int TimelineTotalFrame { get; set; }
public double TimelineTotalTime { get; init; } public double TimelineTotalTime { get; set; }
public bool IsSaving { get; init; } public bool IsSaving { get; set; }
public double TimeRatio { get; init; } public double TimeRatio { get; set; }
private Func<byte[]>? _pixelLoader; private Func<byte[]>? _pixelLoader;
private byte[]? _pixelBuffer; private byte[]? _pixelBuffer;
@@ -68,6 +68,8 @@ namespace LuaScript
internal int TotalChannels => ImageWidth * ImageHeight * 4; internal int TotalChannels => ImageWidth * ImageHeight * 4;
internal void ClearQueries() => _objectQueries.Clear();
internal void SetPixelLoader(Func<byte[]> loader) internal void SetPixelLoader(Func<byte[]> loader)
{ {
_pixelLoader = loader; _pixelLoader = loader;
@@ -89,7 +91,8 @@ namespace LuaScript
public bool ResolveObject(string tag, int frame, out SceneObjectInfo info) public bool ResolveObject(string tag, int frame, out SceneObjectInfo info)
{ {
if (Resolver is not null && Resolver.TryResolve(tag, frame, out var resolved)) var resolver = ResolverProvider?.Invoke();
if (resolver is not null && resolver.TryResolve(tag, frame, out var resolved))
{ {
_objectQueries.Add(new SceneObjectQuery(tag, frame, resolved)); _objectQueries.Add(new SceneObjectQuery(tag, frame, resolved));
info = resolved; info = resolved;
+90 -50
ファイルの表示
@@ -44,6 +44,15 @@ namespace LuaScript
private readonly LuaScriptEngine _engine = new(); private readonly LuaScriptEngine _engine = new();
private readonly SemaphoreSlim _pixelLoaderSemaphore = new(1, 1); private readonly SemaphoreSlim _pixelLoaderSemaphore = new(1, 1);
private AviUtlScriptContext _context = new();
private EffectDescription? _frameDesc;
private SceneObjectResolver? _frameResolver;
private bool _frameResolverBuilt;
private Guid _lastSceneGuid;
private string _lastSceneId = string.Empty;
private bool _sceneIdCached;
private GraphicsDevicesAndContext? _ownCtx; private GraphicsDevicesAndContext? _ownCtx;
@@ -67,9 +76,31 @@ namespace LuaScript
{ {
_ownCtx = new GraphicsDevicesAndContext(devices); _ownCtx = new GraphicsDevicesAndContext(devices);
disposer.Collect(_ownCtx); disposer.Collect(_ownCtx);
_context.ResolverProvider = GetFrameResolver;
return null; return null;
} }
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;
}
protected override void setInput(ID2D1Image? input) protected override void setInput(ID2D1Image? input)
{ {
if (!ReferenceEquals(_cachedInput, input)) if (!ReferenceEquals(_cachedInput, input))
@@ -113,10 +144,12 @@ namespace LuaScript
desc.TimelineDuration.Time.TotalSeconds, desc.TimelineDuration.Time.TotalSeconds,
inDesc); inDesc);
var resolver = BuildSceneObjectResolver(desc); _frameDesc = desc;
_frameResolver = null;
_frameResolverBuilt = false;
if (!_isFirst && key == _cachedKey && if (!_isFirst && key == _cachedKey &&
QueriesMatch(_cachedQueries, resolver)) (_cachedQueries.Length == 0 || QueriesMatch(_cachedQueries, GetFrameResolver())))
{ {
effectOutput = _cachedPixelsModified ? _transformEffect?.Output : null; effectOutput = _cachedPixelsModified ? _transformEffect?.Output : null;
return _cachedOutputDesc ?? inDesc; return _cachedOutputDesc ?? inDesc;
@@ -126,7 +159,8 @@ namespace LuaScript
int imgW = Math.Max(1, (int)Math.Ceiling(bounds.Right - bounds.Left)); int imgW = Math.Max(1, (int)Math.Ceiling(bounds.Right - bounds.Left));
int imgH = Math.Max(1, (int)Math.Ceiling(bounds.Bottom - bounds.Top)); int imgH = Math.Max(1, (int)Math.Ceiling(bounds.Bottom - bounds.Top));
var ctx = BuildContext(in key, imgW, imgH, resolver); var ctx = _context;
PopulateContext(ctx, in key, imgW, imgH);
ctx.SetPixelLoader(() => LoadInputPixels(bounds, imgW, imgH)); ctx.SetPixelLoader(() => LoadInputPixels(bounds, imgW, imgH));
DrawDescription outDesc = inDesc; DrawDescription outDesc = inDesc;
@@ -151,6 +185,14 @@ namespace LuaScript
outDesc = BuildOutputDesc(inDesc, ctx); outDesc = BuildOutputDesc(inDesc, ctx);
} }
catch (LuaScriptTimeoutException ex)
{
effectOutput = null;
_context = new AviUtlScriptContext { ResolverProvider = GetFrameResolver };
_isFirst = true;
Log.Default.Write(ex.Message, ex);
return inDesc;
}
catch (LuaScriptException ex) catch (LuaScriptException ex)
{ {
effectOutput = null; effectOutput = null;
@@ -165,7 +207,7 @@ namespace LuaScript
_isFirst = false; _isFirst = false;
_cachedKey = key; _cachedKey = key;
_cachedQueries = [.. ctx.ObjectQueries]; _cachedQueries = ctx.ObjectQueries.Count == 0 ? [] : [.. ctx.ObjectQueries];
_cachedOutputDesc = outDesc; _cachedOutputDesc = outDesc;
_cachedPixelsModified = pixelsModified; _cachedPixelsModified = pixelsModified;
@@ -219,7 +261,7 @@ namespace LuaScript
return true; return true;
} }
private static AviUtlScriptContext BuildContext(in RenderKey key, int imgW, int imgH, SceneObjectResolver resolver) private void PopulateContext(AviUtlScriptContext ctx, in RenderKey key, int imgW, int imgH)
{ {
var zoom = key.InputDesc.Zoom; var zoom = key.InputDesc.Zoom;
double zoomAvg = (zoom.X + zoom.Y) / 2d; double zoomAvg = (zoom.X + zoom.Y) / 2d;
@@ -227,51 +269,49 @@ namespace LuaScript
? (zoom.X - zoom.Y) / (zoom.X + zoom.Y) ? (zoom.X - zoom.Y) / (zoom.X + zoom.Y)
: 0d; : 0d;
return new AviUtlScriptContext ctx.ClearQueries();
{
ImageWidth = imgW, ctx.ImageWidth = imgW;
ImageHeight = imgH, ctx.ImageHeight = imgH;
X = key.InputDesc.Draw.X, ctx.X = key.InputDesc.Draw.X;
Y = key.InputDesc.Draw.Y, ctx.Y = key.InputDesc.Draw.Y;
Z = key.InputDesc.Draw.Z, ctx.Z = key.InputDesc.Draw.Z;
Ox = key.InputDesc.CenterPoint.X, ctx.Ox = key.InputDesc.CenterPoint.X;
Oy = key.InputDesc.CenterPoint.Y, ctx.Oy = key.InputDesc.CenterPoint.Y;
Oz = 0d, ctx.Oz = 0d;
Sx = zoom.X, ctx.Sx = zoom.X;
Sy = zoom.Y, ctx.Sy = zoom.Y;
Zoom = zoomAvg, ctx.Zoom = zoomAvg;
Aspect = aspect, ctx.Aspect = aspect;
Alpha = key.InputDesc.Opacity * 255d, ctx.Alpha = key.InputDesc.Opacity * 255d;
Rx = key.InputDesc.Rotation.X, ctx.Rx = key.InputDesc.Rotation.X;
Ry = key.InputDesc.Rotation.Y, ctx.Ry = key.InputDesc.Rotation.Y;
Rz = key.InputDesc.Rotation.Z, ctx.Rz = key.InputDesc.Rotation.Z;
Track0 = key.Track0, ctx.Track0 = key.Track0;
Track1 = key.Track1, ctx.Track1 = key.Track1;
Track2 = key.Track2, ctx.Track2 = key.Track2;
Track3 = key.Track3, ctx.Track3 = key.Track3;
Time = key.Time, ctx.Time = key.Time;
Frame = key.Frame, ctx.Frame = key.Frame;
TotalFrame = key.Length, ctx.TotalFrame = key.Length;
TotalTime = key.Fps > 0 ? key.Length / (double)key.Fps : 0d, ctx.TotalTime = key.Fps > 0 ? key.Length / (double)key.Fps : 0d;
Framerate = key.Fps, ctx.Framerate = key.Fps;
TimelineFrame = key.TimelineFrame, ctx.TimelineFrame = key.TimelineFrame;
TimelineTime = key.TimelineTime, ctx.TimelineTime = key.TimelineTime;
SceneWidth = key.SceneWidth, ctx.SceneWidth = key.SceneWidth;
SceneHeight = key.SceneHeight, ctx.SceneHeight = key.SceneHeight;
Layer = key.Layer, ctx.Layer = key.Layer;
Index = key.InputIndex, ctx.Index = key.InputIndex;
Num = key.InputCount, ctx.Num = key.InputCount;
GroupIndex = key.GroupIndex, ctx.GroupIndex = key.GroupIndex;
GroupCount = key.GroupCount, ctx.GroupCount = key.GroupCount;
TimelineTotalFrame = key.TimelineTotalFrame, ctx.TimelineTotalFrame = key.TimelineTotalFrame;
TimelineTotalTime = key.TimelineTotalTime, ctx.TimelineTotalTime = key.TimelineTotalTime;
IsSaving = key.Usage == TimelineSourceUsage.Exporting, ctx.IsSaving = key.Usage == TimelineSourceUsage.Exporting;
IsPlaying = key.Usage == TimelineSourceUsage.Playing, ctx.IsPlaying = key.Usage == TimelineSourceUsage.Playing;
IsPaused = key.Usage == TimelineSourceUsage.Paused, ctx.IsPaused = key.Usage == TimelineSourceUsage.Paused;
SceneId = key.SceneId.ToString(), ctx.SceneId = ResolveSceneId(key.SceneId);
TimeRatio = key.Length > 0 ? key.Frame / (double)key.Length : 0d, ctx.TimeRatio = key.Length > 0 ? key.Frame / (double)key.Length : 0d;
Resolver = resolver,
};
} }
private static DrawDescription BuildOutputDesc(DrawDescription inDesc, AviUtlScriptContext ctx) private static DrawDescription BuildOutputDesc(DrawDescription inDesc, AviUtlScriptContext ctx)
+63 -62
ファイルの表示
@@ -1,4 +1,3 @@
using System.Collections.Concurrent;
using MoonSharp.Interpreter; using MoonSharp.Interpreter;
using MoonSharp.Interpreter.Debugging; using MoonSharp.Interpreter.Debugging;
using MoonSharp.Interpreter.Loaders; using MoonSharp.Interpreter.Loaders;
@@ -11,12 +10,6 @@ namespace LuaScript
LuaScriptException? Exception, LuaScriptException? Exception,
bool TimedOut); bool TimedOut);
private sealed record ExecutionJob(
string Code,
AviUtlScriptContext Context,
CancellationToken Cancellation,
TaskCompletionSource<ExecutionResult> Completion);
private sealed class ExecutionThread : IDisposable private sealed class ExecutionThread : IDisposable
{ {
private sealed class CancellationDebugger : IDebugger private sealed class CancellationDebugger : IDebugger
@@ -46,10 +39,19 @@ namespace LuaScript
} }
} }
private readonly BlockingCollection<ExecutionJob> _queue = new(boundedCapacity: 1); private readonly SemaphoreSlim _workSignal = new(0);
private readonly ManualResetEventSlim _doneSignal = new(false);
private readonly CancellationTokenSource _cts = new();
private readonly Thread _thread; private readonly Thread _thread;
private readonly CancellationDebugger _debugger = new(); private readonly CancellationDebugger _debugger = new();
private string _jobCode = string.Empty;
private AviUtlScriptContext? _jobContext;
private LuaScriptException? _jobException;
private volatile bool _disposeRequested;
private readonly List<string> _removalBuffer = [];
private Script? _script; private Script? _script;
private DynValue? _compiledChunk; private DynValue? _compiledChunk;
private string _lastCompiledCode = string.Empty; private string _lastCompiledCode = string.Empty;
@@ -67,6 +69,8 @@ namespace LuaScript
internal ExecutionThread() internal ExecutionThread()
{ {
_activeCancellation = _cts.Token;
_debugger.UpdateToken(_cts.Token);
_thread = new Thread(WorkerLoop) _thread = new Thread(WorkerLoop)
{ {
IsBackground = true, IsBackground = true,
@@ -77,77 +81,65 @@ namespace LuaScript
internal ExecutionResult TryExecute(string code, AviUtlScriptContext ctx, int timeoutMs) internal ExecutionResult TryExecute(string code, AviUtlScriptContext ctx, int timeoutMs)
{ {
using var cts = new CancellationTokenSource(); _jobCode = code;
var tcs = new TaskCompletionSource<ExecutionResult>( _jobContext = ctx;
TaskCreationOptions.RunContinuationsAsynchronously); _jobException = null;
_doneSignal.Reset();
_workSignal.Release();
if (!_queue.TryAdd(new ExecutionJob(code, ctx, cts.Token, tcs))) if (_doneSignal.Wait(timeoutMs))
return new ExecutionResult( return new ExecutionResult(_jobException, false);
new LuaScriptRuntimeException("Script execution queue is full."), false);
if (tcs.Task.Wait(timeoutMs)) _cts.Cancel();
return tcs.Task.Result;
cts.Cancel();
return new ExecutionResult(null, TimedOut: true); return new ExecutionResult(null, TimedOut: true);
} }
private void WorkerLoop() private void WorkerLoop()
{ {
try while (true)
{ {
foreach (var job in _queue.GetConsumingEnumerable()) _workSignal.Wait();
ProcessJob(job); if (_disposeRequested)
return;
ProcessJob();
_doneSignal.Set();
} }
catch (OperationCanceledException) { }
catch (InvalidOperationException) { }
} }
private void ProcessJob(ExecutionJob job) private void ProcessJob()
{ {
if (job.Cancellation.IsCancellationRequested) var context = _jobContext!;
{ _activeContext = context;
job.Completion.TrySetResult(new ExecutionResult(null, TimedOut: true));
return;
}
_activeCancellation = job.Cancellation;
_activeContext = job.Context;
_debugger.UpdateToken(job.Cancellation);
try try
{ {
EnsureScript(); EnsureScript();
EnsureScriptIntegrity(); EnsureScriptIntegrity();
EnsureCompiled(job.Code); EnsureCompiled(_jobCode);
SetupGlobals(job.Context); SetupGlobals(context);
_script!.Call(_compiledChunk!); _script!.Call(_compiledChunk!);
ReadBackGlobals(job.Context); ReadBackGlobals(context);
job.Completion.TrySetResult(new ExecutionResult(null, false)); _jobException = null;
} }
catch (OperationCanceledException) when (job.Cancellation.IsCancellationRequested) catch (OperationCanceledException) when (_cts.IsCancellationRequested)
{ {
job.Completion.TrySetResult(new ExecutionResult(null, TimedOut: true)); _jobException = null;
} }
catch (LuaScriptException ex) catch (LuaScriptException ex)
{ {
job.Completion.TrySetResult(new ExecutionResult(ex, false)); _jobException = ex;
} }
catch (ScriptRuntimeException ex) catch (ScriptRuntimeException ex)
{ {
job.Completion.TrySetResult(new ExecutionResult( _jobException = new LuaScriptRuntimeException(ex.DecoratedMessage ?? ex.Message, ex);
new LuaScriptRuntimeException(ex.DecoratedMessage ?? ex.Message, ex), false));
} }
catch (Exception ex) catch (Exception ex)
{ {
job.Completion.TrySetResult(new ExecutionResult( _jobException = new LuaScriptRuntimeException(ex.Message, ex);
new LuaScriptRuntimeException(ex.Message, ex), false));
} }
finally finally
{ {
_debugger.UpdateToken(default);
_activeContext = null; _activeContext = null;
_activeCancellation = default;
} }
} }
@@ -269,10 +261,10 @@ namespace LuaScript
_ymm4TableSnapshot = null; _ymm4TableSnapshot = null;
} }
ResetUserTableKeys(_objTable!, ref _objTableSnapshot); ResetUserTableKeys(_objTable!, _objTableSnapshot);
ResetUserTableKeys(_sceneTable!, ref _sceneTableSnapshot); ResetUserTableKeys(_sceneTable!, _sceneTableSnapshot);
ResetUserTableKeys(_animTable!, ref _animTableSnapshot); ResetUserTableKeys(_animTable!, _animTableSnapshot);
ResetUserTableKeys(_ymm4Table!, ref _ymm4TableSnapshot); ResetUserTableKeys(_ymm4Table!, _ymm4TableSnapshot);
} }
script.Globals["time"] = ctx.Time; script.Globals["time"] = ctx.Time;
@@ -366,34 +358,36 @@ namespace LuaScript
return keys; return keys;
} }
private static void ResetUserTableKeys(Table table, ref HashSet<string>? snapshot) private void ResetUserTableKeys(Table table, HashSet<string>? snapshot)
{ {
if (snapshot is null) return; if (snapshot is null) return;
var keysToRemove = new List<string>(); var buffer = _removalBuffer;
buffer.Clear();
foreach (var key in table.Keys) foreach (var key in table.Keys)
{ {
if (key.Type == DataType.String && if (key.Type == DataType.String &&
!snapshot.Contains(key.String)) !snapshot.Contains(key.String))
{ {
keysToRemove.Add(key.String); buffer.Add(key.String);
} }
} }
foreach (var key in keysToRemove) foreach (var key in buffer)
table[key] = DynValue.Nil; table[key] = DynValue.Nil;
} }
private void ResetUserGlobals(Script script) private void ResetUserGlobals(Script script)
{ {
var keysToRemove = new List<string>(); var buffer = _removalBuffer;
buffer.Clear();
foreach (var key in script.Globals.Keys) foreach (var key in script.Globals.Keys)
{ {
if (key.Type == DataType.String && if (key.Type == DataType.String &&
!_builtinGlobalSnapshot!.Contains(key.String)) !_builtinGlobalSnapshot!.Contains(key.String))
{ {
keysToRemove.Add(key.String); buffer.Add(key.String);
} }
} }
foreach (var key in keysToRemove) foreach (var key in buffer)
script.Globals[key] = DynValue.Nil; script.Globals[key] = DynValue.Nil;
} }
@@ -531,18 +525,25 @@ namespace LuaScript
public void Dispose() public void Dispose()
{ {
_queue.CompleteAdding(); _disposeRequested = true;
_workSignal.Release();
_thread.Join(); _thread.Join();
_queue.Dispose(); _cts.Cancel();
_cts.Dispose();
_workSignal.Dispose();
_doneSignal.Dispose();
} }
internal void AbandonAsync() internal void AbandonAsync()
{ {
_queue.CompleteAdding(); _disposeRequested = true;
_workSignal.Release();
ThreadPool.QueueUserWorkItem(_ => ThreadPool.QueueUserWorkItem(_ =>
{ {
_thread.Join(); _thread.Join();
_queue.Dispose(); _cts.Dispose();
_workSignal.Dispose();
_doneSignal.Dispose();
}); });
} }
@@ -577,7 +578,7 @@ namespace LuaScript
var stale = _executionThread; var stale = _executionThread;
_executionThread = new ExecutionThread(); _executionThread = new ExecutionThread();
stale.AbandonAsync(); stale.AbandonAsync();
throw new LuaScriptRuntimeException( throw new LuaScriptTimeoutException(
$"Script execution timed out after {ExecutionTimeoutMilliseconds} ms."); $"Script execution timed out after {ExecutionTimeoutMilliseconds} ms.");
} }
+2
ファイルの表示
@@ -5,4 +5,6 @@ namespace LuaScript
internal sealed class LuaScriptCompilationException(string message, Exception? inner = null) : LuaScriptException(message, inner); internal sealed class LuaScriptCompilationException(string message, Exception? inner = null) : LuaScriptException(message, inner);
internal sealed class LuaScriptRuntimeException(string message, Exception? inner = null) : LuaScriptException(message, inner); internal sealed class LuaScriptRuntimeException(string message, Exception? inner = null) : LuaScriptException(message, inner);
internal sealed class LuaScriptTimeoutException(string message, Exception? inner = null) : LuaScriptException(message, inner);
} }