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)を直接呼ぶロックフリーパスを追加し、アップグレード完了後の長期再生中に不要なロック取得を排除しました。
225 行
8.6 KiB
C#
225 行
8.6 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 readonly EncoderConfig _config;
|
|
private int _disposed;
|
|
|
|
internal MfProxyEncoder(MemoryBudget memoryBudget, string fallbackDirectory, EncoderConfig config)
|
|
{
|
|
_memoryBudget = memoryBudget;
|
|
_fallbackDirectory = fallbackDirectory;
|
|
_config = config;
|
|
}
|
|
|
|
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);
|
|
ValidateInputPath(inputPath);
|
|
|
|
Directory.CreateDirectory(_fallbackDirectory);
|
|
|
|
Span<char> fileNameBuf = stackalloc char[40];
|
|
"zdp_".AsSpan().CopyTo(fileNameBuf);
|
|
Guid.NewGuid().TryFormat(fileNameBuf[4..], out _, "N");
|
|
".mp4".AsSpan().CopyTo(fileNameBuf[36..]);
|
|
var tempFileName = new string(fileNameBuf);
|
|
|
|
var tempPath = Path.Combine(_fallbackDirectory, tempFileName);
|
|
ValidateTempPath(tempPath);
|
|
|
|
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 = _config.EnableHardwareAcceleration,
|
|
VideoProcessingAlgorithm = MediaVideoProcessingAlgorithm.Default
|
|
};
|
|
|
|
var prepResult = await transcoder.PrepareFileTranscodeAsync(inputFile, outputFile, profile);
|
|
|
|
if (!prepResult.CanTranscode && _config.EnableHardwareAcceleration)
|
|
{
|
|
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)
|
|
{
|
|
long lastReportedCenti = 0;
|
|
Action dispatchAction = progressItem.ApplyPendingProgress;
|
|
transcodeOp.Progress = (_, pct) =>
|
|
{
|
|
var p = Math.Min(99.0, pct);
|
|
var centi = (long)(p * 100);
|
|
var prev = Volatile.Read(ref lastReportedCenti);
|
|
if (centi - prev < 100 && p < 99.0)
|
|
return;
|
|
Volatile.Write(ref lastReportedCenti, centi);
|
|
progressItem.SetPendingProgress(p);
|
|
System.Windows.Application.Current?.Dispatcher.BeginInvoke(
|
|
System.Windows.Threading.DispatcherPriority.Background,
|
|
dispatchAction);
|
|
};
|
|
}
|
|
|
|
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))
|
|
{
|
|
byte[]? rented = null;
|
|
try
|
|
{
|
|
await using var readStream = new FileStream(
|
|
tempPath, FileMode.Open, FileAccess.Read, FileShare.Read,
|
|
65536, FileOptions.SequentialScan | FileOptions.Asynchronous);
|
|
var exactSize = (int)readStream.Length;
|
|
rented = BufferPool.Rent(exactSize);
|
|
int totalRead = 0;
|
|
while (totalRead < exactSize)
|
|
{
|
|
int read = await readStream.ReadAsync(rented.AsMemory(totalRead, exactSize - totalRead), cancellationToken);
|
|
if (read == 0)
|
|
break;
|
|
totalRead += read;
|
|
}
|
|
|
|
var delta = (long)totalRead - fileSize;
|
|
if (delta > 0)
|
|
_memoryBudget.RecordAllocation(delta);
|
|
else if (delta < 0)
|
|
_memoryBudget.RecordDeallocation(-delta);
|
|
|
|
entry.SetMemoryData(rented, totalRead);
|
|
rented = null;
|
|
TryDeleteFile(tempPath);
|
|
}
|
|
catch
|
|
{
|
|
if (rented is not null)
|
|
BufferPool.Return(rented);
|
|
_memoryBudget.RecordDeallocation(fileSize);
|
|
throw;
|
|
}
|
|
}
|
|
else if (_config.EnableDiskFallback)
|
|
{
|
|
entry.SetDiskPath(tempPath, fileSize);
|
|
}
|
|
else
|
|
{
|
|
throw new InvalidOperationException("Insufficient memory for proxy and disk fallback is disabled.");
|
|
}
|
|
|
|
return entry;
|
|
}
|
|
catch
|
|
{
|
|
entry?.Dispose();
|
|
TryDeleteFile(tempPath);
|
|
throw;
|
|
}
|
|
}
|
|
|
|
internal static uint AlignTo16(uint value)
|
|
{
|
|
var aligned = (value + 15u) & ~15u;
|
|
return aligned < 16u ? 16u : aligned;
|
|
}
|
|
|
|
private static void ValidateInputPath(string inputPath)
|
|
{
|
|
if (string.IsNullOrEmpty(inputPath) || !Path.IsPathFullyQualified(inputPath))
|
|
throw new ArgumentException("Input path must be a fully qualified absolute path.", nameof(inputPath));
|
|
}
|
|
|
|
private void ValidateTempPath(string tempPath)
|
|
{
|
|
var fullTemp = Path.GetFullPath(tempPath);
|
|
var fullDir = Path.GetFullPath(_fallbackDirectory);
|
|
Span<char> dirWithSep = stackalloc char[fullDir.Length + 1];
|
|
fullDir.AsSpan().CopyTo(dirWithSep);
|
|
dirWithSep[fullDir.Length] = Path.DirectorySeparatorChar;
|
|
if (!fullTemp.AsSpan().StartsWith(dirWithSep, StringComparison.OrdinalIgnoreCase))
|
|
throw new InvalidOperationException("Temporary path is outside the designated fallback directory.");
|
|
}
|
|
|
|
private static void TryDeleteFile(string path)
|
|
{
|
|
try
|
|
{
|
|
if (File.Exists(path))
|
|
File.Delete(path);
|
|
}
|
|
catch { }
|
|
}
|
|
|
|
public void Dispose()
|
|
{
|
|
Interlocked.Exchange(ref _disposed, 1);
|
|
}
|
|
} |