ファイル
YMM4-ProxyForge/ZeroDiskProxy/Memory/MemoryBudget.cs
T
routersys ff929da7a0 不要なMF相互運用ファイル削除とコード全体のリファクタリング
未使用のMFインターロップファイルを削除しました。
MfProxyEncoderのトランスコード進捗報告処理をTranscodeProgressReporterクラスに抽出しました。
キャンセル登録の型をIAsyncOperationWithProgressからIAsyncActionWithProgressに修正しました。
MfProxyEncoderFactory・MemoryBudget・PooledMemoryStream・CacheEntryViewModel等をプライマリコンストラクタ構文に変換しました。
ProxyCacheManagerのCacheKeyをrecord structに変換し、Equalsのオーバーライドを整理しました。
PooledBufferをmutableなstructに変更し、Interlocked.Exchangeによるスレッドセーフなディスポーズを実装しました。
FallbackStreamにRead(Span<byte>)・Write(ReadOnlySpan<byte>)・WriteAsyncの各オーバーロードを追加しました。
MemoryBudgetのTickCountを32ビットuintにキャストし、ラッピング演算の整合性を修正しました。
GetAllSnapshotsをList<T>ベースに変更し、配列の事前確保とArray.Resizeを除去しました。
ZeroDiskProxyVideoSourceのUpgrade適用ロジックをTryApplyUpgradeメソッドとして抽出しました。
ProxyGenerationItem・ByteFormatter・CacheEntryViewModelの文字列生成をstring.Createと補間文字列に統一しました。
PluginHostからResourceRegistryへの依存を取り除き、関連するDispose呼び出しを削除しました。
CheckExportWindowにDebug.Assertを追加し、スレッドプールの非同期継続から呼ばれた場合の前提条件違反を検出できるようにしました。
ClearAllのforeachでデコンストラクション構文をkeyプロパティの明示的な参照に変更しました。
CreateCoreメソッドをインスタンスメンバーからstaticメソッドに変更しました。
パターンマッチングをis { IsLoaded: true }・is { IsValid: true }形式に統一しました。
2026-03-24 17:09:37 +09:00

114 行
3.6 KiB
C#

using System.Runtime.InteropServices;
namespace ZeroDiskProxy.Memory;
internal sealed class MemoryBudget(long reserveMb, long maxCacheMb)
{
private readonly long _reserveBytes = reserveMb * 1024L * 1024L;
private readonly long _maxCacheBytes = maxCacheMb * 1024L * 1024L;
private long _allocatedBytes;
private long _memoryCachePacked;
private const long MemoryCacheIntervalMs = 100L;
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 static uint WrapSafeElapsedMs(uint nowMs, uint cachedMs) =>
unchecked(nowMs - cachedMs);
private long GetCachedAvailablePhysicalMemory()
{
var nowMs = (uint)Environment.TickCount64;
var packed = Interlocked.Read(ref _memoryCachePacked);
var cachedMs = (uint)(packed >> 32);
if (WrapSafeElapsedMs(nowMs, cachedMs) < (uint)MemoryCacheIntervalMs)
{
var memKb = (uint)packed;
if (memKb > 0)
return (long)memKb * 1024L;
}
var fresh = GetAvailablePhysicalMemory();
var freshKbCapped = (uint)Math.Min(fresh >> 10, (long)uint.MaxValue);
Interlocked.Exchange(ref _memoryCachePacked, ((long)nowMs << 32) | freshKbCapped);
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;
}
}