ファイル
YMM4-ProxyForge/ZeroDiskProxy/Core/MfProxyEncoder.cs
T
routersys 67a4e24c34 インターフェース層新設とMemoryBudget競合状態修正によるアーキテクチャ改善
依存性逆転の原則に基づくインターフェース層を新設し、具象クラスへの直接依存を排除しました。
MemoryBudgetのメモリ確保処理をCASループによるアトミック操作に置き換え競合状態を修正しました。
GOPサイズがエンコード設定に実際に反映されていなかった問題を修正しました。
ZeroDiskProxy/Interfaces/ディレクトリを新設し、IProxyEncoder・IProxyEncoderFactory・IExportDetectorの3インターフェースを追加しました。
IProxyEncoderはZeroDiskProxy/Core/からZeroDiskProxy/Interfaces/へ移動し名前空間を変更しました。
ExportDetectorをstaticクラスからsealedインスタンスクラスへ変更しIExportDetectorを実装しました。
_lastExportState・_lastCheckTicksのstaticフィールドをインスタンスフィールドへ変更しました。
IsExporting()・Reset()メソッドのアクセス修飾子をinternalからpublicに変更しインターフェース実装に対応させました。
ZeroDiskProxyPluginでのExportDetector.IsExporting()の直接呼び出しをhost.ExportDetector.IsExporting()に変更しました。
ProxyCacheManagerのFunc<IProxyEncoder>ラムダをファクトリオブジェクトに置き換えるためMfProxyEncoderFactoryクラスを新規追加しました。
ProxyCacheManagerのコンストラクタ引数をFunc<IProxyEncoder>からIProxyEncoderFactoryに変更し_encoderFactory()の呼び出しを_encoderFactory.Create()に変更しました。
PluginHostのコンストラクタを依存性を外部から注入できる形式に変更しました。
ファクトリメソッドCreateDefault()を追加しResourceRegistry・MemoryBudget・MfProxyEncoderFactory・ExportDetectorの生成と組み立てを集約しました。
IExportDetectorをプロパティとして公開し外部からのモック置換を可能にしました。
EnsureInitialized()は引き続きCreateDefault()を呼び出すため既存動作を維持しました。
CanAllocateInMemory()メソッドの判定ロジックに_allocatedBytesを考慮した上限チェックを追加しました。
TryAllocate()メソッドを新規追加しInterlocked.CompareExchangeによるCASループで確保と記録をアトミックに一体化しました。
MfProxyEncoderでのCanAllocateInMemory()呼び出しをTryAllocate()に置き換え、確保成功後にファイル読み込みが失敗した場合はRecordDeallocation()でロールバックするようにしました。
ファイルサイズと実際の読み込みバイト数の差分をdeltaとして計算し過不足を補正するようにしました。
MfProxyEncoderでプロファイル生成時にMF_MT_MAX_KEYFRAME_SPACINGプロパティをgopSizeの値で設定するよう修正しました。
MfGuidsにMF_MT_MAX_KEYFRAME_SPACINGのGUID定数を追加しました。
これにより設定UIで指定したGOPサイズが実際のエンコードに反映されるようになりました。
2026-03-24 10:43:31 +09:00

167 行
6.0 KiB
C#

using System.IO;
using Windows.Media.MediaProperties;
using Windows.Media.Transcoding;
using Windows.Storage;
using ZeroDiskProxy.Interfaces;
using ZeroDiskProxy.Interop;
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.Video.Properties[MfGuids.MF_MT_MAX_KEYFRAME_SPACING] = (uint)Math.Max(1, gopSize);
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.TryAllocate(fileSize))
{
try
{
var data = await File.ReadAllBytesAsync(tempPath, cancellationToken);
var delta = data.LongLength - fileSize;
if (delta > 0)
_memoryBudget.RecordAllocation(delta);
else if (delta < 0)
_memoryBudget.RecordDeallocation(-delta);
entry.SetMemoryData(data);
TryDeleteFile(tempPath);
}
catch
{
_memoryBudget.RecordDeallocation(fileSize);
throw;
}
}
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);
}
}