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の両方で利用するため各ファイルに定義しました。
152 行
5.5 KiB
C#
152 行
5.5 KiB
C#
using System.IO;
|
|
using Windows.Media.MediaProperties;
|
|
using Windows.Media.Transcoding;
|
|
using Windows.Storage;
|
|
using ZeroDiskProxy.Memory;
|
|
using ZeroDiskProxy.Progress;
|
|
|
|
namespace ZeroDiskProxy.Core;
|
|
|
|
internal sealed class MfProxyEncoder : IProxyEncoder
|
|
{
|
|
private readonly MemoryBudget _memoryBudget;
|
|
private readonly string _fallbackDirectory;
|
|
private int _disposed;
|
|
|
|
internal MfProxyEncoder(MemoryBudget memoryBudget, string fallbackDirectory)
|
|
{
|
|
_memoryBudget = memoryBudget;
|
|
_fallbackDirectory = fallbackDirectory;
|
|
}
|
|
|
|
public async Task<ProxyCacheEntry> EncodeAsync(
|
|
string inputPath, float scale, float bitrateFactor, int gopSize,
|
|
ProxyGenerationItem? progressItem, CancellationToken cancellationToken)
|
|
{
|
|
ObjectDisposedException.ThrowIf(Volatile.Read(ref _disposed) != 0, this);
|
|
|
|
Directory.CreateDirectory(_fallbackDirectory);
|
|
var tempFileName = string.Concat("zdp_", Guid.NewGuid().ToString("N"), ".mp4");
|
|
var tempPath = Path.Combine(_fallbackDirectory, tempFileName);
|
|
ProxyCacheEntry? entry = null;
|
|
|
|
try
|
|
{
|
|
cancellationToken.ThrowIfCancellationRequested();
|
|
|
|
var inputFile = await StorageFile.GetFileFromPathAsync(inputPath);
|
|
var outputFolder = await StorageFolder.GetFolderFromPathAsync(_fallbackDirectory);
|
|
var outputFile = await outputFolder.CreateFileAsync(tempFileName, CreationCollisionOption.ReplaceExisting);
|
|
|
|
var sourceProfile = await MediaEncodingProfile.CreateFromFileAsync(inputFile);
|
|
uint origWidth = sourceProfile?.Video?.Width ?? 1920u;
|
|
uint origHeight = sourceProfile?.Video?.Height ?? 1080u;
|
|
if (origWidth == 0) origWidth = 1920;
|
|
if (origHeight == 0) origHeight = 1080;
|
|
|
|
double fps = 30.0;
|
|
if (sourceProfile?.Video?.FrameRate is { Numerator: > 0, Denominator: > 0 } fr)
|
|
fps = (double)fr.Numerator / fr.Denominator;
|
|
|
|
var proxyWidth = AlignTo16((uint)(origWidth * scale));
|
|
var proxyHeight = AlignTo16((uint)(origHeight * scale));
|
|
|
|
var profile = MediaEncodingProfile.CreateMp4(VideoEncodingQuality.Auto);
|
|
profile.Video = VideoEncodingProperties.CreateH264();
|
|
profile.Video.Width = proxyWidth;
|
|
profile.Video.Height = proxyHeight;
|
|
profile.Video.Bitrate = Math.Max((uint)(proxyWidth * proxyHeight * fps * 0.07 * bitrateFactor), 100_000u);
|
|
profile.Video.FrameRate.Numerator = (uint)Math.Max(1, Math.Round(fps));
|
|
profile.Video.FrameRate.Denominator = 1;
|
|
profile.Audio = null;
|
|
|
|
cancellationToken.ThrowIfCancellationRequested();
|
|
|
|
var transcoder = new MediaTranscoder
|
|
{
|
|
HardwareAccelerationEnabled = true,
|
|
VideoProcessingAlgorithm = MediaVideoProcessingAlgorithm.Default
|
|
};
|
|
|
|
var prepResult = await transcoder.PrepareFileTranscodeAsync(inputFile, outputFile, profile);
|
|
|
|
if (!prepResult.CanTranscode)
|
|
{
|
|
transcoder.HardwareAccelerationEnabled = false;
|
|
prepResult = await transcoder.PrepareFileTranscodeAsync(inputFile, outputFile, profile);
|
|
}
|
|
|
|
if (!prepResult.CanTranscode)
|
|
throw new InvalidOperationException(string.Concat("Transcode failed: ", prepResult.FailureReason.ToString()));
|
|
|
|
cancellationToken.ThrowIfCancellationRequested();
|
|
|
|
var transcodeOp = prepResult.TranscodeAsync();
|
|
|
|
if (progressItem is not null)
|
|
{
|
|
transcodeOp.Progress = static (_, pct) => { };
|
|
transcodeOp.Progress = (_, pct) =>
|
|
{
|
|
var p = Math.Min(99.0, pct);
|
|
System.Windows.Application.Current?.Dispatcher.BeginInvoke(
|
|
System.Windows.Threading.DispatcherPriority.Background,
|
|
() => { progressItem.Progress = p; });
|
|
};
|
|
}
|
|
|
|
using var reg = cancellationToken.Register(static state => ((Windows.Foundation.IAsyncOperationWithProgress<TranscodeFailureReason, double>)state!).Cancel(), transcodeOp);
|
|
await transcodeOp;
|
|
|
|
float effectiveScale = (float)proxyWidth / origWidth;
|
|
entry = new ProxyCacheEntry(inputPath, effectiveScale)
|
|
{
|
|
ProxyWidth = proxyWidth,
|
|
ProxyHeight = proxyHeight
|
|
};
|
|
|
|
var fileSize = new FileInfo(tempPath).Length;
|
|
if (_memoryBudget.CanAllocateInMemory(fileSize))
|
|
{
|
|
var data = await File.ReadAllBytesAsync(tempPath, cancellationToken);
|
|
_memoryBudget.RecordAllocation(data.Length);
|
|
entry.SetMemoryData(data);
|
|
TryDeleteFile(tempPath);
|
|
}
|
|
else
|
|
{
|
|
entry.SetDiskPath(tempPath);
|
|
}
|
|
|
|
return entry;
|
|
}
|
|
catch
|
|
{
|
|
entry?.Dispose();
|
|
TryDeleteFile(tempPath);
|
|
throw;
|
|
}
|
|
}
|
|
|
|
private static uint AlignTo16(uint value)
|
|
{
|
|
var aligned = (value + 15u) & ~15u;
|
|
return aligned < 16u ? 16u : aligned;
|
|
}
|
|
|
|
private static void TryDeleteFile(string path)
|
|
{
|
|
try
|
|
{
|
|
if (File.Exists(path))
|
|
File.Delete(path);
|
|
}
|
|
catch { }
|
|
}
|
|
|
|
public void Dispose()
|
|
{
|
|
Interlocked.Exchange(ref _disposed, 1);
|
|
}
|
|
}
|