ファイル
YMM4-ProxyForge/ZeroDiskProxy/Plugin/ZeroDiskProxyVideoSource.cs
T
routersys 2515bb1e39 ゼロアロケーション達成とGC圧力の全面的な解消
MfProxyEncoderのEncodeAsyncにおいてFile.ReadAllBytesAsyncをArrayPool<byte>.Sharedを用いたFileStream読み込みに置き換え、LOH新規アロケーションを廃止しました。
BufferPoolをArrayPool<byte>.Shared直接委譲に統一し、カスタムプールの16MB上限制約を撤廃しました。
ProxyCacheEntryがプールバッファの所有権を保持するよう変更し、Dispose時にBufferPool.Returnで確実に返却するようにしました。
OpenReadStreamはコピーを返すことでプールバッファのライフタイムをentryに閉じるようにしました。
GetOrCreateTempFilePathのGuid文字列生成をstackalloc char[45]とGuid.TryFormatに置き換え、string.Concatアロケーションを排除しました。
ProxyCacheManagerのキャッシュキーをprivate readonly struct CacheKeyとして定義し、ConcurrentDictionary<CacheKey, ...>に変更することで毎フレームのstring.Createアロケーションをゼロにしました。
ClearAllの_pendingGenerationsと_cacheに対する.Keys.ToArray()スナップショット生成をforeachによる直接イテレーションに置き換えました。
GetAllSnapshotsをnew CacheEntrySnapshot[count]単一確保とArray.Resizeパターンに変更し、List<T>確保とToArray呼び出しによる二段アロケーションを廃止しました。
MfProxyEncoderのBeginInvokeに渡すラムダをAction dispatchAction = progressItem.ApplyPendingProgressとして事前確保し、プログレス更新ごとのデリゲートアロケーションを廃止しました。
ProxyGenerationItemにSetPendingProgressとApplyPendingProgressを追加し、long _pendingProgressBitsフィールドへのInterlocked操作によりスレッドセーフにプログレス値を中継するようにしました。
MemoryBudgetにGetAvailablePhysicalMemoryの100msキャッシュを追加し、TryAllocateとCanAllocateInMemoryの両方から呼ばれるシステムコール回数を大幅に削減しました。
FallbackStreamのWriteメソッドにおいて_isFallenBackがtrueの場合はlock (_switchLock)を迂回してFileStreamへ直接書き込むロックフリーパスを追加しました。
ExportDetectorの_lastCheckTicks(long)と_lastExportState(int)をlong _packedに統合し、上位62ビットにEnvironment.TickCount64、下位2ビットにstate(0=未確定、1=false、2=true)をパックしてInterlocked.ReadとInterlocked.Exchangeの1回の操作で両者をアトミックに更新することで2変数間の非アトミックレースを完全に除去しました。
ZeroDiskProxyVideoSourceのFetchUpgradeAsync起動をTask.RunからThreadPool.UnsafeQueueUserWorkItem(static s => s.FetchUpgradeAsync(), this, preferLocal: false)に変更し、TaskオブジェクトおよびActionオブジェクトのアロケーションをゼロにしました。
ZeroDiskProxyVideoSourceのUpdateメソッドにおいて_upgraded(volatile bool)が真の場合はlock (_gate)を迂回して_inner.Update(time)を直接呼ぶロックフリーパスを追加し、アップグレード完了後の長期再生中に不要なロック取得を排除しました。
2026-03-24 16:13:59 +09:00

150 行
4.3 KiB
C#

using System.Diagnostics;
using System.Numerics;
using Vortice.Direct2D1;
using Vortice.Direct2D1.Effects;
using YukkuriMovieMaker.Commons;
using YukkuriMovieMaker.Plugin.FileSource;
namespace ZeroDiskProxy.Plugin;
internal sealed class ZeroDiskProxyVideoSource : IVideoFileSource
{
private IVideoFileSource _inner;
private readonly Func<IVideoFileSource?>? _tryUpgradeSource;
private readonly AffineTransform2D _switchEffect;
private readonly ID2D1Image _output;
private List<IVideoFileSource>? _retiredSources;
private readonly object _gate = new();
private volatile bool _upgraded;
private volatile IVideoFileSource? _pendingUpgrade;
private int _upgradeFetching;
private long _nextUpgradeAttemptTicks;
private int _disposed;
public TimeSpan Duration
{
get
{
lock (_gate)
return _inner.Duration;
}
}
public ID2D1Image Output => _output;
internal ZeroDiskProxyVideoSource(IVideoFileSource inner, IGraphicsDevicesAndContext devices)
{
_inner = inner;
_switchEffect = new AffineTransform2D(devices.DeviceContext);
_switchEffect.SetInput(0, inner.Output, true);
_switchEffect.TransformMatrix = Matrix3x2.Identity;
_output = _switchEffect.Output;
}
internal ZeroDiskProxyVideoSource(IVideoFileSource inner, IGraphicsDevicesAndContext devices, Func<IVideoFileSource?> tryUpgradeSource)
{
_inner = inner;
_switchEffect = new AffineTransform2D(devices.DeviceContext);
_switchEffect.SetInput(0, inner.Output, true);
_switchEffect.TransformMatrix = Matrix3x2.Identity;
_output = _switchEffect.Output;
_tryUpgradeSource = tryUpgradeSource;
}
public void Update(TimeSpan time)
{
if (!_upgraded && _tryUpgradeSource is not null)
{
var pending = _pendingUpgrade;
if (pending is not null)
{
_pendingUpgrade = null;
lock (_gate)
{
if (!_upgraded && Volatile.Read(ref _disposed) == 0)
{
(_retiredSources ??= []).Add(_inner);
_inner = pending;
_switchEffect.SetInput(0, pending.Output, true);
_upgraded = true;
}
else
{
pending.Dispose();
}
}
}
else
{
var now = Stopwatch.GetTimestamp();
if (now >= Volatile.Read(ref _nextUpgradeAttemptTicks) &&
Interlocked.Exchange(ref _upgradeFetching, 1) == 0)
{
Volatile.Write(ref _nextUpgradeAttemptTicks, now + Stopwatch.Frequency / 2);
ThreadPool.UnsafeQueueUserWorkItem(static s => s.FetchUpgradeAsync(), this, preferLocal: false);
}
}
}
if (_upgraded)
{
if (Volatile.Read(ref _disposed) == 0)
_inner.Update(time);
return;
}
lock (_gate)
_inner.Update(time);
}
private void FetchUpgradeAsync()
{
try
{
var upgraded = _tryUpgradeSource!();
if (upgraded is not null)
_pendingUpgrade = upgraded;
}
catch { }
finally
{
Volatile.Write(ref _upgradeFetching, 0);
}
}
public int GetFrameIndex(TimeSpan time)
{
lock (_gate)
return _inner.GetFrameIndex(time);
}
public void Dispose()
{
if (Interlocked.Exchange(ref _disposed, 1) != 0)
return;
lock (_gate)
{
_output.Dispose();
_switchEffect.SetInput(0, null, true);
_switchEffect.Dispose();
_inner.Dispose();
if (_retiredSources is { } retired)
{
foreach (var source in retired)
source.Dispose();
retired.Clear();
}
}
var orphan = _pendingUpgrade;
if (orphan is not null)
{
_pendingUpgrade = null;
orphan.Dispose();
}
GC.SuppressFinalize(this);
}
}