IProxyEncoderインターフェースを定義し、Windows.Media.TranscodeをラップしたMediaFoundation実装であるMfProxyEncoderを追加しました。 ハードウェアアクセラレーションを優先し、失敗時はソフトウェアエンコードへ自動フォールバックします。 解像度を16アライメントに揃え、ビットレートをフレームサイズとfpsから動的算出します。 エンコード完了後にメモリ予算を確認し、容量が十分な場合はRAMに、不足する場合は一時ファイルとしてディスクに保存します。 ProxyCacheEntryはメモリとディスクの双方を透過的に扱うキャッシュエントリで、OpenReadStream()により格納場所を意識せずストリームを取得できます。 ProxyCacheManagerはConcurrentDictionaryによりスレッドセーフなエントリ管理を行い、生成中タスクの重複起動防止、進捗通知、エラー処理を一括管理します。 完了・キャンセル・失敗の各状態に応じてUIへのDispatchタイミングと自動除去遅延を個別に設定しています。 MemoryBudgetはGlobalMemoryStatusExで実際の空き物理メモリを取得し、指定予約量との差分でインメモリ格納可否を判定します。 FallbackStreamはMemoryStreamとして書き込みを開始し、メモリ残量不足を検知した時点でFileStreamへ透過的に切り替えるハイブリッドストリームです。 BufferPoolはArrayPool<byte>をラップし、大容量バッファの再利用によるGC負荷軽減を行います。 MfNativeMethodsにmfplat.dllおよびmfreadwrite.dllのP/Invoke宣言をまとめました。 MfRuntimeは参照カウント方式でMFStartup/MFShutdownのライフサイクルを安全に管理します。 ManagedIStreamはSystem.StreamをCOM IStreamとして公開するアダプタです。 HResultExtensionsはHRESULTをE_OUTOFMEMORYやE_NOTIMPLなど意味のある例外型にマッピングします。 MfGuidsおよびMfConstantsにMediaFoundation定数を集約しました。 ZeroDiskProxyPluginはIVideoFileSourcePluginを実装し、エクスポート検出・ファイルサイズ閾値判定・プロキシキャッシュヒット確認・自動生成開始の一連の処理フローを担います。 ZeroDiskProxyVideoSourceはDirect2D AffineTransform2Dエフェクトを用いてオリジナル動画ソースとプロキシソースを実行時にホットスワップする機構を持ちます。 ZeroDiskProxyVideoSourceWithScaleはプロキシのスケール差分をAffineTransform2Dで補正し、本来の解像度として上位レイヤに提示します。 PluginHostはシングルトンとしてProxyCacheManager・MemoryBudget・ResourceRegistryを統括し、進捗ポップアップの表示制御とアプリ終了時のクリーンアップを行います。 ExportDetectorはEnumWindowsでプロセス内ウィンドウを列挙し、出力進捗ウィンドウや動画書き出しウィンドウのタイトルを検知してエクスポート中かどうかを判定します。 2秒間のキャッシュにより頻繁な呼び出しでもAPI負荷を抑制します。 ResourceRegistryはCOMポインタとIDisposableを統一的に追跡するIDベースのレジストリです。 ResourceHandleはIDisposableとして登録解除を行うRAIIラッパーです。 ZeroDiskProxySettingsはSettingsBase継承によりJSON永続化と設定UIの自動連携を実現します。 解像度スケール・ビットレート係数・GOPサイズ・メモリ予約量・最大キャッシュメモリ・ハードウェアアクセラレーション・CPUコア数・ディスクフォールバック・自動生成・終了時クリアの各パラメータをClampで安全に管理します。 ZeroDiskProxySettingsViewは基本設定・品質設定・メモリ設定・自動化設定・詳細設定・キャッシュ管理の6セクションをExpanderで構成した設定UIです。 GenerationPopupViewはプロキシ生成中のファイル名・進捗バー・ステータス・格納先を一覧表示する非モーダルウィンドウで、ウィンドウ右下に自動配置されます。 SettingsViewModelはキャッシュ一覧の取得・個別削除・全削除・表示更新コマンドを提供します。 GenerationPopupViewModelはObservableCollectionの変更を監視してHasItemsプロパティを自動更新します。 ProxyGenerationItemはファイル名・進捗率・経過時間・ステータス・格納先種別をBindableとして公開します。 InvertBoolToVisibilityConverterをGenerationPopupViewとSettingsViewの両方で利用するため各ファイルに定義しました。
147 行
4.3 KiB
C#
147 行
4.3 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 && !_budget.CanAllocateInMemory(_inner.Position + count))
|
|
SwitchToDisk();
|
|
_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 SwitchToDisk()
|
|
{
|
|
lock (_switchLock)
|
|
{
|
|
if (_isFallenBack)
|
|
return;
|
|
|
|
try
|
|
{
|
|
Directory.CreateDirectory(_fallbackDir);
|
|
var path = Path.Combine(_fallbackDir, string.Concat("zdp_", Guid.NewGuid().ToString("N"), ".tmp"));
|
|
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);
|
|
}
|
|
}
|