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)を直接呼ぶロックフリーパスを追加し、アップグレード完了後の長期再生中に不要なロック取得を排除しました。
158 行
4.5 KiB
C#
158 行
4.5 KiB
C#
using System.Diagnostics;
|
|
using System.IO;
|
|
|
|
namespace ZeroDiskProxy.Memory;
|
|
|
|
internal sealed class FallbackStream : Stream
|
|
{
|
|
private Stream _inner;
|
|
private readonly MemoryBudget _budget;
|
|
private readonly string _fallbackDir;
|
|
private string? _fallbackPath;
|
|
private volatile bool _isFallenBack;
|
|
private int _disposed;
|
|
private readonly object _switchLock = new();
|
|
|
|
internal bool IsFallenBack => _isFallenBack;
|
|
|
|
internal FallbackStream(MemoryBudget budget, string fallbackDirectory, int initialCapacity = 4096)
|
|
{
|
|
_budget = budget;
|
|
_fallbackDir = fallbackDirectory;
|
|
_inner = new MemoryStream(initialCapacity);
|
|
}
|
|
|
|
public override bool CanRead => _inner.CanRead;
|
|
public override bool CanSeek => _inner.CanSeek;
|
|
public override bool CanWrite => !IsDisposed && _inner.CanWrite;
|
|
public override long Length => _inner.Length;
|
|
|
|
public override long Position
|
|
{
|
|
get => _inner.Position;
|
|
set => _inner.Position = value;
|
|
}
|
|
|
|
private bool IsDisposed => Volatile.Read(ref _disposed) != 0;
|
|
|
|
public override void Flush() => _inner.Flush();
|
|
public override int Read(byte[] buffer, int offset, int count) => _inner.Read(buffer, offset, count);
|
|
public override long Seek(long offset, SeekOrigin origin) => _inner.Seek(offset, origin);
|
|
public override void SetLength(long value) => _inner.SetLength(value);
|
|
|
|
public override void Write(byte[] buffer, int offset, int count)
|
|
{
|
|
if (_isFallenBack)
|
|
{
|
|
_inner.Write(buffer, offset, count);
|
|
return;
|
|
}
|
|
|
|
lock (_switchLock)
|
|
{
|
|
if (!_isFallenBack && !_budget.CanAllocateInMemory(_inner.Position + count))
|
|
SwitchToDiskCore();
|
|
_inner.Write(buffer, offset, count);
|
|
}
|
|
}
|
|
|
|
internal byte[] ToArray()
|
|
{
|
|
lock (_switchLock)
|
|
{
|
|
if (_inner is MemoryStream ms)
|
|
return ms.ToArray();
|
|
|
|
var pos = _inner.Position;
|
|
_inner.Position = 0;
|
|
var result = new byte[_inner.Length];
|
|
int totalRead = 0;
|
|
while (totalRead < result.Length)
|
|
{
|
|
int read = _inner.Read(result, totalRead, result.Length - totalRead);
|
|
if (read == 0)
|
|
break;
|
|
totalRead += read;
|
|
}
|
|
_inner.Position = pos;
|
|
return result;
|
|
}
|
|
}
|
|
|
|
internal string? TransferDiskOwnership()
|
|
{
|
|
lock (_switchLock)
|
|
{
|
|
if (!_isFallenBack || _fallbackPath is null)
|
|
return null;
|
|
|
|
var path = _fallbackPath;
|
|
_fallbackPath = null;
|
|
return path;
|
|
}
|
|
}
|
|
|
|
private void SwitchToDiskCore()
|
|
{
|
|
if (_isFallenBack)
|
|
return;
|
|
|
|
try
|
|
{
|
|
Directory.CreateDirectory(_fallbackDir);
|
|
|
|
Span<char> nameBuf = stackalloc char[40];
|
|
"zdp_".AsSpan().CopyTo(nameBuf);
|
|
Guid.NewGuid().TryFormat(nameBuf[4..], out _, "N");
|
|
".tmp".AsSpan().CopyTo(nameBuf[36..]);
|
|
var path = Path.Combine(_fallbackDir, new string(nameBuf));
|
|
|
|
var fileStream = new FileStream(path, FileMode.Create, FileAccess.ReadWrite, FileShare.Read, 65536);
|
|
|
|
var oldStream = _inner;
|
|
var position = oldStream.Position;
|
|
oldStream.Position = 0;
|
|
oldStream.CopyTo(fileStream);
|
|
fileStream.Position = position;
|
|
|
|
var memLength = oldStream.Length;
|
|
_inner = fileStream;
|
|
_fallbackPath = path;
|
|
_isFallenBack = true;
|
|
|
|
oldStream.Dispose();
|
|
_budget.RecordDeallocation(memLength);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
Debug.WriteLine(string.Concat("[FallbackStream] Disk fallback failed: ", ex.Message));
|
|
}
|
|
}
|
|
|
|
protected override void Dispose(bool disposing)
|
|
{
|
|
if (Interlocked.Exchange(ref _disposed, 1) != 0)
|
|
return;
|
|
|
|
if (disposing)
|
|
{
|
|
lock (_switchLock)
|
|
{
|
|
var length = _inner.Length;
|
|
_inner.Dispose();
|
|
|
|
if (!_isFallenBack)
|
|
_budget.RecordDeallocation(length);
|
|
|
|
if (_fallbackPath is not null)
|
|
{
|
|
try { File.Delete(_fallbackPath); }
|
|
catch { }
|
|
_fallbackPath = null;
|
|
}
|
|
}
|
|
}
|
|
|
|
base.Dispose(disposing);
|
|
}
|
|
} |