ProxyCacheManagerのStartProxyGenerationにおいてContainsKeyとTryAddの間に存在したTOCTOU競合を除去し、TryAddの戻り値のみで重複判断するよう修正しました。 RunGenerationAsyncで3箇所に重複していたActiveGenerations.Remove呼び出しをループ後の単一パスに集約し、delayMs変数で各ケースの遅延時間を管理するよう統一しました。 FallbackStreamのWriteメソッドで_inner.Writeの呼び出しを_switchLockの内側に移動し、SwitchToDiskCoreをロック内から呼ぶ内部メソッドとして分離することでWriteとSwitchToDiskの競合を解消しました。 ProxyCacheEntryのSetMemoryDataおよびSetDiskPathにおいて旧フィールドをクリアしてから新フィールドを設定する順序に変更し、IsValidがどちらもnullという一貫性のない状態を観測しないよう保証しました。 MemoryBudgetのTryAllocateにおいてGetAvailablePhysicalMemoryの呼び出しをCASループ外からループ内に移動し、ループを複数回回る間に物理メモリの実態が変化しても常に最新の値で判断するよう修正しました。 ProxyCacheManagerのMakeCacheKeyを文字列補間からstring.Create+stackallocベースに書き換え、中間文字列アロケーションを排除しました。 SettingsViewModelとCacheEntryViewModelに重複していたFormatBytesをUtilities/ByteFormatterとして一元化し、stackallocとstring.Createを組み合わせることでアロケーションをゼロに抑えました。 IDialogServiceインターフェースとWpfDialogService実装を新規追加し、SettingsViewModelが直接呼び出していたSystem.Windows.MessageBox.Showをインターフェース経由に変更しました。 SettingsViewModelのコンストラクタをProxyCacheManagerとMemoryBudgetを直接受け取る形に変更し、PluginHost.Instanceへの直接依存を除去しました。 PluginHost.Instanceの解決はZeroDiskProxySettingsView.xaml.csのコンポジションルートで行うよう責務を整理しました。 GenerationPopupViewのOnItemsChangedからShow・Hideの呼び出しを削除し、ウィンドウ可視性の管理をPluginHost.OnGenerationsChangedに一元化しました。 MfProxyEncoderにValidateInputPathとValidateTempPathを追加し、パストラバーサル攻撃を防止しました。 ValidateTempPathはstackallocとSpan<char>を用いてゼロアロケーションで_fallbackDirectory配下であることを検証します。 ExportDetectorのウィンドウタイトルバッファを256文字から512文字に拡大し、長いウィンドウタイトルによる切り捨てを防止しました。 MfProxyEncoder.AlignTo16をprivate staticからinternal staticに変更しテスト可能にしました。 WinRT APIへの移行により不要になったMfGuids内の全GUIDを削除し、実際に参照されているMF_MT_MAX_KEYFRAME_SPACINGのみを残しました。
239 行
7.3 KiB
C#
239 行
7.3 KiB
C#
using System.Collections.Concurrent;
|
|
using System.Collections.ObjectModel;
|
|
using System.Diagnostics;
|
|
using System.Globalization;
|
|
using System.IO;
|
|
using System.Windows;
|
|
using ZeroDiskProxy.Interfaces;
|
|
using ZeroDiskProxy.Localization;
|
|
using ZeroDiskProxy.Memory;
|
|
using ZeroDiskProxy.Progress;
|
|
using ZeroDiskProxy.Settings;
|
|
|
|
namespace ZeroDiskProxy.Core;
|
|
|
|
internal sealed class ProxyCacheManager : IDisposable
|
|
{
|
|
private readonly ConcurrentDictionary<string, ProxyCacheEntry> _cache = new(StringComparer.OrdinalIgnoreCase);
|
|
private readonly ConcurrentDictionary<string, CancellationTokenSource> _pendingGenerations = new(StringComparer.Ordinal);
|
|
private readonly IProxyEncoderFactory _encoderFactory;
|
|
private readonly MemoryBudget _memoryBudget;
|
|
private int _disposed;
|
|
|
|
internal ObservableCollection<ProxyGenerationItem> ActiveGenerations { get; } = [];
|
|
internal event Action<string, ProxyCacheEntry>? ProxyCompleted;
|
|
|
|
internal ProxyCacheManager(IProxyEncoderFactory encoderFactory, MemoryBudget memoryBudget)
|
|
{
|
|
_encoderFactory = encoderFactory;
|
|
_memoryBudget = memoryBudget;
|
|
}
|
|
|
|
private static string MakeCacheKey(string path, float scale)
|
|
{
|
|
var fullPath = GetFullPath(path);
|
|
Span<char> scaleBuf = stackalloc char[16];
|
|
scale.TryFormat(scaleBuf, out int scaleLen, "F3", CultureInfo.InvariantCulture);
|
|
return string.Create(fullPath.Length + 1 + scaleLen, (fullPath, scale, scaleLen), static (span, state) =>
|
|
{
|
|
state.fullPath.AsSpan().CopyTo(span);
|
|
span[state.fullPath.Length] = '|';
|
|
state.scale.TryFormat(span[(state.fullPath.Length + 1)..], out _, "F3", CultureInfo.InvariantCulture);
|
|
});
|
|
}
|
|
|
|
private static string GetFullPath(string path)
|
|
{
|
|
try { return Path.GetFullPath(path); }
|
|
catch { return path; }
|
|
}
|
|
|
|
internal ProxyCacheEntry? TryGetProxy(string originalPath, float scale)
|
|
{
|
|
var key = MakeCacheKey(originalPath, scale);
|
|
if (_cache.TryGetValue(key, out var entry) && entry.IsValid)
|
|
return entry;
|
|
return null;
|
|
}
|
|
|
|
internal bool ProxyExists(string originalPath, float scale)
|
|
{
|
|
var key = MakeCacheKey(originalPath, scale);
|
|
return _cache.TryGetValue(key, out var entry) && entry.IsValid;
|
|
}
|
|
|
|
internal void StartProxyGeneration(string originalPath, float scale, ZeroDiskProxySettings settings)
|
|
{
|
|
if (Volatile.Read(ref _disposed) != 0)
|
|
return;
|
|
|
|
var key = MakeCacheKey(originalPath, scale);
|
|
|
|
if (_cache.TryGetValue(key, out var existing) && existing.IsValid)
|
|
return;
|
|
|
|
var cts = new CancellationTokenSource();
|
|
if (!_pendingGenerations.TryAdd(key, cts))
|
|
{
|
|
cts.Dispose();
|
|
return;
|
|
}
|
|
|
|
_ = Task.Run(() => RunGenerationAsync(key, originalPath, scale, settings, cts), CancellationToken.None);
|
|
}
|
|
|
|
private async Task RunGenerationAsync(string key, string originalPath, float scale, ZeroDiskProxySettings settings, CancellationTokenSource cts)
|
|
{
|
|
var progressItem = new ProxyGenerationItem(originalPath);
|
|
DispatchInvoke(() => ActiveGenerations.Add(progressItem));
|
|
|
|
int delayMs = 2000;
|
|
|
|
try
|
|
{
|
|
using var encoder = _encoderFactory.Create();
|
|
var entry = await encoder.EncodeAsync(
|
|
originalPath, scale, settings.BitrateFactor / 100f, settings.GopSize,
|
|
progressItem, cts.Token);
|
|
|
|
var stored = _cache.GetOrAdd(key, entry);
|
|
if (!ReferenceEquals(stored, entry))
|
|
{
|
|
_memoryBudget.RecordDeallocation(entry.DataSize);
|
|
entry.Dispose();
|
|
}
|
|
|
|
var isInMem = stored.IsInMemory;
|
|
DispatchInvoke(() =>
|
|
{
|
|
progressItem.Progress = 100;
|
|
progressItem.IsCompleted = true;
|
|
progressItem.StatusMessage = Translate.ProxyGenerationStatusCompleted;
|
|
progressItem.IsInMemory = isInMem;
|
|
});
|
|
|
|
ProxyCompleted?.Invoke(originalPath, stored);
|
|
}
|
|
catch (OperationCanceledException)
|
|
{
|
|
delayMs = 3000;
|
|
DispatchInvoke(() =>
|
|
{
|
|
progressItem.StatusMessage = Translate.ProxyGenerationStatusCanceled;
|
|
progressItem.IsFailed = true;
|
|
});
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
delayMs = 8000;
|
|
var msg = ex.Message;
|
|
Debug.WriteLine(string.Concat("[ZeroDiskProxy] Proxy generation failed for ", originalPath, ": ", ex));
|
|
DispatchInvoke(() =>
|
|
{
|
|
progressItem.StatusMessage = string.Concat(Translate.ProxyGenerationStatusFailedPrefix, msg);
|
|
progressItem.IsFailed = true;
|
|
});
|
|
}
|
|
finally
|
|
{
|
|
_pendingGenerations.TryRemove(key, out _);
|
|
cts.Dispose();
|
|
}
|
|
|
|
await Task.Delay(delayMs, CancellationToken.None);
|
|
DispatchInvoke(() => ActiveGenerations.Remove(progressItem));
|
|
}
|
|
|
|
private static void DispatchInvoke(Action action)
|
|
{
|
|
var app = Application.Current;
|
|
if (app is null)
|
|
return;
|
|
|
|
if (app.Dispatcher.CheckAccess())
|
|
action();
|
|
else
|
|
app.Dispatcher.Invoke(action);
|
|
}
|
|
|
|
internal void RemoveProxy(string originalPath, float scale)
|
|
{
|
|
var key = MakeCacheKey(originalPath, scale);
|
|
if (!_cache.TryRemove(key, out var entry))
|
|
return;
|
|
|
|
var size = entry.DataSize;
|
|
entry.Dispose();
|
|
_memoryBudget.RecordDeallocation(size);
|
|
}
|
|
|
|
internal (int count, long totalSize) ClearAll()
|
|
{
|
|
foreach (var key in _pendingGenerations.Keys.ToArray())
|
|
{
|
|
if (_pendingGenerations.TryRemove(key, out var cts))
|
|
{
|
|
try { cts.Cancel(); cts.Dispose(); }
|
|
catch { }
|
|
}
|
|
}
|
|
|
|
long totalSize = 0;
|
|
int count = 0;
|
|
foreach (var key in _cache.Keys.ToArray())
|
|
{
|
|
if (_cache.TryRemove(key, out var entry))
|
|
{
|
|
totalSize += entry.DataSize;
|
|
entry.Dispose();
|
|
count++;
|
|
}
|
|
}
|
|
|
|
_memoryBudget.RecordDeallocation(totalSize);
|
|
return (count, totalSize);
|
|
}
|
|
|
|
internal CacheEntrySnapshot[] GetAllSnapshots()
|
|
{
|
|
var values = _cache.Values;
|
|
var result = new List<CacheEntrySnapshot>(values.Count);
|
|
foreach (var e in values)
|
|
{
|
|
if (e.IsValid)
|
|
result.Add(e.CreateSnapshot());
|
|
}
|
|
return result.ToArray();
|
|
}
|
|
|
|
internal (int entryCount, long memSize, long diskSize, int memCount, int diskCount) GetCacheInfo()
|
|
{
|
|
long ms = 0, ds = 0;
|
|
int mc = 0, dc = 0;
|
|
foreach (var e in _cache.Values)
|
|
{
|
|
if (!e.IsValid)
|
|
continue;
|
|
|
|
if (e.IsInMemory)
|
|
{
|
|
ms += e.DataSize;
|
|
mc++;
|
|
}
|
|
else
|
|
{
|
|
ds += e.DataSize;
|
|
dc++;
|
|
}
|
|
}
|
|
return (_cache.Count, ms, ds, mc, dc);
|
|
}
|
|
|
|
public void Dispose()
|
|
{
|
|
if (Interlocked.Exchange(ref _disposed, 1) != 0)
|
|
return;
|
|
|
|
ClearAll();
|
|
}
|
|
} |