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)を直接呼ぶロックフリーパスを追加し、アップグレード完了後の長期再生中に不要なロック取得を排除しました。
116 行
3.5 KiB
C#
116 行
3.5 KiB
C#
using System.Diagnostics;
|
|
using System.Runtime.InteropServices;
|
|
|
|
namespace ZeroDiskProxy.Memory;
|
|
|
|
internal sealed class MemoryBudget
|
|
{
|
|
private readonly long _reserveBytes;
|
|
private readonly long _maxCacheBytes;
|
|
private long _allocatedBytes;
|
|
|
|
private long _cachedAvailableMemory;
|
|
private long _memoryCacheTimestamp;
|
|
private static readonly long MemoryCacheTicks = Stopwatch.Frequency / 10;
|
|
|
|
internal MemoryBudget(long reserveMb, long maxCacheMb)
|
|
{
|
|
_reserveBytes = reserveMb * 1024L * 1024L;
|
|
_maxCacheBytes = maxCacheMb * 1024L * 1024L;
|
|
}
|
|
|
|
internal long AllocatedBytes => Volatile.Read(ref _allocatedBytes);
|
|
|
|
internal bool CanAllocateInMemory(long requestedBytes)
|
|
{
|
|
if (requestedBytes <= 0)
|
|
return true;
|
|
|
|
var limit = Math.Min(GetCachedAvailablePhysicalMemory() - _reserveBytes, _maxCacheBytes);
|
|
if (limit <= 0)
|
|
return false;
|
|
|
|
var allocated = Volatile.Read(ref _allocatedBytes);
|
|
return allocated >= 0 && requestedBytes <= limit - allocated;
|
|
}
|
|
|
|
internal bool TryAllocate(long requestedBytes)
|
|
{
|
|
if (requestedBytes <= 0)
|
|
return true;
|
|
|
|
while (true)
|
|
{
|
|
var available = GetCachedAvailablePhysicalMemory();
|
|
var current = Volatile.Read(ref _allocatedBytes);
|
|
if (current < 0)
|
|
return false;
|
|
|
|
var limit = Math.Min(available - _reserveBytes, _maxCacheBytes);
|
|
if (limit <= 0)
|
|
return false;
|
|
|
|
var next = current + requestedBytes;
|
|
if (next < 0 || next > limit)
|
|
return false;
|
|
|
|
if (Interlocked.CompareExchange(ref _allocatedBytes, next, current) == current)
|
|
return true;
|
|
}
|
|
}
|
|
|
|
internal void RecordAllocation(long bytes)
|
|
{
|
|
if (bytes > 0)
|
|
Interlocked.Add(ref _allocatedBytes, bytes);
|
|
}
|
|
|
|
internal void RecordDeallocation(long bytes)
|
|
{
|
|
if (bytes > 0)
|
|
Interlocked.Add(ref _allocatedBytes, -bytes);
|
|
}
|
|
|
|
internal static long EstimateProxySize(long originalFileSize, float scale)
|
|
=> (long)(originalFileSize * scale * scale * 0.3);
|
|
|
|
private long GetCachedAvailablePhysicalMemory()
|
|
{
|
|
var now = Stopwatch.GetTimestamp();
|
|
if (now - Volatile.Read(ref _memoryCacheTimestamp) < MemoryCacheTicks)
|
|
{
|
|
var cached = Volatile.Read(ref _cachedAvailableMemory);
|
|
if (cached > 0)
|
|
return cached;
|
|
}
|
|
|
|
var fresh = GetAvailablePhysicalMemory();
|
|
Volatile.Write(ref _cachedAvailableMemory, fresh);
|
|
Volatile.Write(ref _memoryCacheTimestamp, now);
|
|
return fresh;
|
|
}
|
|
|
|
[StructLayout(LayoutKind.Sequential)]
|
|
private struct MEMORYSTATUSEX
|
|
{
|
|
public uint dwLength;
|
|
public uint dwMemoryLoad;
|
|
public ulong ullTotalPhys;
|
|
public ulong ullAvailPhys;
|
|
public ulong ullTotalPageFile;
|
|
public ulong ullAvailPageFile;
|
|
public ulong ullTotalVirtual;
|
|
public ulong ullAvailVirtual;
|
|
public ulong ullAvailExtendedVirtual;
|
|
}
|
|
|
|
[DllImport("kernel32.dll", SetLastError = true)]
|
|
[return: MarshalAs(UnmanagedType.Bool)]
|
|
private static extern bool GlobalMemoryStatusEx(ref MEMORYSTATUSEX lpBuffer);
|
|
|
|
private static long GetAvailablePhysicalMemory()
|
|
{
|
|
var status = new MEMORYSTATUSEX { dwLength = (uint)Marshal.SizeOf<MEMORYSTATUSEX>() };
|
|
return GlobalMemoryStatusEx(ref status) ? (long)status.ullAvailPhys : 2L * 1024 * 1024 * 1024;
|
|
}
|
|
} |