From e5a1389c95dedac7cafc069872d4ea38d19c8218 Mon Sep 17 00:00:00 2001 From: routersys Date: Fri, 21 Aug 2026 23:08:23 +0900 Subject: [PATCH] =?UTF-8?q?=E3=83=97=E3=83=AD=E3=82=AD=E3=82=B7=E7=94=9F?= =?UTF-8?q?=E6=88=90=E3=81=AEYMM4=E6=8F=8F=E7=94=BB=E7=B5=90=E6=9E=9C?= =?UTF-8?q?=E3=83=99=E3=83=BC=E3=82=B9ffmpeg=E6=96=B9=E5=BC=8F=E3=81=B8?= =?UTF-8?q?=E3=81=AE=E7=A7=BB=E8=A1=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ProxyForge/Core/EncoderConfig.cs | 7 +- ProxyForge/Core/FFmpegProxyEncoder.cs | 254 ++++++++ ProxyForge/Core/FFmpegProxyEncoderFactory.cs | 14 + ProxyForge/Core/MfProxyEncoder.cs | 193 ------ ProxyForge/Core/MfProxyEncoderFactory.cs | 13 - ProxyForge/Core/ProxyCacheEntry.cs | 223 +------ ProxyForge/Core/ProxyCacheManager.cs | 52 +- ProxyForge/Interop/HResultExtensions.cs | 34 - ProxyForge/Interop/MfAttributeKeys.cs | 28 - ProxyForge/Interop/MfComInterfaces.cs | 392 ------------ ProxyForge/Interop/MfGuids.cs | 8 - ProxyForge/Interop/MfNativeMethods.cs | 58 -- ProxyForge/Interop/MfTransformInterfaces.cs | 106 ---- ProxyForge/Localization/Texts.ar-sa.resx | 18 +- ProxyForge/Localization/Texts.csv | 20 +- ProxyForge/Localization/Texts.en-us.resx | 18 +- ProxyForge/Localization/Texts.es-es.resx | 18 +- ProxyForge/Localization/Texts.id-id.resx | 18 +- ProxyForge/Localization/Texts.ko-kr.resx | 18 +- ProxyForge/Localization/Texts.resx | 18 +- ProxyForge/Localization/Texts.zh-cn.resx | 18 +- ProxyForge/Localization/Texts.zh-tw.resx | 18 +- ProxyForge/Memory/BufferPool.cs | 25 +- ProxyForge/Memory/FallbackStream.cs | 182 ------ ProxyForge/Memory/MemoryBudget.cs | 114 ---- ProxyForge/Plugin/PluginHost.cs | 23 +- ProxyForge/Plugin/ProxyForgePlugin.cs | 56 +- ProxyForge/Plugin/Ymm4VideoSourceLoader.cs | 35 + ProxyForge/Progress/ProxyGenerationItem.cs | 13 - ProxyForge/ProxyForge.csproj | 8 + ProxyForge/Resource/ResourceRegistry.cs | 83 --- ProxyForge/Settings/ProxyForgeSettings.cs | 21 - ProxyForge/Streaming/ChunkAllocator.cs | 66 -- .../Streaming/LightweightVideoFileSource.cs | 439 ------------- ProxyForge/Streaming/MfSession.cs | 28 - ProxyForge/Streaming/StreamingMfEncoder.cs | 596 ------------------ .../Streaming/StreamingMfEncoderFactory.cs | 15 - ProxyForge/Streaming/VideoFileProbe.cs | 123 ---- ProxyForge/Transcoding/FFmpegArguments.cs | 134 ++++ .../Transcoding/FFmpegEncoderSelector.cs | 159 +++++ ProxyForge/Transcoding/FFmpegProcessRunner.cs | 243 +++++++ ProxyForge/Transcoding/FFmpegRuntime.cs | 63 ++ ProxyForge/Transcoding/FrameRate.cs | 59 ++ ProxyForge/Transcoding/ProxyFrameRenderer.cs | 114 ++++ ProxyForge/Transcoding/ProxyGeometry.cs | 48 ++ ProxyForge/ViewModels/SettingsViewModel.cs | 38 +- ProxyForge/Views/GenerationPopupView.xaml | 3 - ProxyForge/Views/ProxyForgeSettingsView.xaml | 37 +- .../Views/ProxyForgeSettingsView.xaml.cs | 2 +- 49 files changed, 1249 insertions(+), 3024 deletions(-) create mode 100644 ProxyForge/Core/FFmpegProxyEncoder.cs create mode 100644 ProxyForge/Core/FFmpegProxyEncoderFactory.cs delete mode 100644 ProxyForge/Core/MfProxyEncoder.cs delete mode 100644 ProxyForge/Core/MfProxyEncoderFactory.cs delete mode 100644 ProxyForge/Interop/HResultExtensions.cs delete mode 100644 ProxyForge/Interop/MfAttributeKeys.cs delete mode 100644 ProxyForge/Interop/MfComInterfaces.cs delete mode 100644 ProxyForge/Interop/MfGuids.cs delete mode 100644 ProxyForge/Interop/MfNativeMethods.cs delete mode 100644 ProxyForge/Interop/MfTransformInterfaces.cs delete mode 100644 ProxyForge/Memory/FallbackStream.cs delete mode 100644 ProxyForge/Memory/MemoryBudget.cs create mode 100644 ProxyForge/Plugin/Ymm4VideoSourceLoader.cs delete mode 100644 ProxyForge/Resource/ResourceRegistry.cs delete mode 100644 ProxyForge/Streaming/ChunkAllocator.cs delete mode 100644 ProxyForge/Streaming/LightweightVideoFileSource.cs delete mode 100644 ProxyForge/Streaming/MfSession.cs delete mode 100644 ProxyForge/Streaming/StreamingMfEncoder.cs delete mode 100644 ProxyForge/Streaming/StreamingMfEncoderFactory.cs delete mode 100644 ProxyForge/Streaming/VideoFileProbe.cs create mode 100644 ProxyForge/Transcoding/FFmpegArguments.cs create mode 100644 ProxyForge/Transcoding/FFmpegEncoderSelector.cs create mode 100644 ProxyForge/Transcoding/FFmpegProcessRunner.cs create mode 100644 ProxyForge/Transcoding/FFmpegRuntime.cs create mode 100644 ProxyForge/Transcoding/FrameRate.cs create mode 100644 ProxyForge/Transcoding/ProxyFrameRenderer.cs create mode 100644 ProxyForge/Transcoding/ProxyGeometry.cs diff --git a/ProxyForge/Core/EncoderConfig.cs b/ProxyForge/Core/EncoderConfig.cs index ae2bf67..e44595d 100644 --- a/ProxyForge/Core/EncoderConfig.cs +++ b/ProxyForge/Core/EncoderConfig.cs @@ -1,6 +1,5 @@ -namespace ProxyForge.Core; +namespace ProxyForge.Core; internal readonly record struct EncoderConfig( - bool EnableHardwareAcceleration, - bool EnableDiskFallback -); \ No newline at end of file + bool EnableHardwareAcceleration +); diff --git a/ProxyForge/Core/FFmpegProxyEncoder.cs b/ProxyForge/Core/FFmpegProxyEncoder.cs new file mode 100644 index 0000000..cc0ea60 --- /dev/null +++ b/ProxyForge/Core/FFmpegProxyEncoder.cs @@ -0,0 +1,254 @@ +using ProxyForge.Interfaces; +using ProxyForge.Plugin; +using ProxyForge.Progress; +using ProxyForge.Transcoding; +using System.Buffers; +using System.Diagnostics; +using System.Globalization; +using System.IO; +using System.Windows; +using System.Windows.Threading; +using YukkuriMovieMaker.Commons; +using YukkuriMovieMaker.Plugin.FileSource; + +namespace ProxyForge.Core; + +internal sealed class FFmpegProxyEncoder : IProxyEncoder +{ + private const int DiagnosticExcerptLength = 200; + private const long ProgressReportStepCenti = 100L; + + private readonly string _fallbackDirectory; + private readonly EncoderConfig _config; + private readonly FFmpegExecutables _executables; + private readonly Ymm4VideoSourceFactory _sourceFactory; + private int _disposed; + + internal FFmpegProxyEncoder( + string fallbackDirectory, + EncoderConfig config, + FFmpegExecutables executables, + Ymm4VideoSourceFactory sourceFactory) + { + _fallbackDirectory = fallbackDirectory; + _config = config; + _executables = executables; + _sourceFactory = sourceFactory; + } + + public async Task EncodeAsync( + string inputPath, float scale, float bitrateFactor, int gopSize, + ProxyGenerationItem? progressItem, CancellationToken cancellationToken) + { + ObjectDisposedException.ThrowIf(Volatile.Read(ref _disposed) != 0, this); + ValidateInputPath(inputPath); + + if (!_executables.IsAvailable) + throw new InvalidOperationException("FFmpeg executables are unavailable."); + + Directory.CreateDirectory(_fallbackDirectory); + + var outputPath = Path.Combine(_fallbackDirectory, CreateTempFileName()); + ValidateOutputPath(outputPath); + + GraphicsDevices? devices = null; + IGraphicsDevicesAndContext? context = null; + IVideoFileSource? source = null; + ProxyFrameRenderer? renderer = null; + ProxyCacheEntry? entry = null; + + try + { + cancellationToken.ThrowIfCancellationRequested(); + + devices = new GraphicsDevices(); + context = devices.CreateContext(); + context.DeviceContext.SetDpi(ProxyFrameRenderer.ReferenceDpi, ProxyFrameRenderer.ReferenceDpi); + + source = _sourceFactory(context, inputPath) + ?? throw new InvalidOperationException( + "No YukkuriMovieMaker video file source plugin was able to open the input file."); + + var duration = source.Duration; + if (duration <= TimeSpan.Zero) + throw new InvalidOperationException("The video source reported a zero duration."); + + var frameCount = source.GetFrameIndex(duration); + if (frameCount <= 0) + throw new InvalidOperationException("The video source reported no frames."); + + source.Update(FrameRate.GetSampleTime(0, frameCount, duration)); + + var (displayWidth, displayHeight) = ProxyFrameRenderer.MeasureDisplaySize(context, source.Output); + var geometry = ProxyGeometryCalculator.Calculate(displayWidth, displayHeight, scale); + var frameRate = FrameRate.FromFrameCountAndDuration(frameCount, duration); + + renderer = new ProxyFrameRenderer(context, source.Output, geometry, displayWidth, displayHeight); + + var videoEncoder = await FFmpegEncoderSelector.ResolveAsync( + _executables.FFmpegPath, + _config.EnableHardwareAcceleration, + geometry.Width, + geometry.Height, + _fallbackDirectory, + cancellationToken).ConfigureAwait(false); + + var request = new FFmpegEncodeRequest( + outputPath, + geometry.Width, + geometry.Height, + frameRate, + FFmpegArguments.CalculateVideoBitrate(geometry.Width, geometry.Height, frameRate.Value, bitrateFactor), + Math.Max(1, gopSize), + videoEncoder); + + var pump = new FramePump(source, renderer, frameCount, duration, progressItem); + + var result = await FFmpegProcessRunner.RunAsync( + _executables.FFmpegPath, + arguments => FFmpegArguments.WriteEncode(arguments, in request), + _fallbackDirectory, + null, + pump.WriteAsync, + ProcessPriorityClass.BelowNormal, + cancellationToken).ConfigureAwait(false); + + if (!result.IsSuccess) + { + Debug.WriteLine(string.Concat("[FFmpegProxyEncoder] ffmpeg failed: ", result.Diagnostics)); + throw new InvalidOperationException(string.Concat( + "ffmpeg exited with code ", + result.ExitCode.ToString(CultureInfo.InvariantCulture), + ": ", + result.FirstDiagnosticLine(DiagnosticExcerptLength))); + } + + var outputInfo = new FileInfo(outputPath); + if (!outputInfo.Exists || outputInfo.Length == 0) + throw new InvalidOperationException("ffmpeg completed without producing a proxy file."); + + entry = new ProxyCacheEntry(inputPath, geometry.EffectiveScale) + { + ProxyWidth = geometry.Width, + ProxyHeight = geometry.Height + }; + entry.SetDiskPath(outputPath, outputInfo.Length); + return entry; + } + catch + { + entry?.Dispose(); + TryDeleteFile(outputPath); + throw; + } + finally + { + renderer?.Dispose(); + source?.Dispose(); + context?.Dispose(); + devices?.Dispose(); + } + } + + private static string CreateTempFileName() + { + Span buffer = stackalloc char[40]; + "zdp_".AsSpan().CopyTo(buffer); + Guid.NewGuid().TryFormat(buffer[4..], out _, "N"); + ".mp4".AsSpan().CopyTo(buffer[36..]); + return new string(buffer); + } + + 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 ValidateOutputPath(string outputPath) + { + var fullOutput = Path.GetFullPath(outputPath); + var fullDirectory = Path.GetFullPath(_fallbackDirectory); + Span directoryWithSeparator = stackalloc char[fullDirectory.Length + 1]; + fullDirectory.AsSpan().CopyTo(directoryWithSeparator); + directoryWithSeparator[fullDirectory.Length] = Path.DirectorySeparatorChar; + if (!fullOutput.AsSpan().StartsWith(directoryWithSeparator, StringComparison.OrdinalIgnoreCase)) + throw new InvalidOperationException("Output path is outside the designated temporary directory."); + } + + private static void TryDeleteFile(string path) + { + try + { + if (File.Exists(path)) + File.Delete(path); + } + catch (Exception ex) + { + Debug.WriteLine(string.Concat("[FFmpegProxyEncoder] Delete failed: ", ex.Message)); + } + } + + public void Dispose() + { + Interlocked.Exchange(ref _disposed, 1); + } + + private sealed class FramePump( + IVideoFileSource source, + ProxyFrameRenderer renderer, + int frameCount, + TimeSpan duration, + ProxyGenerationItem? progressItem) + { + private readonly Action? _dispatchAction = + progressItem is null ? null : progressItem.ApplyPendingProgress; + private long _lastReportedCenti; + + internal Task WriteAsync(Stream destination, CancellationToken cancellationToken) => + Task.Factory.StartNew( + () => Write(destination, cancellationToken), + cancellationToken, + TaskCreationOptions.LongRunning, + TaskScheduler.Default); + + private void Write(Stream destination, CancellationToken cancellationToken) + { + var frameBytes = renderer.FrameByteCount; + var buffer = ArrayPool.Shared.Rent(frameBytes); + try + { + var frame = buffer.AsSpan(0, frameBytes); + for (var index = 0; index < frameCount; index++) + { + cancellationToken.ThrowIfCancellationRequested(); + + source.Update(FrameRate.GetSampleTime(index, frameCount, duration)); + renderer.Render(frame); + destination.Write(frame); + + ReportProgress(index + 1); + } + } + finally + { + ArrayPool.Shared.Return(buffer); + } + } + + private void ReportProgress(int completedFrames) + { + if (progressItem is null || _dispatchAction is null) + return; + + var percentage = Math.Min(99.0, completedFrames * 100.0 / frameCount); + var centi = (long)(percentage * 100); + if (centi - _lastReportedCenti < ProgressReportStepCenti && percentage < 99.0) + return; + + _lastReportedCenti = centi; + progressItem.SetPendingProgress(percentage); + Application.Current?.Dispatcher.BeginInvoke(DispatcherPriority.Background, _dispatchAction); + } + } +} diff --git a/ProxyForge/Core/FFmpegProxyEncoderFactory.cs b/ProxyForge/Core/FFmpegProxyEncoderFactory.cs new file mode 100644 index 0000000..d1db582 --- /dev/null +++ b/ProxyForge/Core/FFmpegProxyEncoderFactory.cs @@ -0,0 +1,14 @@ +using ProxyForge.Interfaces; +using ProxyForge.Plugin; +using ProxyForge.Transcoding; + +namespace ProxyForge.Core; + +internal sealed class FFmpegProxyEncoderFactory( + string fallbackDirectory, + Func configProvider) : IProxyEncoderFactory +{ + public IProxyEncoder Create() => + new FFmpegProxyEncoder( + fallbackDirectory, configProvider(), FFmpegRuntime.Require(), Ymm4VideoSourceLoader.Load); +} diff --git a/ProxyForge/Core/MfProxyEncoder.cs b/ProxyForge/Core/MfProxyEncoder.cs deleted file mode 100644 index 5ddca40..0000000 --- a/ProxyForge/Core/MfProxyEncoder.cs +++ /dev/null @@ -1,193 +0,0 @@ -using ProxyForge.Interfaces; -using ProxyForge.Interop; -using ProxyForge.Memory; -using ProxyForge.Progress; -using System.IO; -using Windows.Foundation; -using Windows.Media.MediaProperties; -using Windows.Media.Transcoding; -using Windows.Storage; - -namespace ProxyForge.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 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 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) - { - var reporter = new TranscodeProgressReporter(progressItem); - transcodeOp.Progress = reporter.Report; - } - - using var reg = cancellationToken.Register( - static state => ((IAsyncActionWithProgress)state!).Cancel(), - transcodeOp); - await transcodeOp; - - float effectiveScale = (float)proxyWidth / origWidth; - entry = new ProxyCacheEntry(inputPath, effectiveScale, _memoryBudget.RecordDeallocation) - { - ProxyWidth = proxyWidth, - ProxyHeight = proxyHeight - }; - - CaptureOutputHybrid(tempPath, entry); - return entry; - } - catch - { - entry?.Dispose(); - TryDeleteFile(tempPath); - throw; - } - } - - private void CaptureOutputHybrid(string outputPath, ProxyCacheEntry entry) - { - var fileSize = new FileInfo(outputPath).Length; - entry.SetDiskPath(outputPath, fileSize); - } - - 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 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); - } - - private sealed class TranscodeProgressReporter(ProxyGenerationItem progressItem) - { - private readonly Action _dispatchAction = progressItem.ApplyPendingProgress; - private long _lastReportedCenti; - - internal void Report(IAsyncActionWithProgress _, double 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); - } - } -} \ No newline at end of file diff --git a/ProxyForge/Core/MfProxyEncoderFactory.cs b/ProxyForge/Core/MfProxyEncoderFactory.cs deleted file mode 100644 index acbd504..0000000 --- a/ProxyForge/Core/MfProxyEncoderFactory.cs +++ /dev/null @@ -1,13 +0,0 @@ -using ProxyForge.Interfaces; -using ProxyForge.Memory; - -namespace ProxyForge.Core; - -internal sealed class MfProxyEncoderFactory( - MemoryBudget memoryBudget, - string fallbackDirectory, - Func configProvider) : IProxyEncoderFactory -{ - public IProxyEncoder Create() => - new MfProxyEncoder(memoryBudget, fallbackDirectory, configProvider()); -} \ No newline at end of file diff --git a/ProxyForge/Core/ProxyCacheEntry.cs b/ProxyForge/Core/ProxyCacheEntry.cs index c9b398d..1d52bc3 100644 --- a/ProxyForge/Core/ProxyCacheEntry.cs +++ b/ProxyForge/Core/ProxyCacheEntry.cs @@ -1,4 +1,3 @@ -using ProxyForge.Memory; using System.Diagnostics; using System.IO; @@ -6,17 +5,10 @@ namespace ProxyForge.Core; internal sealed class ProxyCacheEntry : IDisposable { - private byte[]? _memoryData; - private int _memoryDataLength; private string? _diskPath; - private readonly Action? _onMemoryReleased; private long _cachedSize; - private long _trackedMemoryBytes; private long _lastAccessedTicks = DateTime.UtcNow.Ticks; - private readonly object _diskWriteLock = new(); private int _disposed; - private int _streamCount; - private int _releaseMemoryWhenPossible; private int _persistentDiskEntry; internal string OriginalPath { get; } @@ -24,42 +16,24 @@ internal sealed class ProxyCacheEntry : IDisposable internal uint ProxyWidth { get; init; } internal uint ProxyHeight { get; init; } - internal bool IsInMemory => - Volatile.Read(ref _memoryData) is not null && - Volatile.Read(ref _diskPath) is null; - internal bool IsValid => Volatile.Read(ref _disposed) == 0 && - (Volatile.Read(ref _memoryData) is not null || Volatile.Read(ref _diskPath) is not null); + Volatile.Read(ref _diskPath) is not null; internal long DataSize => Interlocked.Read(ref _cachedSize); internal DateTime CreatedAt { get; } = DateTime.UtcNow; internal DateTime LastAccessedAt => new(Interlocked.Read(ref _lastAccessedTicks)); - internal ProxyCacheEntry(string originalPath, float scale, Action? onMemoryReleased = null) + internal ProxyCacheEntry(string originalPath, float scale) { OriginalPath = originalPath; Scale = scale; - _onMemoryReleased = onMemoryReleased; - } - - internal void SetMemoryData(byte[] pooledBuffer, int length) - { - Interlocked.Exchange(ref _trackedMemoryBytes, length); - Interlocked.Exchange(ref _cachedSize, (long)length); - Volatile.Write(ref _memoryDataLength, length); - Volatile.Write(ref _diskPath, null); - Volatile.Write(ref _releaseMemoryWhenPossible, 0); - Volatile.Write(ref _memoryData, pooledBuffer); - UpdateLastAccess(); } internal void SetDiskPath(string path, long size) { Interlocked.Exchange(ref _cachedSize, size); Volatile.Write(ref _diskPath, path); - Volatile.Write(ref _releaseMemoryWhenPossible, 1); - TryReturnBuffer(); UpdateLastAccess(); } @@ -77,76 +51,11 @@ internal sealed class ProxyCacheEntry : IDisposable internal Stream OpenReadStream() { - ObjectDisposedException.ThrowIf(Volatile.Read(ref _disposed) != 0, this); - UpdateLastAccess(); - - while (true) - { - var mem = Volatile.Read(ref _memoryData); - if (mem is null) - break; - - Interlocked.Increment(ref _streamCount); - - if (Volatile.Read(ref _disposed) != 0) - { - OnStreamClosed(); - throw new ObjectDisposedException(nameof(ProxyCacheEntry)); - } - - if (!ReferenceEquals(mem, Volatile.Read(ref _memoryData))) - { - OnStreamClosed(); - continue; - } - - var len = Volatile.Read(ref _memoryDataLength); - return new PooledMemoryStream(mem, len, this); - } - - var disk = Volatile.Read(ref _diskPath); - if (disk is not null && File.Exists(disk)) - return new FileStream(disk, FileMode.Open, FileAccess.Read, FileShare.Read, 65536, FileOptions.SequentialScan); - - throw new InvalidOperationException("Proxy data unavailable"); + var path = GetExistingFilePath(); + return new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, 65536, FileOptions.SequentialScan); } - internal string GetOrCreateTempFilePath(string tempDirectory) - { - ObjectDisposedException.ThrowIf(Volatile.Read(ref _disposed) != 0, this); - UpdateLastAccess(); - - var disk = Volatile.Read(ref _diskPath); - if (disk is not null && File.Exists(disk)) - return disk; - - lock (_diskWriteLock) - { - disk = Volatile.Read(ref _diskPath); - if (disk is not null && File.Exists(disk)) - return disk; - - var mem = Volatile.Read(ref _memoryData); - if (mem is null) - throw new InvalidOperationException("Proxy data unavailable"); - - Directory.CreateDirectory(tempDirectory); - - Span nameBuf = stackalloc char[45]; - "zdp_read_".AsSpan().CopyTo(nameBuf); - Guid.NewGuid().TryFormat(nameBuf[9..], out _, "N"); - ".mp4".AsSpan().CopyTo(nameBuf[41..]); - var tempPath = Path.Combine(tempDirectory, new string(nameBuf)); - - using var fs = new FileStream(tempPath, FileMode.CreateNew, FileAccess.Write, FileShare.None, 65536); - fs.Write(mem, 0, Volatile.Read(ref _memoryDataLength)); - - Volatile.Write(ref _diskPath, tempPath); - Volatile.Write(ref _releaseMemoryWhenPossible, 1); - TryReturnBuffer(); - return tempPath; - } - } + internal string GetFilePath() => GetExistingFilePath(); internal CacheEntrySnapshot CreateSnapshot() => new(OriginalPath, @@ -154,35 +63,20 @@ internal sealed class ProxyCacheEntry : IDisposable Scale, ProxyWidth, ProxyHeight, - IsInMemory, DataSize, CreatedAt, LastAccessedAt); - private void OnStreamClosed() + private string GetExistingFilePath() { - if (Interlocked.Decrement(ref _streamCount) == 0) - TryReturnBuffer(); - } + ObjectDisposedException.ThrowIf(Volatile.Read(ref _disposed) != 0, this); - private void TryReturnBuffer() - { - if (Volatile.Read(ref _streamCount) != 0) - return; + var path = Volatile.Read(ref _diskPath); + if (path is null || !File.Exists(path)) + throw new InvalidOperationException("Proxy data unavailable"); - if (Volatile.Read(ref _disposed) == 0 && Volatile.Read(ref _releaseMemoryWhenPossible) == 0) - return; - - var buf = Interlocked.Exchange(ref _memoryData, null); - if (buf is null) - return; - - Volatile.Write(ref _memoryDataLength, 0); - BufferPool.Return(buf); - - var released = Interlocked.Exchange(ref _trackedMemoryBytes, 0); - if (released > 0) - _onMemoryReleased?.Invoke(released); + UpdateLastAccess(); + return path; } private void UpdateLastAccess() => @@ -193,8 +87,6 @@ internal sealed class ProxyCacheEntry : IDisposable if (Interlocked.Exchange(ref _disposed, 1) != 0) return; - TryReturnBuffer(); - var disk = Interlocked.Exchange(ref _diskPath, null); if (disk is null || Volatile.Read(ref _persistentDiskEntry) != 0) return; @@ -209,94 +101,6 @@ internal sealed class ProxyCacheEntry : IDisposable Debug.WriteLine(string.Concat("[ProxyCacheEntry] Delete failed: ", ex.Message)); } } - - private sealed class PooledMemoryStream(byte[] buffer, int length, ProxyCacheEntry owner) : Stream - { - private int _position; - private int _streamDisposed; - - public override bool CanRead => Volatile.Read(ref _streamDisposed) == 0; - public override bool CanSeek => Volatile.Read(ref _streamDisposed) == 0; - public override bool CanWrite => false; - public override long Length => length; - - public override long Position - { - get => Volatile.Read(ref _position); - set - { - ArgumentOutOfRangeException.ThrowIfNegative(value); - ArgumentOutOfRangeException.ThrowIfGreaterThan(value, length); - Volatile.Write(ref _position, (int)value); - } - } - - public override int Read(byte[] destination, int offset, int count) - { - ArgumentNullException.ThrowIfNull(destination); - ArgumentOutOfRangeException.ThrowIfNegative(offset); - ArgumentOutOfRangeException.ThrowIfNegative(count); - ArgumentOutOfRangeException.ThrowIfGreaterThan(offset + count, destination.Length); - return ReadCore(destination.AsSpan(offset, count)); - } - - public override int Read(Span destination) => ReadCore(destination); - - private int ReadCore(Span destination) - { - var pos = Volatile.Read(ref _position); - var available = length - pos; - if (available <= 0) - return 0; - var toRead = Math.Min(destination.Length, available); - buffer.AsSpan(pos, toRead).CopyTo(destination); - Volatile.Write(ref _position, pos + toRead); - return toRead; - } - - public override ValueTask ReadAsync(Memory destination, CancellationToken cancellationToken = default) - { - if (cancellationToken.IsCancellationRequested) - return ValueTask.FromCanceled(cancellationToken); - return ValueTask.FromResult(ReadCore(destination.Span)); - } - - public override Task ReadAsync(byte[] destination, int offset, int count, CancellationToken cancellationToken) - { - if (cancellationToken.IsCancellationRequested) - return Task.FromCanceled(cancellationToken); - return Task.FromResult(Read(destination, offset, count)); - } - - public override long Seek(long offset, SeekOrigin origin) - { - var newPos = origin switch - { - SeekOrigin.Begin => offset, - SeekOrigin.Current => Volatile.Read(ref _position) + offset, - SeekOrigin.End => length + offset, - _ => throw new ArgumentOutOfRangeException(nameof(origin)) - }; - var clamped = (int)Math.Clamp(newPos, 0L, (long)length); - Volatile.Write(ref _position, clamped); - return clamped; - } - - public override void Flush() { } - - public override void SetLength(long value) => - throw new NotSupportedException(); - - public override void Write(byte[] destination, int offset, int count) => - throw new NotSupportedException(); - - protected override void Dispose(bool disposing) - { - if (Interlocked.Exchange(ref _streamDisposed, 1) == 0 && disposing) - owner.OnStreamClosed(); - base.Dispose(disposing); - } - } } internal readonly record struct CacheEntrySnapshot( @@ -305,8 +109,7 @@ internal readonly record struct CacheEntrySnapshot( float Scale, uint ProxyWidth, uint ProxyHeight, - bool IsInMemory, long DataSize, DateTime CreatedAt, DateTime LastAccessedAt -); \ No newline at end of file +); diff --git a/ProxyForge/Core/ProxyCacheManager.cs b/ProxyForge/Core/ProxyCacheManager.cs index 91c113d..ae91b64 100644 --- a/ProxyForge/Core/ProxyCacheManager.cs +++ b/ProxyForge/Core/ProxyCacheManager.cs @@ -25,6 +25,7 @@ internal sealed class ProxyCacheManager : IDisposable private readonly ConcurrentDictionary _cache = new(); private readonly ConcurrentDictionary _pendingGenerations = new(); + private readonly SemaphoreSlim _encodeGate = new(1, 1); private readonly IProxyEncoderFactory _encoderFactory; private readonly VideoCacheDatabase? _videoCache; private readonly string _tmpDirectory; @@ -123,10 +124,19 @@ internal sealed class ProxyCacheManager : IDisposable try { - using var encoder = _encoderFactory.Create(); - var entry = await encoder.EncodeAsync( - originalPath, scale, settings.BitrateFactor / 100f, settings.GopSize, - progressItem, cts.Token).ConfigureAwait(false); + ProxyCacheEntry entry; + await AcquireEncodeSlotAsync(progressItem, cts.Token).ConfigureAwait(false); + try + { + using var encoder = _encoderFactory.Create(); + entry = await encoder.EncodeAsync( + originalPath, scale, settings.BitrateFactor / 100f, settings.GopSize, + progressItem, cts.Token).ConfigureAwait(false); + } + finally + { + _encodeGate.Release(); + } var stored = _cache.GetOrAdd(key, entry); if (!ReferenceEquals(stored, entry)) @@ -135,13 +145,11 @@ internal sealed class ProxyCacheManager : IDisposable if (_videoCache is not null && ProxyForgeSettings.Default.EnableVideoCache) PersistToVideoCache(originalPath, scale, stored); - var isInMem = stored.IsInMemory; DispatchInvoke(() => { progressItem.Progress = 100; progressItem.IsCompleted = true; progressItem.StatusMessage = Translate.ProxyGenerationStatusCompleted; - progressItem.IsInMemory = isInMem; }); ProxyCompleted?.Invoke(originalPath, stored); @@ -176,6 +184,16 @@ internal sealed class ProxyCacheManager : IDisposable DispatchInvoke(() => ActiveGenerations.Remove(progressItem)); } + private async Task AcquireEncodeSlotAsync(ProxyGenerationItem progressItem, CancellationToken cancellationToken) + { + if (_encodeGate.Wait(0, CancellationToken.None)) + return; + + DispatchInvoke(() => progressItem.StatusMessage = Translate.ProxyGenerationStatusQueued); + await _encodeGate.WaitAsync(cancellationToken).ConfigureAwait(false); + DispatchInvoke(() => progressItem.StatusMessage = Translate.ProxyGenerationStatusGenerating); + } + private static void DispatchInvoke(Action action) { var app = Application.Current; @@ -253,7 +271,7 @@ internal sealed class ProxyCacheManager : IDisposable resultList.Add(new CacheEntrySnapshot( db.OriginalPath, db.FileName, db.Scale, db.ProxyWidth, db.ProxyHeight, - false, db.FileSize, db.CreatedAt, db.LastAccessedAt)); + db.FileSize, db.CreatedAt, db.LastAccessedAt)); } } } @@ -261,27 +279,19 @@ internal sealed class ProxyCacheManager : IDisposable return resultList.Count > 0 ? [.. resultList] : []; } - internal (int entryCount, long memSize, long diskSize, int memCount, int diskCount) GetCacheInfo() + internal (int entryCount, long totalSize) GetCacheInfo() { - long ms = 0, ds = 0; - int mc = 0, dc = 0; + long totalSize = 0; + var count = 0; foreach (var e in _cache.Values) { if (!e.IsValid) continue; - if (e.IsInMemory) - { - ms += e.DataSize; - mc++; - } - else - { - ds += e.DataSize; - dc++; - } + totalSize += e.DataSize; + count++; } - return (_cache.Count, ms, ds, mc, dc); + return (count, totalSize); } public void Dispose() diff --git a/ProxyForge/Interop/HResultExtensions.cs b/ProxyForge/Interop/HResultExtensions.cs deleted file mode 100644 index be6a8f9..0000000 --- a/ProxyForge/Interop/HResultExtensions.cs +++ /dev/null @@ -1,34 +0,0 @@ -using System.Runtime.InteropServices; - -namespace ProxyForge.Interop; - -internal static class HResultExtensions -{ - internal const int S_OK = 0; - internal const int S_FALSE = 1; - internal const int MF_E_NO_MORE_TYPES = unchecked((int)0xC00D36B9); - internal const int MF_E_TRANSFORM_NEED_MORE_INPUT = unchecked((int)0xC00D6D72); - internal const int E_FAIL = unchecked((int)0x80004005); - internal const int E_OUTOFMEMORY = unchecked((int)0x8007000E); - internal const int E_NOTIMPL = unchecked((int)0x80004001); - - internal static void ThrowOnFailure(int hr, string? context = null) - { - if (hr >= 0) - return; - - var message = context is not null - ? string.Concat("[ZeroDiskProxy] ", context, ": HRESULT 0x", hr.ToString("X8")) - : string.Concat("[ZeroDiskProxy] HRESULT 0x", hr.ToString("X8")); - - throw hr switch - { - E_OUTOFMEMORY => new OutOfMemoryException(message), - E_NOTIMPL => new NotImplementedException(message), - _ => Marshal.GetExceptionForHR(hr) ?? new COMException(message, hr), - }; - } - - internal static bool Succeeded(int hr) => hr >= 0; - internal static bool Failed(int hr) => hr < 0; -} \ No newline at end of file diff --git a/ProxyForge/Interop/MfAttributeKeys.cs b/ProxyForge/Interop/MfAttributeKeys.cs deleted file mode 100644 index daacacb..0000000 --- a/ProxyForge/Interop/MfAttributeKeys.cs +++ /dev/null @@ -1,28 +0,0 @@ -namespace ProxyForge.Interop; - -internal static class MfAttributeKeys -{ - internal static readonly Guid MF_MT_MAJOR_TYPE = new("48eba18e-f8c9-4687-bf11-0a74c9f96a8f"); - internal static readonly Guid MF_MT_SUBTYPE = new("f7e34c9a-42e8-4714-b74b-cb29d72c35e5"); - internal static readonly Guid MF_MT_FRAME_SIZE = new("1652c33d-d6b2-4012-b834-72030849a37d"); - internal static readonly Guid MF_MT_FRAME_RATE = new("c459a2e8-3d2c-4e44-b132-fee5156c7bb0"); - internal static readonly Guid MF_MT_AVG_BITRATE = new("20332624-fb0d-4d9e-bd0d-cbf6786c102e"); - internal static readonly Guid MF_MT_INTERLACE_MODE = new("e2724bb8-e676-4806-b4b2-a8d6efb44ccd"); - internal static readonly Guid MF_MT_DEFAULT_STRIDE = new("644b4e48-1e02-4516-b0eb-c01ca9d49ac5"); - internal static readonly Guid MF_MT_MPEG2_PROFILE = new("ad76a80b-2d5c-4e0b-b375-64e520137036"); - internal static readonly Guid MF_MT_MPEG2_LEVEL = new("96f66574-11c5-4015-8666-bff516436da7"); - - internal static readonly Guid MFMediaType_Video = new("73646976-0000-0010-8000-00aa00389b71"); - internal static readonly Guid MFMediaType_Audio = new("73647561-0000-0010-8000-00aa00389b71"); - internal static readonly Guid MFVideoFormat_H264 = new("34363248-0000-0010-8000-00aa00389b71"); - internal static readonly Guid MFVideoFormat_NV12 = new("3231564e-0000-0010-8000-00aa00389b71"); - internal static readonly Guid MFVideoFormat_RGB32 = new("00000016-0000-0010-8000-00aa00389b71"); - - internal static readonly Guid MF_READWRITE_ENABLE_HARDWARE_TRANSFORMS = new("a634a91c-822b-41b9-a494-4de4643612b0"); - internal static readonly Guid MF_SOURCE_READER_ENABLE_ADVANCED_VIDEO_PROCESSING = new("f81da2c0-b537-4672-a8b2-a681b17307a3"); - internal static readonly Guid MF_SINK_WRITER_DISABLE_THROTTLING = new("08b845d8-2b74-4afe-9d53-be16d2d5ae4f"); - internal static readonly Guid MF_LOW_LATENCY = new("9c27891a-ed7a-40e1-88e8-b22727a024ee"); - - internal static readonly Guid MF_PD_DURATION = new("6c990d33-bb8e-477a-8598-0d5d96fcd88a"); - internal static readonly Guid MF_SOURCE_READER_MEDIASOURCE_CHARACTERISTICS = new("6d23f5c8-c5d7-4a9b-9971-5d11f8bca880"); -} \ No newline at end of file diff --git a/ProxyForge/Interop/MfComInterfaces.cs b/ProxyForge/Interop/MfComInterfaces.cs deleted file mode 100644 index a1e980e..0000000 --- a/ProxyForge/Interop/MfComInterfaces.cs +++ /dev/null @@ -1,392 +0,0 @@ -using System.Runtime.InteropServices; - -namespace ProxyForge.Interop; - -[ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] -[Guid("70ae66f2-c809-4e4f-8915-bdcb406b7993")] -internal interface IMFSourceReader -{ - [PreserveSig] - int GetStreamSelection(uint dwStreamIndex, [MarshalAs(UnmanagedType.Bool)] out bool pfSelected); - - [PreserveSig] - int SetStreamSelection(uint dwStreamIndex, [MarshalAs(UnmanagedType.Bool)] bool fSelected); - - [PreserveSig] - int GetNativeMediaType(uint dwStreamIndex, uint dwMediaTypeIndex, out IMFMediaType ppMediaType); - - [PreserveSig] - int GetCurrentMediaType(uint dwStreamIndex, out IMFMediaType ppMediaType); - - [PreserveSig] - int SetCurrentMediaType(uint dwStreamIndex, nint pdwReserved, IMFMediaType pMediaType); - - [PreserveSig] - int SetCurrentPosition(in Guid guidTimeFormat, in PropVariant varPosition); - - [PreserveSig] - int ReadSample( - uint dwStreamIndex, uint dwControlFlags, - out uint pdwActualStreamIndex, out uint pdwStreamFlags, - out long pllTimestamp, out IMFSample? ppSample); - - [PreserveSig] - int Flush(uint dwStreamIndex); - - [PreserveSig] - int GetServiceForStream(uint dwStreamIndex, in Guid guidService, in Guid riid, out nint ppvObject); - - [PreserveSig] - int GetPresentationAttribute(uint dwStreamIndex, in Guid guidAttribute, nint pvarAttribute); -} - -[ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] -[Guid("3137f1cd-fe5e-4805-a5d8-fb477448cb3d")] -internal interface IMFSinkWriter -{ - [PreserveSig] - int AddStream(IMFMediaType pTargetMediaType, out uint pdwStreamIndex); - - [PreserveSig] - int SetInputMediaType(uint dwStreamIndex, IMFMediaType pInputMediaType, IMFAttributes? pEncodingParameters); - - [PreserveSig] - int BeginWriting(); - - [PreserveSig] - int WriteSample(uint dwStreamIndex, IMFSample pSample); - - [PreserveSig] - int SendStreamTick(uint dwStreamIndex, long llTimestamp); - - [PreserveSig] - int PlaceSampleMarker(uint dwStreamIndex, nint pvContext); - - [PreserveSig] - int NotifyEndOfSegment(uint dwStreamIndex); - - [PreserveSig] - int Flush(uint dwStreamIndex); - - [PreserveSig] - int Finalize_(); - - [PreserveSig] - int GetServiceForStream(uint dwStreamIndex, in Guid guidService, in Guid riid, out nint ppvObject); - - [PreserveSig] - int GetStatistics(uint dwStreamIndex, out MF_SINK_WRITER_STATISTICS pStats); -} - -[ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] -[Guid("44ae0fa8-ea31-4109-8d2e-4cae4997c555")] -internal interface IMFMediaType : IMFAttributes -{ - [PreserveSig] - new int GetItem(in Guid guidKey, nint pValue); - [PreserveSig] - new int GetItemType(in Guid guidKey, out uint pType); - [PreserveSig] - new int CompareItem(in Guid guidKey, nint Value, [MarshalAs(UnmanagedType.Bool)] out bool pbResult); - [PreserveSig] - new int Compare(IMFAttributes pTheirs, uint MatchType, [MarshalAs(UnmanagedType.Bool)] out bool pbResult); - [PreserveSig] - new int GetUINT32(in Guid guidKey, out uint punValue); - [PreserveSig] - new int GetUINT64(in Guid guidKey, out ulong punValue); - [PreserveSig] - new int GetDouble(in Guid guidKey, out double pfValue); - [PreserveSig] - new int GetGUID(in Guid guidKey, out Guid pguidValue); - [PreserveSig] - new int GetStringLength(in Guid guidKey, out uint pcchLength); - [PreserveSig] - new int GetString(in Guid guidKey, [MarshalAs(UnmanagedType.LPWStr)] out string pwszValue, uint cchBufSize, nint pcchLength); - [PreserveSig] - new int GetAllocatedString(in Guid guidKey, [MarshalAs(UnmanagedType.LPWStr)] out string ppwszValue, out uint pcchLength); - [PreserveSig] - new int GetBlobSize(in Guid guidKey, out uint pcbBlobSize); - [PreserveSig] - new int GetBlob(in Guid guidKey, nint pBuf, uint cbBufSize, nint pcbBlobSize); - [PreserveSig] - new int GetAllocatedBlob(in Guid guidKey, out nint ppBuf, out uint pcbSize); - [PreserveSig] - new int GetUnknown(in Guid guidKey, in Guid riid, [MarshalAs(UnmanagedType.IUnknown)] out object ppv); - [PreserveSig] - new int SetItem(in Guid guidKey, nint Value); - [PreserveSig] - new int DeleteItem(in Guid guidKey); - [PreserveSig] - new int DeleteAllItems(); - [PreserveSig] - new int SetUINT32(in Guid guidKey, uint unValue); - [PreserveSig] - new int SetUINT64(in Guid guidKey, ulong unValue); - [PreserveSig] - new int SetDouble(in Guid guidKey, double fValue); - [PreserveSig] - new int SetGUID(in Guid guidKey, in Guid guidValue); - [PreserveSig] - new int SetString(in Guid guidKey, [MarshalAs(UnmanagedType.LPWStr)] string wszValue); - [PreserveSig] - new int SetBlob(in Guid guidKey, nint pBuf, uint cbBufSize); - [PreserveSig] - new int SetUnknown(in Guid guidKey, [MarshalAs(UnmanagedType.IUnknown)] object pUnknown); - [PreserveSig] - new int LockStore(); - [PreserveSig] - new int UnlockStore(); - [PreserveSig] - new int GetCount(out uint pcItems); - [PreserveSig] - new int GetItemByIndex(uint unIndex, out Guid pguidKey, nint pValue); - [PreserveSig] - new int CopyAllItems(IMFAttributes pDest); - - [PreserveSig] - int GetMajorType(out Guid pguidMajorType); - [PreserveSig] - int IsCompressedFormat([MarshalAs(UnmanagedType.Bool)] out bool pfCompressed); - [PreserveSig] - int IsEqual(IMFMediaType pIMediaType, out uint pdwFlags); - [PreserveSig] - int GetRepresentation(Guid guidRepresentation, out nint ppvRepresentation); - [PreserveSig] - int FreeRepresentation(Guid guidRepresentation, nint pvRepresentation); -} - -[ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] -[Guid("2cd2d921-c447-44a7-a13c-4adabfc247e3")] -internal interface IMFAttributes -{ - [PreserveSig] - int GetItem(in Guid guidKey, nint pValue); - [PreserveSig] - int GetItemType(in Guid guidKey, out uint pType); - [PreserveSig] - int CompareItem(in Guid guidKey, nint Value, [MarshalAs(UnmanagedType.Bool)] out bool pbResult); - [PreserveSig] - int Compare(IMFAttributes pTheirs, uint MatchType, [MarshalAs(UnmanagedType.Bool)] out bool pbResult); - [PreserveSig] - int GetUINT32(in Guid guidKey, out uint punValue); - [PreserveSig] - int GetUINT64(in Guid guidKey, out ulong punValue); - [PreserveSig] - int GetDouble(in Guid guidKey, out double pfValue); - [PreserveSig] - int GetGUID(in Guid guidKey, out Guid pguidValue); - [PreserveSig] - int GetStringLength(in Guid guidKey, out uint pcchLength); - [PreserveSig] - int GetString(in Guid guidKey, [MarshalAs(UnmanagedType.LPWStr)] out string pwszValue, uint cchBufSize, nint pcchLength); - [PreserveSig] - int GetAllocatedString(in Guid guidKey, [MarshalAs(UnmanagedType.LPWStr)] out string ppwszValue, out uint pcchLength); - [PreserveSig] - int GetBlobSize(in Guid guidKey, out uint pcbBlobSize); - [PreserveSig] - int GetBlob(in Guid guidKey, nint pBuf, uint cbBufSize, nint pcbBlobSize); - [PreserveSig] - int GetAllocatedBlob(in Guid guidKey, out nint ppBuf, out uint pcbSize); - [PreserveSig] - int GetUnknown(in Guid guidKey, in Guid riid, [MarshalAs(UnmanagedType.IUnknown)] out object ppv); - [PreserveSig] - int SetItem(in Guid guidKey, nint Value); - [PreserveSig] - int DeleteItem(in Guid guidKey); - [PreserveSig] - int DeleteAllItems(); - [PreserveSig] - int SetUINT32(in Guid guidKey, uint unValue); - [PreserveSig] - int SetUINT64(in Guid guidKey, ulong unValue); - [PreserveSig] - int SetDouble(in Guid guidKey, double fValue); - [PreserveSig] - int SetGUID(in Guid guidKey, in Guid guidValue); - [PreserveSig] - int SetString(in Guid guidKey, [MarshalAs(UnmanagedType.LPWStr)] string wszValue); - [PreserveSig] - int SetBlob(in Guid guidKey, nint pBuf, uint cbBufSize); - [PreserveSig] - int SetUnknown(in Guid guidKey, [MarshalAs(UnmanagedType.IUnknown)] object pUnknown); - [PreserveSig] - int LockStore(); - [PreserveSig] - int UnlockStore(); - [PreserveSig] - int GetCount(out uint pcItems); - [PreserveSig] - int GetItemByIndex(uint unIndex, out Guid pguidKey, nint pValue); - [PreserveSig] - int CopyAllItems(IMFAttributes pDest); -} - -[ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] -[Guid("c40a00f2-b93a-4d80-ae8c-5a1c634f58e4")] -internal interface IMFSample : IMFAttributes -{ - [PreserveSig] - new int GetItem(in Guid guidKey, nint pValue); - [PreserveSig] - new int GetItemType(in Guid guidKey, out uint pType); - [PreserveSig] - new int CompareItem(in Guid guidKey, nint Value, [MarshalAs(UnmanagedType.Bool)] out bool pbResult); - [PreserveSig] - new int Compare(IMFAttributes pTheirs, uint MatchType, [MarshalAs(UnmanagedType.Bool)] out bool pbResult); - [PreserveSig] - new int GetUINT32(in Guid guidKey, out uint punValue); - [PreserveSig] - new int GetUINT64(in Guid guidKey, out ulong punValue); - [PreserveSig] - new int GetDouble(in Guid guidKey, out double pfValue); - [PreserveSig] - new int GetGUID(in Guid guidKey, out Guid pguidValue); - [PreserveSig] - new int GetStringLength(in Guid guidKey, out uint pcchLength); - [PreserveSig] - new int GetString(in Guid guidKey, [MarshalAs(UnmanagedType.LPWStr)] out string pwszValue, uint cchBufSize, nint pcchLength); - [PreserveSig] - new int GetAllocatedString(in Guid guidKey, [MarshalAs(UnmanagedType.LPWStr)] out string ppwszValue, out uint pcchLength); - [PreserveSig] - new int GetBlobSize(in Guid guidKey, out uint pcbBlobSize); - [PreserveSig] - new int GetBlob(in Guid guidKey, nint pBuf, uint cbBufSize, nint pcbBlobSize); - [PreserveSig] - new int GetAllocatedBlob(in Guid guidKey, out nint ppBuf, out uint pcbSize); - [PreserveSig] - new int GetUnknown(in Guid guidKey, in Guid riid, [MarshalAs(UnmanagedType.IUnknown)] out object ppv); - [PreserveSig] - new int SetItem(in Guid guidKey, nint Value); - [PreserveSig] - new int DeleteItem(in Guid guidKey); - [PreserveSig] - new int DeleteAllItems(); - [PreserveSig] - new int SetUINT32(in Guid guidKey, uint unValue); - [PreserveSig] - new int SetUINT64(in Guid guidKey, ulong unValue); - [PreserveSig] - new int SetDouble(in Guid guidKey, double fValue); - [PreserveSig] - new int SetGUID(in Guid guidKey, in Guid guidValue); - [PreserveSig] - new int SetString(in Guid guidKey, [MarshalAs(UnmanagedType.LPWStr)] string wszValue); - [PreserveSig] - new int SetBlob(in Guid guidKey, nint pBuf, uint cbBufSize); - [PreserveSig] - new int SetUnknown(in Guid guidKey, [MarshalAs(UnmanagedType.IUnknown)] object pUnknown); - [PreserveSig] - new int LockStore(); - [PreserveSig] - new int UnlockStore(); - [PreserveSig] - new int GetCount(out uint pcItems); - [PreserveSig] - new int GetItemByIndex(uint unIndex, out Guid pguidKey, nint pValue); - [PreserveSig] - new int CopyAllItems(IMFAttributes pDest); - - [PreserveSig] - int GetSampleFlags(out uint pdwSampleFlags); - [PreserveSig] - int SetSampleFlags(uint dwSampleFlags); - [PreserveSig] - int GetSampleTime(out long phnsSampleTime); - [PreserveSig] - int SetSampleTime(long hnsSampleTime); - [PreserveSig] - int GetSampleDuration(out long phnsSampleDuration); - [PreserveSig] - int SetSampleDuration(long hnsSampleDuration); - [PreserveSig] - int GetBufferCount(out uint pdwBufferCount); - [PreserveSig] - int GetBufferByIndex(uint dwIndex, out IMFMediaBuffer ppBuffer); - [PreserveSig] - int ConvertToContiguousBuffer(out IMFMediaBuffer ppBuffer); - [PreserveSig] - int AddBuffer(IMFMediaBuffer pBuffer); - [PreserveSig] - int RemoveBufferByIndex(uint dwIndex); - [PreserveSig] - int RemoveAllBuffers(); - [PreserveSig] - int GetTotalLength(out uint pcbTotalLength); - [PreserveSig] - int CopyToBuffer(IMFMediaBuffer pBuffer); -} - -[ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] -[Guid("045FA593-8799-42b8-BC8D-8968C6453507")] -internal interface IMFMediaBuffer -{ - [PreserveSig] - int Lock(out nint ppbBuffer, out int pcbMaxLength, out int pcbCurrentLength); - [PreserveSig] - int Unlock(); - [PreserveSig] - int GetCurrentLength(out int pcbCurrentLength); - [PreserveSig] - int SetCurrentLength(int cbCurrentLength); - [PreserveSig] - int GetMaxLength(out int pcbMaxLength); -} - -[ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] -[Guid("7DC9D5F9-9ED9-44ec-9BBF-0600BB589FBF")] -internal interface IMF2DBuffer -{ - [PreserveSig] - int Lock2D(out nint ppbScanline0, out int plPitch); - [PreserveSig] - int Unlock2D(); - [PreserveSig] - int GetScanline0AndPitch(out nint pbScanline0, out int plPitch); - [PreserveSig] - int IsContiguousFormat([MarshalAs(UnmanagedType.Bool)] out bool pfIsContiguous); - [PreserveSig] - int GetContiguousLength(out int pcbLength); - [PreserveSig] - int ContiguousCopyTo(nint pbDestBuffer, int cbDestBuffer); - [PreserveSig] - int ContiguousCopyFrom(nint pbSrcBuffer, int cbSrcBuffer); -} - -[StructLayout(LayoutKind.Sequential)] -internal struct MF_SINK_WRITER_STATISTICS -{ - public uint cb; - public long llLastTimestampReceived; - public long llLastTimestampEncoded; - public long llLastTimestampProcessed; - public long llLastStreamTickReceived; - public long llLastSinkSampleRequest; - public ulong qwNumSamplesReceived; - public ulong qwNumSamplesEncoded; - public ulong qwNumSamplesProcessed; - public ulong qwNumStreamTicksReceived; - public uint dwByteCountQueued; - public ulong qwByteCountProcessed; - public uint dwNumOutstandingSinkSampleRequests; - public uint dwAverageSampleRateReceived; - public uint dwAverageSampleRateEncoded; - public uint dwAverageSampleRateProcessed; -} - -[StructLayout(LayoutKind.Explicit, Size = 24)] -internal struct PropVariant : IDisposable -{ - [FieldOffset(0)] internal ushort vt; - [FieldOffset(8)] internal long hVal; - - internal static PropVariant FromInt64(long value) => new() { vt = 20, hVal = value }; - - public void Dispose() - { - if (vt != 0) - PropVariantClear(ref this); - } - - [DllImport("ole32.dll")] - private static extern int PropVariantClear(ref PropVariant pvar); -} \ No newline at end of file diff --git a/ProxyForge/Interop/MfGuids.cs b/ProxyForge/Interop/MfGuids.cs deleted file mode 100644 index d546dd9..0000000 --- a/ProxyForge/Interop/MfGuids.cs +++ /dev/null @@ -1,8 +0,0 @@ -namespace ProxyForge.Interop; - -internal static class MfGuids -{ - internal static readonly Guid MF_MT_MAX_KEYFRAME_SPACING = new("c16eb52b-73a1-476f-8d62-839d6a020652"); - internal static readonly Guid CLSID_CColorConvertDMO = new("98230571-0087-4204-b020-3282538e57d3"); - internal static readonly Guid IID_IMFTransform = new("bf94c121-5b05-4e6f-8000-ba598961414d"); -} \ No newline at end of file diff --git a/ProxyForge/Interop/MfNativeMethods.cs b/ProxyForge/Interop/MfNativeMethods.cs deleted file mode 100644 index 8dd9dc1..0000000 --- a/ProxyForge/Interop/MfNativeMethods.cs +++ /dev/null @@ -1,58 +0,0 @@ -using System.Runtime.InteropServices; - -namespace ProxyForge.Interop; - -internal static partial class MfNativeMethods -{ - [LibraryImport("mfplat.dll")] - internal static partial int MFStartup(uint version, uint dwFlags); - - [LibraryImport("mfplat.dll")] - internal static partial int MFShutdown(); - - [DllImport("mfplat.dll")] - internal static extern int MFCreateMediaType(out IMFMediaType ppMFType); - - [DllImport("mfplat.dll")] - internal static extern int MFCreateMemoryBuffer(int cbMaxLength, out IMFMediaBuffer ppBuffer); - - [DllImport("mfplat.dll")] - internal static extern int MFCreateSample(out IMFSample ppIMFSample); - - [DllImport("mfplat.dll")] - internal static extern int MFCreateAttributes(out IMFAttributes ppMFAttributes, uint cInitialSize); - - [DllImport("mfreadwrite.dll", CharSet = CharSet.Unicode)] - internal static extern int MFCreateSourceReaderFromURL( - string pwszURL, IMFAttributes? pAttributes, out IMFSourceReader ppSourceReader); - - [DllImport("mfreadwrite.dll", CharSet = CharSet.Unicode)] - internal static extern int MFCreateSinkWriterFromURL( - string pwszOutputURL, nint pByteStream, IMFAttributes? pAttributes, out IMFSinkWriter ppSinkWriter); - - [DllImport("ole32.dll")] - internal static extern int PropVariantClear(nint pvar); - - [DllImport("ole32.dll")] - internal static extern int CoCreateInstance( - in Guid rclsid, nint pUnkOuter, uint dwClsContext, in Guid riid, out nint ppv); - - [DllImport("ole32.dll")] - internal static extern int CreateStreamOnHGlobal( - nint hGlobal, - [MarshalAs(UnmanagedType.Bool)] bool fDeleteOnRelease, - out nint ppstm); - - [DllImport("mfplat.dll")] - internal static extern int MFCreateMFByteStreamOnStream(nint pStream, out nint ppByteStream); - - internal const uint MF_VERSION = 0x00020070; - internal const uint MF_SOURCE_READER_FIRST_VIDEO_STREAM = 0xFFFFFFFC; - internal const uint MF_SOURCE_READER_FIRST_AUDIO_STREAM = 0xFFFFFFFD; - internal const uint MF_SOURCE_READER_MEDIASOURCE = 0xFFFFFFFF; - internal const uint MF_SOURCE_READERF_ENDOFSTREAM = 0x00000001; - internal const uint MF_SOURCE_READERF_ERROR = 0x00000002; - - internal static ulong PackSize(uint width, uint height) => ((ulong)width << 32) | height; - internal static ulong PackRatio(uint numerator, uint denominator) => ((ulong)numerator << 32) | denominator; -} \ No newline at end of file diff --git a/ProxyForge/Interop/MfTransformInterfaces.cs b/ProxyForge/Interop/MfTransformInterfaces.cs deleted file mode 100644 index 433f7d5..0000000 --- a/ProxyForge/Interop/MfTransformInterfaces.cs +++ /dev/null @@ -1,106 +0,0 @@ -using System.Runtime.InteropServices; - -namespace ProxyForge.Interop; - -[ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] -[Guid("bf94c121-5b05-4e6f-8000-ba598961414d")] -internal interface IMFTransform -{ - [PreserveSig] - int GetStreamLimits(out uint pdwInputMinimum, out uint pdwInputMaximum, out uint pdwOutputMinimum, out uint pdwOutputMaximum); - - [PreserveSig] - int GetStreamCount(out uint pcInputStreams, out uint pcOutputStreams); - - [PreserveSig] - int GetStreamIDs(uint dwInputIDArraySize, [Out] uint[] pdwInputIDs, uint dwOutputIDArraySize, [Out] uint[] pdwOutputIDs); - - [PreserveSig] - int GetInputStreamInfo(uint dwInputStreamID, out MFT_INPUT_STREAM_INFO pStreamInfo); - - [PreserveSig] - int GetOutputStreamInfo(uint dwOutputStreamID, out MFT_OUTPUT_STREAM_INFO pStreamInfo); - - [PreserveSig] - int GetAttributes(out IMFAttributes pAttributes); - - [PreserveSig] - int GetInputStreamAttributes(uint dwInputStreamID, out IMFAttributes pAttributes); - - [PreserveSig] - int GetOutputStreamAttributes(uint dwOutputStreamID, out IMFAttributes pAttributes); - - [PreserveSig] - int DeleteInputStream(uint dwStreamID); - - [PreserveSig] - int AddInputStreams(uint cStreams, [In] uint[] adwStreamIDs); - - [PreserveSig] - int GetInputAvailableType(uint dwInputStreamID, uint dwTypeIndex, out IMFMediaType ppType); - - [PreserveSig] - int GetOutputAvailableType(uint dwOutputStreamID, uint dwTypeIndex, out IMFMediaType ppType); - - [PreserveSig] - int SetInputType(uint dwInputStreamID, IMFMediaType? pType, uint dwFlags); - - [PreserveSig] - int SetOutputType(uint dwOutputStreamID, IMFMediaType? pType, uint dwFlags); - - [PreserveSig] - int GetInputCurrentType(uint dwInputStreamID, out IMFMediaType ppType); - - [PreserveSig] - int GetOutputCurrentType(uint dwOutputStreamID, out IMFMediaType ppType); - - [PreserveSig] - int GetInputStatus(uint dwInputStreamID, out uint pdwFlags); - - [PreserveSig] - int GetOutputStatus(out uint pdwFlags); - - [PreserveSig] - int SetOutputBounds(long hnsLowerBound, long hnsUpperBound); - - [PreserveSig] - int ProcessEvent(uint dwInputStreamID, nint pEvent); - - [PreserveSig] - int ProcessMessage(uint eMessage, nint ulParam); - - [PreserveSig] - int ProcessInput(uint dwInputStreamID, IMFSample pSample, uint dwFlags); - - [PreserveSig] - int ProcessOutput(uint dwFlags, uint cOutputBufferCount, ref MFT_OUTPUT_DATA_BUFFER pOutputSamples, out uint pdwStatus); -} - -[StructLayout(LayoutKind.Sequential)] -internal struct MFT_INPUT_STREAM_INFO -{ - public long hnsMaxLatency; - public uint dwFlags; - public uint cbSize; - public uint cbMaxLookahead; - public uint cbAlignment; -} - -[StructLayout(LayoutKind.Sequential)] -internal struct MFT_OUTPUT_STREAM_INFO -{ - public uint dwFlags; - public uint cbSize; - public uint cbAlignment; -} - -[StructLayout(LayoutKind.Sequential)] -internal struct MFT_OUTPUT_DATA_BUFFER -{ - public uint dwStreamID; - [MarshalAs(UnmanagedType.Interface)] - public IMFSample? pSample; - public uint dwStatus; - [MarshalAs(UnmanagedType.Interface)] - public object? pEvents; -} \ No newline at end of file diff --git a/ProxyForge/Localization/Texts.ar-sa.resx b/ProxyForge/Localization/Texts.ar-sa.resx index e8182e0..85d4d4b 100644 --- a/ProxyForge/Localization/Texts.ar-sa.resx +++ b/ProxyForge/Localization/Texts.ar-sa.resx @@ -61,9 +61,9 @@ ar-sa ProxyForge إعدادات ProxyForge -الذاكرة القرص جارٍ الإنشاء... +في الانتظار... مكتمل تم الإلغاء فشل: @@ -72,16 +72,15 @@ تم حذف {0} عنصرًا ({1}). لم تتم تهيئة المكوّن الإضافي عدد عناصر التخزين المؤقت: {0} -الذاكرة: {0} عنصر ({1}) القرص: {2} عنصر ({3}) -مخصّص: {0} +القرص: {0} عنصر ({1}) ProxyForge - جارٍ إنشاء الوكيل جارٍ إنشاء فيديو وكيل... لا توجد عناصر وكيل قيد الإنشاء. -تسريع التحرير باستخدام فيديوهات وكيلة قائمة على الذاكرة +تسريع التحرير باستخدام فيديوهات وكيلة منخفضة الدقة الإعدادات الأساسية اضبط السلوك الأساسي لفيديوهات الوكيل استخدام الوكيل -استخدم فيديو وكيل منخفض الدقة في الذاكرة أثناء التحرير.&#10;يتم التبديل تلقائيًا إلى الأصل عند التصدير. +استخدم فيديو وكيل منخفض الدقة أثناء التحرير.&#10;يتم التبديل تلقائيًا إلى الأصل عند التصدير. مقياس الدقة معامل مقياس الدقة لفيديو الوكيل الحد الأدنى لحجم الملف @@ -89,16 +88,9 @@ إعدادات الجودة اضبط التوازن بين جودة الترميز والأداء معامل معدل البت -القيمة الأعلى تعطي جودة أفضل لكنها تستهلك ذاكرة أكبر +القيمة الأعلى تعطي جودة أفضل لكن حجم ملف أكبر حجم GOP الفاصل بين الإطارات المفتاحية -إعدادات الذاكرة -التحكم في استخدام الذاكرة والرجوع إلى القرص -الذاكرة المحجوزة -يتم الرجوع إلى القرص عند انخفاض الذاكرة عن هذه القيمة -أقصى ذاكرة للتخزين المؤقت -الرجوع إلى القرص -أنشئ ملفات مؤقتة على القرص عند عدم كفاية الذاكرة إعدادات الأتمتة إنشاء تلقائي مسح التخزين المؤقت عند الإنهاء diff --git a/ProxyForge/Localization/Texts.csv b/ProxyForge/Localization/Texts.csv index 4f515ff..d2f7f6c 100644 --- a/ProxyForge/Localization/Texts.csv +++ b/ProxyForge/Localization/Texts.csv @@ -1,9 +1,9 @@ -Key,comment,ja-jp,en-us,zh-cn,zh-tw,ko-kr,es-es,ar-sa,id-id, +Key,comment,ja-jp,en-us,zh-cn,zh-tw,ko-kr,es-es,ar-sa,id-id, "AppName",Application name,ProxyForge,ProxyForge,ProxyForge,ProxyForge,ProxyForge,ProxyForge,ProxyForge,ProxyForge, "SettingsName",Settings page name,ProxyForge 設定,ProxyForge Settings,ProxyForge 设置,ProxyForge 設定,ProxyForge 설정,Configuración de ProxyForge,إعدادات ProxyForge,Pengaturan ProxyForge, -"StorageMemory",Storage type memory,メモリ,Memory,内存,記憶體,메모리,Memoria,الذاكرة,Memori, "StorageDisk",Storage type disk,ディスク,Disk,磁盘,磁碟,디스크,Disco,القرص,Disk, "ProxyGenerationStatusGenerating",Proxy generation generating status,生成中...,Generating...,正在生成...,正在產生...,생성 중...,Generando...,جارٍ الإنشاء...,Sedang membuat..., +"ProxyGenerationStatusQueued",Proxy generation queued status,待機中...,Queued...,排队中...,佇列中...,대기 중...,En cola...,في الانتظار...,Menunggu..., "ProxyGenerationStatusCompleted",Proxy generation completed status,完了,Completed,完成,完成,완료,Completado,مكتمل,Selesai, "ProxyGenerationStatusCanceled",Proxy generation canceled status,キャンセル,Canceled,已取消,已取消,취소됨,Cancelado,تم الإلغاء,Dibatalkan, "ProxyGenerationStatusFailedPrefix",Proxy generation failed prefix,失敗: ,Failed: ,失败: ,失敗: ,실패: ,Error: ,فشل: ,Gagal: , @@ -12,16 +12,15 @@ Key,comment,ja-jp,en-us,zh-cn,zh-tw,ko-kr,es-es,ar-sa,id-id, "CacheDeleteSummaryFormat",Cache delete result summary format,{0} 件 ({1}) を削除しました。,Deleted {0} items ({1}).,已删除 {0} 项({1})。,已刪除 {0} 項({1})。,{0}개 항목({1})을 삭제했습니다.,Se eliminaron {0} elementos ({1}).,تم حذف {0} عنصرًا ({1}).,{0} item ({1}) telah dihapus., "CacheSummaryPluginNotInitialized",Plugin not initialized cache summary,プラグイン未初期化,Plugin not initialized,插件未初始化,外掛未初始化,플러그인이 초기화되지 않음,Plugin no inicializado,لم تتم تهيئة المكوّن الإضافي,Plugin belum diinisialisasi, "CacheSummaryCountFormat",Cache entry count summary format,キャッシュ数: {0} 件,Cache count: {0} items,缓存数: {0} 项,快取數: {0} 項,캐시 수: {0}개,Conteo de caché: {0} elementos,عدد عناصر التخزين المؤقت: {0},Jumlah cache: {0} item, -"CacheUsageMemoryAndDiskFormat",Memory and disk usage summary format,メモリ: {0} 件 ({1}) ディスク: {2} 件 ({3}),Memory: {0} items ({1}) Disk: {2} items ({3}),内存: {0} 项({1}) 磁盘: {2} 项({3}),記憶體: {0} 項({1}) 磁碟: {2} 項({3}),메모리: {0}개({1}) 디스크: {2}개({3}),Memoria: {0} elementos ({1}) Disco: {2} elementos ({3}),الذاكرة: {0} عنصر ({1}) القرص: {2} عنصر ({3}),Memori: {0} item ({1}) Disk: {2} item ({3}), -"CacheUsageAllocatedFormat",Allocated memory suffix format, 割当済: {0}, Allocated: {0}, 已分配: {0}, 已配置: {0}, 할당됨: {0}, Asignado: {0}, مخصّص: {0}, Dialokasikan: {0}, +"CacheUsageDiskFormat",Disk cache usage summary format,ディスク: {0} 件 ({1}),Disk: {0} items ({1}),磁盘: {0} 项({1}),磁碟: {0} 項({1}),디스크: {0}개({1}),Disco: {0} elementos ({1}),القرص: {0} عنصر ({1}),Disk: {0} item ({1}), "GenerationPopupWindowTitle",Generation popup window title,ProxyForge - プロキシ生成中,ProxyForge - Generating Proxy,ProxyForge - 正在生成代理,ProxyForge - 正在產生代理,ProxyForge - 프록시 생성 중,ProxyForge - Generando proxy,ProxyForge - جارٍ إنشاء الوكيل,ProxyForge - Sedang Membuat Proksi, "GenerationPopupHeader",Generation popup header text,プロキシ動画を生成しています...,Generating proxy video...,正在生成代理视频...,正在產生代理影片...,프록시 영상을 생성하는 중...,Generando video proxy...,جارٍ إنشاء فيديو وكيل...,Sedang membuat video proksi..., "GenerationPopupNoActiveItems",No active generation items message,生成中のプロキシはありません,There are no proxies being generated.,当前没有正在生成的代理。,目前沒有正在產生的代理。,생성 중인 프록시가 없습니다.,No hay proxies en generación.,لا توجد عناصر وكيل قيد الإنشاء.,Tidak ada proksi yang sedang dibuat., -"SettingsCardDescription",Settings card description,メモリベースのプロキシ動画で編集を高速化,Speed up editing with memory-based proxy videos,通过基于内存的代理视频加速编辑,透過記憶體式代理影片加速編輯,메모리 기반 프록시 영상으로 편집 속도 향상,Acelera la edición con videos proxy basados en memoria,تسريع التحرير باستخدام فيديوهات وكيلة قائمة على الذاكرة,Tingkatkan kecepatan edit dengan video proksi berbasis memori, +"SettingsCardDescription",Settings card description,低解像度のプロキシ動画で編集を高速化,Speed up editing with low-resolution proxy videos,通过低分辨率代理视频加速编辑,透過低解析度代理影片加速編輯,저해상도 프록시 영상으로 편집 속도 향상,Acelera la edición con videos proxy de baja resolución,تسريع التحرير باستخدام فيديوهات وكيلة منخفضة الدقة,Tingkatkan kecepatan edit dengan video proksi resolusi rendah, "SectionBasicSettingsHeader",Basic settings section header,基本設定,Basic Settings,基本设置,基本設定,기본 설정,Configuración básica,الإعدادات الأساسية,Pengaturan Dasar, "SectionBasicSettingsDescription",Basic settings section description,プロキシ動画の基本的な動作を設定します,Configure the basic behavior of proxy videos,设置代理视频的基本行为,設定代理影片的基本行為,프록시 영상의 기본 동작을 설정합니다,Configura el comportamiento básico de los videos proxy,اضبط السلوك الأساسي لفيديوهات الوكيل,Atur perilaku dasar video proksi, "SettingUseProxyLabel",Use proxy setting label,プロキシを使用する,Use proxy,使用代理,使用代理,프록시 사용,Usar proxy,استخدام الوكيل,Gunakan proksi, -"SettingUseProxyTooltip",Use proxy setting tooltip,編集中にメモリ上の低解像度プロキシ動画を使用します。 出力時は自動でオリジナルに切り替わります。,Use low-resolution proxy video in memory while editing. Automatically switches to original on export.,编辑时使用内存中的低分辨率代理视频。 导出时自动切换为原始视频。,編輯時使用記憶體中的低解析度代理影片。 輸出時會自動切換為原始影片。,편집 중에는 메모리의 저해상도 프록시 영상을 사용합니다. 내보낼 때는 원본으로 자동 전환됩니다.,Usa video proxy de baja resolución en memoria durante la edición. Al exportar cambia automáticamente al original.,استخدم فيديو وكيل منخفض الدقة في الذاكرة أثناء التحرير. يتم التبديل تلقائيًا إلى الأصل عند التصدير.,Gunakan video proksi resolusi rendah di memori saat mengedit. Akan otomatis beralih ke video asli saat ekspor., +"SettingUseProxyTooltip",Use proxy setting tooltip,編集中に低解像度のプロキシ動画を使用します。 出力時は自動でオリジナルに切り替わります。,Use a low-resolution proxy video while editing. Automatically switches to the original on export.,编辑时使用低分辨率代理视频。 导出时自动切换为原始视频。,編輯時使用低解析度代理影片。 輸出時會自動切換為原始影片。,편집 중에는 저해상도 프록시 영상을 사용합니다. 내보낼 때는 원본으로 자동 전환됩니다.,Usa un video proxy de baja resolución durante la edición. Al exportar cambia automáticamente al original.,استخدم فيديو وكيل منخفض الدقة أثناء التحرير. يتم التبديل تلقائيًا إلى الأصل عند التصدير.,Gunakan video proksi resolusi rendah saat mengedit. Akan otomatis beralih ke video asli saat ekspor., "SettingResolutionScaleLabel",Resolution scale setting label,解像度スケール,Resolution Scale,分辨率缩放,解析度縮放,해상도 배율,Escala de resolución,مقياس الدقة,Skala Resolusi, "SettingResolutionScaleTooltip",Resolution scale setting tooltip,プロキシ動画の解像度倍率,Resolution scale factor for proxy video,代理视频的分辨率倍率,代理影片的解析度倍率,프록시 영상의 해상도 배율,Factor de escala de resolución para video proxy,معامل مقياس الدقة لفيديو الوكيل,Faktor skala resolusi untuk video proksi, "SettingMinFileSizeLabel",Minimum file size setting label,最小ファイルサイズ,Minimum File Size,最小文件大小,最小檔案大小,최소 파일 크기,Tamaño mínimo de archivo,الحد الأدنى لحجم الملف,Ukuran File Minimum, @@ -29,16 +28,9 @@ Key,comment,ja-jp,en-us,zh-cn,zh-tw,ko-kr,es-es,ar-sa,id-id, "SectionQualitySettingsHeader",Quality settings section header,品質設定,Quality Settings,质量设置,品質設定,품질 설정,Configuración de calidad,إعدادات الجودة,Pengaturan Kualitas, "SectionQualitySettingsDescription",Quality settings section description,エンコード品質とパフォーマンスのバランスを調整します,Adjust the balance between encoding quality and performance,调整编码质量与性能之间的平衡,調整編碼品質與效能之間的平衡,인코딩 품질과 성능의 균형을 조정합니다,Ajusta el equilibrio entre calidad de codificación y rendimiento,اضبط التوازن بين جودة الترميز والأداء,Sesuaikan keseimbangan antara kualitas encoding dan performa, "SettingBitrateFactorLabel",Bitrate factor setting label,ビットレート係数,Bitrate Factor,比特率系数,位元率係數,비트레이트 계수,Factor de bitrate,معامل معدل البت,Faktor Bitrate, -"SettingBitrateFactorTooltip",Bitrate factor setting tooltip,高いほど高品質ですがメモリ使用量が増えます,Higher value gives better quality but uses more memory,值越高画质越好但内存占用越大,值越高畫質越好但記憶體用量越大,값이 높을수록 품질은 좋아지지만 메모리 사용량이 늘어납니다,Un valor más alto mejora la calidad pero aumenta el uso de memoria,القيمة الأعلى تعطي جودة أفضل لكنها تستهلك ذاكرة أكبر,Nilai lebih tinggi memberi kualitas lebih baik tetapi memakai lebih banyak memori, +"SettingBitrateFactorTooltip",Bitrate factor setting tooltip,高いほど高品質ですがファイルサイズが増えます,Higher value gives better quality but a larger file,值越高画质越好但文件越大,值越高畫質越好但檔案越大,값이 높을수록 품질은 좋아지지만 파일이 커집니다,Un valor más alto mejora la calidad pero aumenta el tamaño del archivo,القيمة الأعلى تعطي جودة أفضل لكن حجم ملف أكبر,Nilai lebih tinggi memberi kualitas lebih baik tetapi ukuran file lebih besar, "SettingGopSizeLabel",GOP size setting label,GOPサイズ,GOP Size,GOP 大小,GOP 大小,GOP 크기,Tamaño GOP,حجم GOP,Ukuran GOP, "SettingGopSizeTooltip",GOP size setting tooltip,キーフレーム間隔,Keyframe interval,关键帧间隔,關鍵影格間隔,키프레임 간격,Intervalo de fotogramas clave,الفاصل بين الإطارات المفتاحية,Interval keyframe, -"SectionMemorySettingsHeader",Memory settings section header,メモリ設定,Memory Settings,内存设置,記憶體設定,메모리 설정,Configuración de memoria,إعدادات الذاكرة,Pengaturan Memori, -"SectionMemorySettingsDescription",Memory settings section description,メモリ使用量とディスクフォールバックを制御します,Control memory usage and disk fallback,控制内存使用量和磁盘回退,控制記憶體使用量與磁碟回退,메모리 사용량과 디스크 폴백을 제어합니다,Controla el uso de memoria y el respaldo en disco,التحكم في استخدام الذاكرة والرجوع إلى القرص,Kendalikan penggunaan memori dan fallback ke disk, -"SettingMemoryReserveLabel",Memory reserve setting label,メモリ予約量,Memory Reserve,内存预留量,記憶體保留量,메모리 예약량,Reserva de memoria,الذاكرة المحجوزة,Cadangan Memori, -"SettingMemoryReserveTooltip",Memory reserve setting tooltip,これを下回るとディスクにフォールバックします,Falls back to disk when memory goes below this value,内存低于该值时回退到磁盘,記憶體低於此值時回退到磁碟,메모리가 이 값보다 낮아지면 디스크로 폴백합니다,Cambia a disco cuando la memoria cae por debajo de este valor,يتم الرجوع إلى القرص عند انخفاض الذاكرة عن هذه القيمة,Akan fallback ke disk saat memori turun di bawah nilai ini, -"SettingMaxCacheMemoryLabel",Max cache memory setting label,最大キャッシュメモリ,Max Cache Memory,最大缓存内存,最大快取記憶體,최대 캐시 메모리,Máxima memoria de caché,أقصى ذاكرة للتخزين المؤقت,Maksimum Memori Cache, -"SettingDiskFallbackLabel",Disk fallback setting label,ディスクフォールバック,Disk Fallback,磁盘回退,磁碟回退,디스크 폴백,Respaldo en disco,الرجوع إلى القرص,Fallback Disk, -"SettingDiskFallbackTooltip",Disk fallback setting tooltip,メモリ不足時にディスクに一時ファイルを作成します,Create temporary files on disk when memory is insufficient,内存不足时在磁盘创建临时文件,記憶體不足時在磁碟建立暫存檔,메모리가 부족할 때 디스크에 임시 파일을 생성합니다,Crea archivos temporales en disco cuando no hay suficiente memoria,أنشئ ملفات مؤقتة على القرص عند عدم كفاية الذاكرة,Buat file sementara di disk saat memori tidak cukup, "SectionAutomationSettingsHeader",Automation settings section header,自動化設定,Automation Settings,自动化设置,自動化設定,자동화 설정,Configuración de automatización,إعدادات الأتمتة,Pengaturan Otomatisasi, "SettingAutoGenerateLabel",Auto generate setting label,自動生成,Auto Generate,自动生成,自動產生,자동 생성,Generación automática,إنشاء تلقائي,Buat Otomatis, "SettingClearCacheOnExitLabel",Clear cache on exit setting label,終了時にキャッシュクリア,Clear Cache on Exit,退出时清除缓存,結束時清除快取,종료 시 캐시 지우기,Borrar caché al salir,مسح التخزين المؤقت عند الإنهاء,Hapus Cache saat Keluar, diff --git a/ProxyForge/Localization/Texts.en-us.resx b/ProxyForge/Localization/Texts.en-us.resx index 7291adb..b974d16 100644 --- a/ProxyForge/Localization/Texts.en-us.resx +++ b/ProxyForge/Localization/Texts.en-us.resx @@ -61,9 +61,9 @@ en-us ProxyForge ProxyForge Settings -Memory Disk Generating... +Queued... Completed Canceled Failed: @@ -72,16 +72,15 @@ Deleted {0} items ({1}). Plugin not initialized Cache count: {0} items -Memory: {0} items ({1}) Disk: {2} items ({3}) -Allocated: {0} +Disk: {0} items ({1}) ProxyForge - Generating Proxy Generating proxy video... There are no proxies being generated. -Speed up editing with memory-based proxy videos +Speed up editing with low-resolution proxy videos Basic Settings Configure the basic behavior of proxy videos Use proxy -Use low-resolution proxy video in memory while editing.&#10;Automatically switches to original on export. +Use a low-resolution proxy video while editing.&#10;Automatically switches to the original on export. Resolution Scale Resolution scale factor for proxy video Minimum File Size @@ -89,16 +88,9 @@ Quality Settings Adjust the balance between encoding quality and performance Bitrate Factor -Higher value gives better quality but uses more memory +Higher value gives better quality but a larger file GOP Size Keyframe interval -Memory Settings -Control memory usage and disk fallback -Memory Reserve -Falls back to disk when memory goes below this value -Max Cache Memory -Disk Fallback -Create temporary files on disk when memory is insufficient Automation Settings Auto Generate Clear Cache on Exit diff --git a/ProxyForge/Localization/Texts.es-es.resx b/ProxyForge/Localization/Texts.es-es.resx index bc23ab9..149c63d 100644 --- a/ProxyForge/Localization/Texts.es-es.resx +++ b/ProxyForge/Localization/Texts.es-es.resx @@ -61,9 +61,9 @@ es-es ProxyForge Configuración de ProxyForge -Memoria Disco Generando... +En cola... Completado Cancelado Error: @@ -72,16 +72,15 @@ Se eliminaron {0} elementos ({1}). Plugin no inicializado Conteo de caché: {0} elementos -Memoria: {0} elementos ({1}) Disco: {2} elementos ({3}) -Asignado: {0} +Disco: {0} elementos ({1}) ProxyForge - Generando proxy Generando video proxy... No hay proxies en generación. -Acelera la edición con videos proxy basados en memoria +Acelera la edición con videos proxy de baja resolución Configuración básica Configura el comportamiento básico de los videos proxy Usar proxy -Usa video proxy de baja resolución en memoria durante la edición.&#10;Al exportar cambia automáticamente al original. +Usa un video proxy de baja resolución durante la edición.&#10;Al exportar cambia automáticamente al original. Escala de resolución Factor de escala de resolución para video proxy Tamaño mínimo de archivo @@ -89,16 +88,9 @@ Configuración de calidad Ajusta el equilibrio entre calidad de codificación y rendimiento Factor de bitrate -Un valor más alto mejora la calidad pero aumenta el uso de memoria +Un valor más alto mejora la calidad pero aumenta el tamaño del archivo Tamaño GOP Intervalo de fotogramas clave -Configuración de memoria -Controla el uso de memoria y el respaldo en disco -Reserva de memoria -Cambia a disco cuando la memoria cae por debajo de este valor -Máxima memoria de caché -Respaldo en disco -Crea archivos temporales en disco cuando no hay suficiente memoria Configuración de automatización Generación automática Borrar caché al salir diff --git a/ProxyForge/Localization/Texts.id-id.resx b/ProxyForge/Localization/Texts.id-id.resx index 2a3413b..50f991a 100644 --- a/ProxyForge/Localization/Texts.id-id.resx +++ b/ProxyForge/Localization/Texts.id-id.resx @@ -61,9 +61,9 @@ id-id ProxyForge Pengaturan ProxyForge -Memori Disk Sedang membuat... +Menunggu... Selesai Dibatalkan Gagal: @@ -72,16 +72,15 @@ {0} item ({1}) telah dihapus. Plugin belum diinisialisasi Jumlah cache: {0} item -Memori: {0} item ({1}) Disk: {2} item ({3}) -Dialokasikan: {0} +Disk: {0} item ({1}) ProxyForge - Sedang Membuat Proksi Sedang membuat video proksi... Tidak ada proksi yang sedang dibuat. -Tingkatkan kecepatan edit dengan video proksi berbasis memori +Tingkatkan kecepatan edit dengan video proksi resolusi rendah Pengaturan Dasar Atur perilaku dasar video proksi Gunakan proksi -Gunakan video proksi resolusi rendah di memori saat mengedit.&#10;Akan otomatis beralih ke video asli saat ekspor. +Gunakan video proksi resolusi rendah saat mengedit.&#10;Akan otomatis beralih ke video asli saat ekspor. Skala Resolusi Faktor skala resolusi untuk video proksi Ukuran File Minimum @@ -89,16 +88,9 @@ Pengaturan Kualitas Sesuaikan keseimbangan antara kualitas encoding dan performa Faktor Bitrate -Nilai lebih tinggi memberi kualitas lebih baik tetapi memakai lebih banyak memori +Nilai lebih tinggi memberi kualitas lebih baik tetapi ukuran file lebih besar Ukuran GOP Interval keyframe -Pengaturan Memori -Kendalikan penggunaan memori dan fallback ke disk -Cadangan Memori -Akan fallback ke disk saat memori turun di bawah nilai ini -Maksimum Memori Cache -Fallback Disk -Buat file sementara di disk saat memori tidak cukup Pengaturan Otomatisasi Buat Otomatis Hapus Cache saat Keluar diff --git a/ProxyForge/Localization/Texts.ko-kr.resx b/ProxyForge/Localization/Texts.ko-kr.resx index 94bba2f..d2d41d4 100644 --- a/ProxyForge/Localization/Texts.ko-kr.resx +++ b/ProxyForge/Localization/Texts.ko-kr.resx @@ -61,9 +61,9 @@ ko-kr ProxyForge ProxyForge 설정 -메모리 디스크 생성 중... +대기 중... 완료 취소됨 실패: @@ -72,16 +72,15 @@ {0}개 항목({1})을 삭제했습니다. 플러그인이 초기화되지 않음 캐시 수: {0}개 -메모리: {0}개({1}) 디스크: {2}개({3}) -할당됨: {0} +디스크: {0}개({1}) ProxyForge - 프록시 생성 중 프록시 영상을 생성하는 중... 생성 중인 프록시가 없습니다. -메모리 기반 프록시 영상으로 편집 속도 향상 +저해상도 프록시 영상으로 편집 속도 향상 기본 설정 프록시 영상의 기본 동작을 설정합니다 프록시 사용 -편집 중에는 메모리의 저해상도 프록시 영상을 사용합니다.&#10;내보낼 때는 원본으로 자동 전환됩니다. +편집 중에는 저해상도 프록시 영상을 사용합니다.&#10;내보낼 때는 원본으로 자동 전환됩니다. 해상도 배율 프록시 영상의 해상도 배율 최소 파일 크기 @@ -89,16 +88,9 @@ 품질 설정 인코딩 품질과 성능의 균형을 조정합니다 비트레이트 계수 -값이 높을수록 품질은 좋아지지만 메모리 사용량이 늘어납니다 +값이 높을수록 품질은 좋아지지만 파일이 커집니다 GOP 크기 키프레임 간격 -메모리 설정 -메모리 사용량과 디스크 폴백을 제어합니다 -메모리 예약량 -메모리가 이 값보다 낮아지면 디스크로 폴백합니다 -최대 캐시 메모리 -디스크 폴백 -메모리가 부족할 때 디스크에 임시 파일을 생성합니다 자동화 설정 자동 생성 종료 시 캐시 지우기 diff --git a/ProxyForge/Localization/Texts.resx b/ProxyForge/Localization/Texts.resx index 9215794..7ea69f8 100644 --- a/ProxyForge/Localization/Texts.resx +++ b/ProxyForge/Localization/Texts.resx @@ -61,9 +61,9 @@ ja-jp ProxyForge ProxyForge 設定 -メモリ ディスク 生成中... +待機中... 完了 キャンセル 失敗: @@ -72,16 +72,15 @@ {0} 件 ({1}) を削除しました。 プラグイン未初期化 キャッシュ数: {0} 件 -メモリ: {0} 件 ({1}) ディスク: {2} 件 ({3}) -割当済: {0} +ディスク: {0} 件 ({1}) ProxyForge - プロキシ生成中 プロキシ動画を生成しています... 生成中のプロキシはありません -メモリベースのプロキシ動画で編集を高速化 +低解像度のプロキシ動画で編集を高速化 基本設定 プロキシ動画の基本的な動作を設定します プロキシを使用する -編集中にメモリ上の低解像度プロキシ動画を使用します。&#10;出力時は自動でオリジナルに切り替わります。 +編集中に低解像度のプロキシ動画を使用します。&#10;出力時は自動でオリジナルに切り替わります。 解像度スケール プロキシ動画の解像度倍率 最小ファイルサイズ @@ -89,16 +88,9 @@ 品質設定 エンコード品質とパフォーマンスのバランスを調整します ビットレート係数 -高いほど高品質ですがメモリ使用量が増えます +高いほど高品質ですがファイルサイズが増えます GOPサイズ キーフレーム間隔 -メモリ設定 -メモリ使用量とディスクフォールバックを制御します -メモリ予約量 -これを下回るとディスクにフォールバックします -最大キャッシュメモリ -ディスクフォールバック -メモリ不足時にディスクに一時ファイルを作成します 自動化設定 自動生成 終了時にキャッシュクリア diff --git a/ProxyForge/Localization/Texts.zh-cn.resx b/ProxyForge/Localization/Texts.zh-cn.resx index 5d7599d..a7caa65 100644 --- a/ProxyForge/Localization/Texts.zh-cn.resx +++ b/ProxyForge/Localization/Texts.zh-cn.resx @@ -61,9 +61,9 @@ zh-cn ProxyForge ProxyForge 设置 -内存 磁盘 正在生成... +排队中... 完成 已取消 失败: @@ -72,16 +72,15 @@ 已删除 {0} 项({1})。 插件未初始化 缓存数: {0} 项 -内存: {0} 项({1}) 磁盘: {2} 项({3}) -已分配: {0} +磁盘: {0} 项({1}) ProxyForge - 正在生成代理 正在生成代理视频... 当前没有正在生成的代理。 -通过基于内存的代理视频加速编辑 +通过低分辨率代理视频加速编辑 基本设置 设置代理视频的基本行为 使用代理 -编辑时使用内存中的低分辨率代理视频。&#10;导出时自动切换为原始视频。 +编辑时使用低分辨率代理视频。&#10;导出时自动切换为原始视频。 分辨率缩放 代理视频的分辨率倍率 最小文件大小 @@ -89,16 +88,9 @@ 质量设置 调整编码质量与性能之间的平衡 比特率系数 -值越高画质越好但内存占用越大 +值越高画质越好但文件越大 GOP 大小 关键帧间隔 -内存设置 -控制内存使用量和磁盘回退 -内存预留量 -内存低于该值时回退到磁盘 -最大缓存内存 -磁盘回退 -内存不足时在磁盘创建临时文件 自动化设置 自动生成 退出时清除缓存 diff --git a/ProxyForge/Localization/Texts.zh-tw.resx b/ProxyForge/Localization/Texts.zh-tw.resx index 0684fc6..1d15d8c 100644 --- a/ProxyForge/Localization/Texts.zh-tw.resx +++ b/ProxyForge/Localization/Texts.zh-tw.resx @@ -61,9 +61,9 @@ zh-tw ProxyForge ProxyForge 設定 -記憶體 磁碟 正在產生... +佇列中... 完成 已取消 失敗: @@ -72,16 +72,15 @@ 已刪除 {0} 項({1})。 外掛未初始化 快取數: {0} 項 -記憶體: {0} 項({1}) 磁碟: {2} 項({3}) -已配置: {0} +磁碟: {0} 項({1}) ProxyForge - 正在產生代理 正在產生代理影片... 目前沒有正在產生的代理。 -透過記憶體式代理影片加速編輯 +透過低解析度代理影片加速編輯 基本設定 設定代理影片的基本行為 使用代理 -編輯時使用記憶體中的低解析度代理影片。&#10;輸出時會自動切換為原始影片。 +編輯時使用低解析度代理影片。&#10;輸出時會自動切換為原始影片。 解析度縮放 代理影片的解析度倍率 最小檔案大小 @@ -89,16 +88,9 @@ 品質設定 調整編碼品質與效能之間的平衡 位元率係數 -值越高畫質越好但記憶體用量越大 +值越高畫質越好但檔案越大 GOP 大小 關鍵影格間隔 -記憶體設定 -控制記憶體使用量與磁碟回退 -記憶體保留量 -記憶體低於此值時回退到磁碟 -最大快取記憶體 -磁碟回退 -記憶體不足時在磁碟建立暫存檔 自動化設定 自動產生 結束時清除快取 diff --git a/ProxyForge/Memory/BufferPool.cs b/ProxyForge/Memory/BufferPool.cs index a1efb09..c565ba6 100644 --- a/ProxyForge/Memory/BufferPool.cs +++ b/ProxyForge/Memory/BufferPool.cs @@ -1,4 +1,4 @@ -using System.Buffers; +using System.Buffers; namespace ProxyForge.Memory; @@ -13,26 +13,3 @@ internal static class BufferPool ArrayPool.Shared.Return(buffer, clearArray); } } - -internal struct PooledBuffer : IDisposable -{ - private byte[]? _buffer; - private readonly int _length; - - internal PooledBuffer(int length) - { - _length = length; - _buffer = BufferPool.Rent(length); - } - - internal readonly byte[] Array => _buffer ?? throw new ObjectDisposedException(nameof(PooledBuffer)); - internal readonly int Length => _length; - internal readonly Span Span => _buffer is not null ? _buffer.AsSpan(0, _length) : throw new ObjectDisposedException(nameof(PooledBuffer)); - - public void Dispose() - { - var buf = Interlocked.Exchange(ref _buffer, null); - if (buf is not null) - BufferPool.Return(buf); - } -} \ No newline at end of file diff --git a/ProxyForge/Memory/FallbackStream.cs b/ProxyForge/Memory/FallbackStream.cs deleted file mode 100644 index 456e126..0000000 --- a/ProxyForge/Memory/FallbackStream.cs +++ /dev/null @@ -1,182 +0,0 @@ -using System.Diagnostics; -using System.IO; - -namespace ProxyForge.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 => Volatile.Read(ref _disposed) == 0 && _inner.CanWrite; - public override long Length => _inner.Length; - - public override long Position - { - get => _inner.Position; - set => _inner.Position = value; - } - - public override void Flush() => _inner.Flush(); - public override int Read(byte[] buffer, int offset, int count) => _inner.Read(buffer, offset, count); - public override int Read(Span buffer) => _inner.Read(buffer); - 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) - { - _inner.Write(buffer, offset, count); - return; - } - - lock (_switchLock) - { - if (!_isFallenBack && !_budget.CanAllocateInMemory(_inner.Position + count)) - SwitchToDiskCore(); - _inner.Write(buffer, offset, count); - } - } - - public override void Write(ReadOnlySpan buffer) - { - if (_isFallenBack) - { - _inner.Write(buffer); - return; - } - - lock (_switchLock) - { - if (!_isFallenBack && !_budget.CanAllocateInMemory(_inner.Position + buffer.Length)) - SwitchToDiskCore(); - _inner.Write(buffer); - } - } - - public override ValueTask WriteAsync(ReadOnlyMemory buffer, CancellationToken cancellationToken = default) - { - if (cancellationToken.IsCancellationRequested) - return ValueTask.FromCanceled(cancellationToken); - - Write(buffer.Span); - return ValueTask.CompletedTask; - } - - 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 SwitchToDiskCore() - { - if (_isFallenBack) - return; - - try - { - Directory.CreateDirectory(_fallbackDir); - - Span nameBuf = stackalloc char[40]; - "zdp_".AsSpan().CopyTo(nameBuf); - Guid.NewGuid().TryFormat(nameBuf[4..], out _, "N"); - ".tmp".AsSpan().CopyTo(nameBuf[36..]); - var path = Path.Combine(_fallbackDir, new string(nameBuf)); - - 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); - } -} \ No newline at end of file diff --git a/ProxyForge/Memory/MemoryBudget.cs b/ProxyForge/Memory/MemoryBudget.cs deleted file mode 100644 index 55ac5ea..0000000 --- a/ProxyForge/Memory/MemoryBudget.cs +++ /dev/null @@ -1,114 +0,0 @@ -using System.Runtime.InteropServices; - -namespace ProxyForge.Memory; - -internal sealed class MemoryBudget(long reserveMb, long maxCacheMb) -{ - private readonly long _reserveBytes = reserveMb * 1024L * 1024L; - private readonly long _maxCacheBytes = maxCacheMb * 1024L * 1024L; - private long _allocatedBytes; - - private long _memoryCachePacked; - private const long MemoryCacheIntervalMs = 100L; - - internal long AllocatedBytes => Volatile.Read(ref _allocatedBytes); - - internal bool CanAllocateInMemory(long requestedBytes) - { - if (requestedBytes <= 0) - return true; - - var limit = Math.Min(GetCachedAvailablePhysicalMemory() - _reserveBytes, _maxCacheBytes); - if (limit <= 0) - return false; - - var allocated = Volatile.Read(ref _allocatedBytes); - return allocated >= 0 && requestedBytes <= limit - allocated; - } - - internal bool TryAllocate(long requestedBytes) - { - if (requestedBytes <= 0) - return true; - - while (true) - { - var available = GetCachedAvailablePhysicalMemory(); - var current = Volatile.Read(ref _allocatedBytes); - if (current < 0) - return false; - - var limit = Math.Min(available - _reserveBytes, _maxCacheBytes); - if (limit <= 0) - return false; - - var next = current + requestedBytes; - if (next < 0 || next > limit) - return false; - - if (Interlocked.CompareExchange(ref _allocatedBytes, next, current) == current) - return true; - } - } - - internal void RecordAllocation(long bytes) - { - if (bytes > 0) - Interlocked.Add(ref _allocatedBytes, bytes); - } - - internal void RecordDeallocation(long bytes) - { - if (bytes > 0) - Interlocked.Add(ref _allocatedBytes, -bytes); - } - - internal static long EstimateProxySize(long originalFileSize, float scale) - => (long)(originalFileSize * scale * scale * 0.3); - - private static uint WrapSafeElapsedMs(uint nowMs, uint cachedMs) => - unchecked(nowMs - cachedMs); - - private long GetCachedAvailablePhysicalMemory() - { - var nowMs = (uint)Environment.TickCount64; - var packed = Interlocked.Read(ref _memoryCachePacked); - var cachedMs = (uint)(packed >> 32); - - if (WrapSafeElapsedMs(nowMs, cachedMs) < (uint)MemoryCacheIntervalMs) - { - var memKb = (uint)packed; - if (memKb > 0) - return (long)memKb * 1024L; - } - - var fresh = GetAvailablePhysicalMemory(); - var freshKbCapped = (uint)Math.Min(fresh >> 10, (long)uint.MaxValue); - Interlocked.Exchange(ref _memoryCachePacked, ((long)nowMs << 32) | freshKbCapped); - return fresh; - } - - [StructLayout(LayoutKind.Sequential)] - private struct MEMORYSTATUSEX - { - public uint dwLength; - public uint dwMemoryLoad; - public ulong ullTotalPhys; - public ulong ullAvailPhys; - public ulong ullTotalPageFile; - public ulong ullAvailPageFile; - public ulong ullTotalVirtual; - public ulong ullAvailVirtual; - public ulong ullAvailExtendedVirtual; - } - - [DllImport("kernel32.dll", SetLastError = true)] - [return: MarshalAs(UnmanagedType.Bool)] - private static extern bool GlobalMemoryStatusEx(ref MEMORYSTATUSEX lpBuffer); - - private static long GetAvailablePhysicalMemory() - { - var status = new MEMORYSTATUSEX { dwLength = (uint)Marshal.SizeOf() }; - return GlobalMemoryStatusEx(ref status) ? (long)status.ullAvailPhys : 2L * 1024 * 1024 * 1024; - } -} \ No newline at end of file diff --git a/ProxyForge/Plugin/PluginHost.cs b/ProxyForge/Plugin/PluginHost.cs index 180be30..99b807b 100644 --- a/ProxyForge/Plugin/PluginHost.cs +++ b/ProxyForge/Plugin/PluginHost.cs @@ -2,10 +2,8 @@ using ProxyForge.Core; using ProxyForge.Detection; using ProxyForge.Interfaces; -using ProxyForge.Memory; using ProxyForge.Services; using ProxyForge.Settings; -using ProxyForge.Streaming; using ProxyForge.ViewModels; using ProxyForge.Views; using System.IO; @@ -23,26 +21,20 @@ internal sealed class PluginHost : IDisposable private GenerationPopupView? _popupView; internal static PluginHost? Instance => _instance; - internal MemoryBudget Budget { get; } internal ProxyCacheManager CacheManager { get; } internal IExportDetector ExportDetector { get; } - internal ChunkAllocator ChunkAllocator { get; } internal string FallbackDirectory { get; } internal string TmpDirectory { get; } internal VideoCacheDatabase? VideoCache { get; } private PluginHost( - MemoryBudget budget, IProxyEncoderFactory encoderFactory, IExportDetector exportDetector, - ChunkAllocator chunkAllocator, string fallbackDirectory, string tmpDirectory, VideoCacheDatabase? videoCache) { - Budget = budget; ExportDetector = exportDetector; - ChunkAllocator = chunkAllocator; FallbackDirectory = fallbackDirectory; TmpDirectory = tmpDirectory; VideoCache = videoCache; @@ -54,21 +46,15 @@ internal sealed class PluginHost : IDisposable private static PluginHost CreateDefault() { var settings = ProxyForgeSettings.Default; - var budget = new MemoryBudget(settings.MemoryReserveMb, settings.MaxCacheMemoryMb); var pluginDir = Path.GetDirectoryName(typeof(PluginHost).Assembly.Location) ?? AppDirectories.TemporaryDirectory; var cacheDir = Path.Combine(pluginDir, "cache"); var tmpDirectory = Path.Combine(cacheDir, "tmp"); - var chunkAllocator = new ChunkAllocator(65536); - MfSession.AddRef(); WindowThemeRegistry.Register(new WindowThemeService()); - IProxyEncoderFactory encoderFactory = new MfProxyEncoderFactory( - budget, + IProxyEncoderFactory encoderFactory = new FFmpegProxyEncoderFactory( tmpDirectory, - static () => new EncoderConfig( - ProxyForgeSettings.Default.EnableHardwareAcceleration, - ProxyForgeSettings.Default.EnableDiskFallback)); + static () => new EncoderConfig(ProxyForgeSettings.Default.EnableHardwareAcceleration)); VideoCacheDatabase? videoCache = null; if (settings.EnableVideoCache) @@ -81,7 +67,7 @@ internal sealed class PluginHost : IDisposable } IExportDetector exportDetector = new ExportDetector(); - return new PluginHost(budget, encoderFactory, exportDetector, chunkAllocator, tmpDirectory, tmpDirectory, videoCache); + return new PluginHost(encoderFactory, exportDetector, tmpDirectory, tmpDirectory, videoCache); } internal static PluginHost EnsureInitialized() @@ -164,10 +150,7 @@ internal sealed class PluginHost : IDisposable CacheManager.Dispose(); VideoCache?.Dispose(); - ChunkAllocator.Dispose(); CleanupTmpDirectory(); - - MfSession.Release(); } private void CleanupTmpDirectory() diff --git a/ProxyForge/Plugin/ProxyForgePlugin.cs b/ProxyForge/Plugin/ProxyForgePlugin.cs index b5b2c55..35c48b8 100644 --- a/ProxyForge/Plugin/ProxyForgePlugin.cs +++ b/ProxyForge/Plugin/ProxyForgePlugin.cs @@ -1,6 +1,5 @@ using ProxyForge.Core; using ProxyForge.Settings; -using ProxyForge.Streaming; using System.Diagnostics; using System.IO; using System.Windows; @@ -56,10 +55,9 @@ internal sealed class ProxyForgePlugin : IVideoFileSourcePlugin { var cached = host.CacheManager.TryGetProxy(filePath, proxyScale); if (cached is { IsValid: true }) - return LoadFromCache(devices, cached, host.FallbackDirectory); + return LoadFromCache(devices, cached); - var initialSource = CreateLightweightSource(devices, filePath) - ?? WrapFromOther(devices, filePath); + var initialSource = LoadRaw(devices, filePath); if (initialSource is null) return null; @@ -84,28 +82,12 @@ internal sealed class ProxyForgePlugin : IVideoFileSourcePlugin return null; } - private static IVideoFileSource? CreateLightweightSource( - IGraphicsDevicesAndContext devices, string filePath) - { - try - { - return LightweightVideoFileSource.TryCreate(filePath, devices); - } - catch (Exception ex) - { - Debug.WriteLine(string.Concat("[ProxyForge] LightweightSource failed for ", filePath, ": ", ex.Message)); - return null; - } - } - private static IVideoFileSource? LoadFromCache( - IGraphicsDevicesAndContext devices, ProxyCacheEntry entry, string fallbackDir) + IGraphicsDevicesAndContext devices, ProxyCacheEntry entry) { try { - var tempPath = entry.GetOrCreateTempFilePath(fallbackDir); - - var source = LoadRaw(devices, tempPath); + var source = LoadRaw(devices, entry.GetFilePath()); if (source is null) return null; @@ -120,32 +102,8 @@ internal sealed class ProxyForgePlugin : IVideoFileSourcePlugin } } - private static IVideoFileSource? WrapFromOther(IGraphicsDevicesAndContext devices, string filePath) - { - var source = LoadRaw(devices, filePath); - return source is not null ? new ProxyForgeVideoSource(source, devices) : null; - } - - private static IVideoFileSource? LoadRaw(IGraphicsDevicesAndContext devices, string filePath) - { - foreach (var plugin in PluginLoader.VideoFileSourcePlugins) - { - if (plugin is ProxyForgePlugin) - continue; - - try - { - var s = plugin.CreateVideoFileSource(devices, filePath); - if (s is not null) - return s; - } - catch (Exception ex) - { - Debug.WriteLine(string.Concat("[ProxyForge] Plugin ", plugin.Name, " failed for ", filePath, ": ", ex.Message)); - } - } - return null; - } + private static IVideoFileSource? LoadRaw(IGraphicsDevicesAndContext devices, string filePath) => + Ymm4VideoSourceLoader.Load(devices, filePath); private static IVideoFileSource? TryLoadProxy( IGraphicsDevicesAndContext devices, string filePath, float proxyScale, PluginHost host) @@ -154,7 +112,7 @@ internal sealed class ProxyForgePlugin : IVideoFileSourcePlugin if (cached is null || !cached.IsValid) return null; - var source = LoadFromCache(devices, cached, host.FallbackDirectory); + var source = LoadFromCache(devices, cached); if (source is null) host.CacheManager.RemoveProxy(filePath, proxyScale); diff --git a/ProxyForge/Plugin/Ymm4VideoSourceLoader.cs b/ProxyForge/Plugin/Ymm4VideoSourceLoader.cs new file mode 100644 index 0000000..b8c66d6 --- /dev/null +++ b/ProxyForge/Plugin/Ymm4VideoSourceLoader.cs @@ -0,0 +1,35 @@ +using System.Diagnostics; +using YukkuriMovieMaker.Commons; +using YukkuriMovieMaker.Plugin; +using YukkuriMovieMaker.Plugin.FileSource; + +namespace ProxyForge.Plugin; + +internal delegate IVideoFileSource? Ymm4VideoSourceFactory( + IGraphicsDevicesAndContext devices, string filePath); + +internal static class Ymm4VideoSourceLoader +{ + internal static IVideoFileSource? Load(IGraphicsDevicesAndContext devices, string filePath) + { + foreach (var plugin in PluginLoader.VideoFileSourcePlugins) + { + if (plugin is ProxyForgePlugin) + continue; + + try + { + var source = plugin.CreateVideoFileSource(devices, filePath); + if (source is not null) + return source; + } + catch (Exception ex) + { + Debug.WriteLine(string.Concat( + "[ProxyForge] Plugin ", plugin.Name, " failed for ", filePath, ": ", ex.Message)); + } + } + + return null; + } +} diff --git a/ProxyForge/Progress/ProxyGenerationItem.cs b/ProxyForge/Progress/ProxyGenerationItem.cs index 93cf695..8d724f0 100644 --- a/ProxyForge/Progress/ProxyGenerationItem.cs +++ b/ProxyForge/Progress/ProxyGenerationItem.cs @@ -59,19 +59,6 @@ public sealed class ProxyGenerationItem : Bindable set => Set(ref _statusMessage, value); } - private bool _isInMemory = true; - public bool IsInMemory - { - get => _isInMemory; - set - { - if (Set(ref _isInMemory, value)) - OnPropertyChanged(nameof(StorageText)); - } - } - - public string StorageText => _isInMemory ? Translate.StorageMemory : Translate.StorageDisk; - internal ProxyGenerationItem(string originalPath) { OriginalPath = originalPath; diff --git a/ProxyForge/ProxyForge.csproj b/ProxyForge/ProxyForge.csproj index 4253b88..cdda06c 100644 --- a/ProxyForge/ProxyForge.csproj +++ b/ProxyForge/ProxyForge.csproj @@ -81,6 +81,10 @@ $(YMM4DirPath)YukkuriMovieMaker.Plugin.dll false + + $(YMM4DirPath)YukkuriMovieMaker.Plugin.FileSource.FFmpeg.dll + false + $(YMM4DirPath)SharpGen.Runtime.COM.dll false @@ -104,6 +108,10 @@ + + + + diff --git a/ProxyForge/Resource/ResourceRegistry.cs b/ProxyForge/Resource/ResourceRegistry.cs deleted file mode 100644 index 0905476..0000000 --- a/ProxyForge/Resource/ResourceRegistry.cs +++ /dev/null @@ -1,83 +0,0 @@ -using System.Collections.Concurrent; -using System.Diagnostics; -using System.Runtime.InteropServices; - -namespace ProxyForge.Resource; - -internal sealed class ResourceRegistry : IDisposable -{ - private readonly ConcurrentDictionary _entries = new(); - private long _nextId; - private int _disposed; - - internal int Count => _entries.Count; - - internal ResourceHandle TrackComPtr(nint comPtr, string? debugName = null) - { - ObjectDisposedException.ThrowIf(Volatile.Read(ref _disposed) != 0, this); - if (comPtr == nint.Zero) - return ResourceHandle.Invalid; - - var id = Interlocked.Increment(ref _nextId); - _entries[id] = new RegistryEntry(id, comPtr, null, debugName); - return new ResourceHandle(id, this); - } - - internal ResourceHandle TrackDisposable(IDisposable disposable, string? debugName = null) - { - ObjectDisposedException.ThrowIf(Volatile.Read(ref _disposed) != 0, this); - - var id = Interlocked.Increment(ref _nextId); - _entries[id] = new RegistryEntry(id, nint.Zero, disposable, debugName); - return new ResourceHandle(id, this); - } - - internal void Release(long id) - { - if (!_entries.TryRemove(id, out var entry)) - return; - - ReleaseEntry(entry); - } - - internal void ReleaseAll() - { - foreach (var kvp in _entries) - { - if (_entries.TryRemove(kvp.Key, out var entry)) - ReleaseEntry(entry); - } - } - - private static void ReleaseEntry(RegistryEntry entry) - { - try - { - if (entry.ComPtr != nint.Zero) - Marshal.Release(entry.ComPtr); - - entry.Disposable?.Dispose(); - } - catch (Exception ex) - { - Debug.WriteLine(string.Concat("[ResourceRegistry] Release failed: ", ex.Message)); - } - } - - public void Dispose() - { - if (Interlocked.Exchange(ref _disposed, 1) != 0) - return; - - ReleaseAll(); - } - - private sealed record RegistryEntry(long Id, nint ComPtr, IDisposable? Disposable, string? DebugName); -} - -internal readonly struct ResourceHandle(long id, ResourceRegistry registry) : IDisposable -{ - internal static ResourceHandle Invalid => default; - - public void Dispose() => registry?.Release(id); -} \ No newline at end of file diff --git a/ProxyForge/Settings/ProxyForgeSettings.cs b/ProxyForge/Settings/ProxyForgeSettings.cs index 6cc1725..6ac587a 100644 --- a/ProxyForge/Settings/ProxyForgeSettings.cs +++ b/ProxyForge/Settings/ProxyForgeSettings.cs @@ -45,20 +45,6 @@ internal sealed class ProxyForgeSettings : SettingsBase set => Set(ref _gopSize, Math.Clamp(value, 1, 300)); } - private int _memoryReserveMb = 512; - public int MemoryReserveMb - { - get => _memoryReserveMb; - set => Set(ref _memoryReserveMb, Math.Clamp(value, 128, 8192)); - } - - private int _maxCacheMemoryMb = 2048; - public int MaxCacheMemoryMb - { - get => _maxCacheMemoryMb; - set => Set(ref _maxCacheMemoryMb, Math.Clamp(value, 256, 16384)); - } - private bool _autoGenerate = true; public bool AutoGenerate { @@ -87,13 +73,6 @@ internal sealed class ProxyForgeSettings : SettingsBase set => Set(ref _enableHardwareAcceleration, value); } - private bool _enableDiskFallback = true; - public bool EnableDiskFallback - { - get => _enableDiskFallback; - set => Set(ref _enableDiskFallback, value); - } - private bool _enableVideoCache = true; public bool EnableVideoCache { diff --git a/ProxyForge/Streaming/ChunkAllocator.cs b/ProxyForge/Streaming/ChunkAllocator.cs deleted file mode 100644 index 6cee983..0000000 --- a/ProxyForge/Streaming/ChunkAllocator.cs +++ /dev/null @@ -1,66 +0,0 @@ -using System.Buffers; -using System.Collections.Concurrent; -using System.Runtime.CompilerServices; - -namespace ProxyForge.Streaming; - -internal sealed class ChunkAllocator : IDisposable -{ - private readonly int _chunkSize; - private readonly ConcurrentBag _pool = []; - private long _allocatedCount; - private long _returnedCount; - private int _disposed; - - internal int ChunkSize => _chunkSize; - internal long ActiveCount => Volatile.Read(ref _allocatedCount) - Volatile.Read(ref _returnedCount); - - internal ChunkAllocator(int chunkSize = 65536) - { - ArgumentOutOfRangeException.ThrowIfLessThan(chunkSize, 4096); - _chunkSize = chunkSize; - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - internal byte[] Rent() - { - ObjectDisposedException.ThrowIf(Volatile.Read(ref _disposed) != 0, this); - Interlocked.Increment(ref _allocatedCount); - - if (_pool.TryTake(out var buffer)) - return buffer; - - return ArrayPool.Shared.Rent(_chunkSize); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - internal void Return(byte[] buffer) - { - if (buffer is null) - return; - - Interlocked.Increment(ref _returnedCount); - - if (Volatile.Read(ref _disposed) != 0) - { - ArrayPool.Shared.Return(buffer); - return; - } - - _pool.Add(buffer); - } - - internal void DrainPool() - { - while (_pool.TryTake(out var buffer)) - ArrayPool.Shared.Return(buffer); - } - - public void Dispose() - { - if (Interlocked.Exchange(ref _disposed, 1) != 0) - return; - - DrainPool(); - } -} \ No newline at end of file diff --git a/ProxyForge/Streaming/LightweightVideoFileSource.cs b/ProxyForge/Streaming/LightweightVideoFileSource.cs deleted file mode 100644 index 811c51c..0000000 --- a/ProxyForge/Streaming/LightweightVideoFileSource.cs +++ /dev/null @@ -1,439 +0,0 @@ -using ProxyForge.Interop; -using System.Numerics; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using Vortice.DCommon; -using Vortice.Direct2D1; -using Vortice.Direct2D1.Effects; -using Vortice.DXGI; -using Vortice.Mathematics; -using YukkuriMovieMaker.Commons; -using YukkuriMovieMaker.Plugin.FileSource; - -namespace ProxyForge.Streaming; - -internal sealed class LightweightVideoFileSource : IVideoFileSource -{ - private readonly string _filePath; - private readonly ID2D1Bitmap _bitmap; - private readonly AffineTransform2D _effect; - private readonly ID2D1Image _output; - private readonly uint _width; - private readonly uint _height; - private readonly double _fps; - private readonly TimeSpan _duration; - private byte[]? _bgraBuffer; - private int _lastFrameIndex = -1; - private bool _hasFrame; - private int _disposed; - - public TimeSpan Duration => _duration; - public ID2D1Image Output => _output; - - private LightweightVideoFileSource( - string filePath, - ID2D1Bitmap bitmap, - AffineTransform2D effect, - uint width, uint height, double fps, TimeSpan duration) - { - _filePath = filePath; - _bitmap = bitmap; - _effect = effect; - _output = effect.Output; - _width = width; - _height = height; - _fps = fps; - _duration = duration; - } - - internal static LightweightVideoFileSource? TryCreate(string filePath, IGraphicsDevicesAndContext devices) - { - if (string.IsNullOrEmpty(filePath)) - return null; - - IMFAttributes? attrs = null; - IMFSourceReader? reader = null; - - try - { - MfSession.AddRef(); - - HResultExtensions.ThrowOnFailure( - MfNativeMethods.MFCreateAttributes(out attrs, 2), "MFCreateAttributes"); - attrs.SetUINT32(MfAttributeKeys.MF_LOW_LATENCY, 1); - - var hr = MfNativeMethods.MFCreateSourceReaderFromURL(filePath, attrs, out reader); - if (HResultExtensions.Failed(hr) || reader is null) - { - MfSession.Release(); - return null; - } - - reader.SetStreamSelection(0xFFFFFFFE, false); - reader.SetStreamSelection(MfNativeMethods.MF_SOURCE_READER_FIRST_VIDEO_STREAM, true); - - uint width = 1920, height = 1080; - var fps = 30.0; - - hr = reader.GetCurrentMediaType( - MfNativeMethods.MF_SOURCE_READER_FIRST_VIDEO_STREAM, out var nativeType); - if (HResultExtensions.Succeeded(hr) && nativeType is not null) - { - try - { - if (HResultExtensions.Succeeded( - nativeType.GetUINT64(MfAttributeKeys.MF_MT_FRAME_SIZE, out var packed))) - { - var w = (uint)(packed >> 32); - var h = (uint)(packed & 0xFFFFFFFF); - if (w > 0) width = w; - if (h > 0) height = h; - } - - if (HResultExtensions.Succeeded( - nativeType.GetUINT64(MfAttributeKeys.MF_MT_FRAME_RATE, out var packedRate))) - { - var num = (uint)(packedRate >> 32); - var den = (uint)(packedRate & 0xFFFFFFFF); - if (num > 0 && den > 0) - fps = (double)num / den; - } - } - finally - { - Marshal.FinalReleaseComObject(nativeType); - } - } - - var duration = QueryDuration(reader); - - Marshal.FinalReleaseComObject(reader); - reader = null; - MfSession.Release(); - - var pixelFormat = new PixelFormat(Format.B8G8R8A8_UNorm, Vortice.DCommon.AlphaMode.Ignore); - var bitmapProps = new BitmapProperties(pixelFormat); - var bitmap = devices.DeviceContext.CreateBitmap( - new SizeI((int)width, (int)height), bitmapProps); - - var effect = new AffineTransform2D(devices.DeviceContext); - effect.SetInput(0, bitmap, true); - effect.TransformMatrix = Matrix3x2.CreateTranslation(-(int)width / 2f, -(int)height / 2f); - - return new LightweightVideoFileSource( - filePath, bitmap, effect, width, height, fps, duration); - } - catch - { - if (reader is not null) - { - try { Marshal.FinalReleaseComObject(reader); } catch { } - MfSession.Release(); - } - return null; - } - finally - { - if (attrs is not null) - Marshal.FinalReleaseComObject(attrs); - } - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public void Update(TimeSpan time) - { - if (Volatile.Read(ref _disposed) != 0) - return; - - var frameIndex = GetFrameIndex(time); - if (frameIndex == _lastFrameIndex && _hasFrame) - return; - - ExtractFrame(time); - _lastFrameIndex = frameIndex; - } - - private void ExtractFrame(TimeSpan time) - { - IMFAttributes? attrs = null; - IMFSourceReader? reader = null; - var sessionAcquired = false; - - try - { - MfSession.AddRef(); - sessionAcquired = true; - - HResultExtensions.ThrowOnFailure( - MfNativeMethods.MFCreateAttributes(out attrs, 2)); - attrs.SetUINT32(MfAttributeKeys.MF_LOW_LATENCY, 1); - - var hr = MfNativeMethods.MFCreateSourceReaderFromURL(_filePath, attrs, out reader); - if (HResultExtensions.Failed(hr) || reader is null) - return; - - reader.SetStreamSelection(0xFFFFFFFE, false); - reader.SetStreamSelection(MfNativeMethods.MF_SOURCE_READER_FIRST_VIDEO_STREAM, true); - - var isNv12 = false; - IMFMediaType? outType = null; - try - { - HResultExtensions.ThrowOnFailure(MfNativeMethods.MFCreateMediaType(out outType)); - outType.SetGUID(MfAttributeKeys.MF_MT_MAJOR_TYPE, MfAttributeKeys.MFMediaType_Video); - outType.SetGUID(MfAttributeKeys.MF_MT_SUBTYPE, MfAttributeKeys.MFVideoFormat_NV12); - - hr = reader.SetCurrentMediaType( - MfNativeMethods.MF_SOURCE_READER_FIRST_VIDEO_STREAM, nint.Zero, outType); - - if (HResultExtensions.Succeeded(hr)) - { - isNv12 = true; - } - else - { - outType.SetGUID(MfAttributeKeys.MF_MT_SUBTYPE, MfAttributeKeys.MFVideoFormat_RGB32); - outType.SetUINT32(MfAttributeKeys.MF_SOURCE_READER_ENABLE_ADVANCED_VIDEO_PROCESSING, 1); - reader.SetCurrentMediaType( - MfNativeMethods.MF_SOURCE_READER_FIRST_VIDEO_STREAM, nint.Zero, outType); - } - } - finally - { - if (outType is not null) - Marshal.FinalReleaseComObject(outType); - } - - var targetHns = Math.Max(0, time.Ticks); - using var pv = PropVariant.FromInt64(targetHns); - reader.SetCurrentPosition(Guid.Empty, in pv); - - var frameDurationHns = _fps > 0 ? (long)(10_000_000.0 / _fps) : 333_333L; - const int maxReads = 16; - - for (var i = 0; i < maxReads; i++) - { - hr = reader.ReadSample( - MfNativeMethods.MF_SOURCE_READER_FIRST_VIDEO_STREAM, - 0, out _, out var flags, out var timestamp, out var sample); - - if (HResultExtensions.Failed(hr) || - (flags & MfNativeMethods.MF_SOURCE_READERF_ENDOFSTREAM) != 0 || - (flags & MfNativeMethods.MF_SOURCE_READERF_ERROR) != 0) - { - if (sample is not null) - Marshal.FinalReleaseComObject(sample); - break; - } - - if (sample is null) - continue; - - if (timestamp >= targetHns - frameDurationHns) - { - if (isNv12) - RenderNv12Sample(sample); - else - RenderRgb32Sample(sample); - _hasFrame = true; - Marshal.FinalReleaseComObject(sample); - break; - } - - Marshal.FinalReleaseComObject(sample); - } - } - catch - { - } - finally - { - if (reader is not null) - { - try { Marshal.FinalReleaseComObject(reader); } catch { } - } - if (attrs is not null) - { - try { Marshal.FinalReleaseComObject(attrs); } catch { } - } - if (sessionAcquired) - MfSession.Release(); - } - } - - private unsafe void RenderNv12Sample(IMFSample sample) - { - sample.GetBufferByIndex(0, out var buffer); - if (buffer is null) - return; - - try - { - var hr = buffer.Lock(out var dataPtr, out _, out var currentLength); - if (HResultExtensions.Failed(hr)) - return; - - try - { - var w = (int)_width; - var h = (int)_height; - if (w <= 0 || h <= 0 || currentLength <= 0) - return; - - var alignedH = currentLength * 2 / (w * 3); - if (alignedH < h) - alignedH = h; - - var bgraSize = w * h * 4; - var buf = _bgraBuffer; - if (buf is null || buf.Length < bgraSize) - _bgraBuffer = buf = new byte[bgraSize]; - - var bgraStride = w * 4; - - fixed (byte* bgraBase = buf) - { - byte* yPlane = (byte*)dataPtr; - byte* uvPlane = yPlane + w * alignedH; - - for (var y = 0; y < h; y++) - { - byte* yRow = yPlane + y * w; - byte* uvRow = uvPlane + (y >> 1) * w; - byte* dst = bgraBase + y * bgraStride; - - for (var x = 0; x < w; x++) - { - var yv = yRow[x]; - var u = uvRow[x & ~1]; - var v = uvRow[(x & ~1) + 1]; - - var c = yv - 16; - var d = u - 128; - var e = v - 128; - - var r = (298 * c + 409 * e + 128) >> 8; - var g = (298 * c - 100 * d - 208 * e + 128) >> 8; - var b = (298 * c + 516 * d + 128) >> 8; - - dst[0] = (byte)(b < 0 ? 0 : b > 255 ? 255 : b); - dst[1] = (byte)(g < 0 ? 0 : g > 255 ? 255 : g); - dst[2] = (byte)(r < 0 ? 0 : r > 255 ? 255 : r); - dst[3] = 255; - dst += 4; - } - } - - _bitmap.CopyFromMemory((nint)bgraBase, bgraStride); - } - } - finally - { - buffer.Unlock(); - } - } - finally - { - Marshal.FinalReleaseComObject(buffer); - } - } - - private void RenderRgb32Sample(IMFSample sample) - { - sample.GetBufferByIndex(0, out var buffer); - if (buffer is null) - return; - - try - { - var minPitch = (int)_width * 4; - - if (buffer is IMF2DBuffer buf2D) - { - var hr = buf2D.Lock2D(out var scanline, out var pitch); - if (HResultExtensions.Succeeded(hr)) - { - try - { - if (Math.Abs(pitch) >= minPitch) - _bitmap.CopyFromMemory(scanline, Math.Abs(pitch)); - } - finally - { - buf2D.Unlock2D(); - } - return; - } - } - - { - var hr = buffer.Lock(out var ptr, out _, out var currentLength); - if (HResultExtensions.Failed(hr)) - return; - - try - { - if (currentLength >= minPitch * (int)_height) - _bitmap.CopyFromMemory(ptr, minPitch); - } - finally - { - buffer.Unlock(); - } - } - } - finally - { - Marshal.FinalReleaseComObject(buffer); - } - } - - public int GetFrameIndex(TimeSpan time) => - _fps > 0 ? (int)(time.TotalSeconds * _fps) : 0; - - private static TimeSpan QueryDuration(IMFSourceReader reader) - { - var pvPtr = Marshal.AllocHGlobal(24); - try - { - unsafe { new Span((void*)pvPtr, 24).Clear(); } - - var hr = reader.GetPresentationAttribute( - MfNativeMethods.MF_SOURCE_READER_MEDIASOURCE, - MfAttributeKeys.MF_PD_DURATION, - pvPtr); - - if (HResultExtensions.Succeeded(hr)) - { - var vt = Marshal.ReadInt16(pvPtr); - if (vt is 20 or 21) - return new TimeSpan(Marshal.ReadInt64(pvPtr, 8)); - } - - return TimeSpan.Zero; - } - catch - { - return TimeSpan.Zero; - } - finally - { - MfNativeMethods.PropVariantClear(pvPtr); - Marshal.FreeHGlobal(pvPtr); - } - } - - public void Dispose() - { - if (Interlocked.Exchange(ref _disposed, 1) != 0) - return; - - _output.Dispose(); - _effect.SetInput(0, null, true); - _effect.Dispose(); - _bitmap.Dispose(); - _bgraBuffer = null; - - GC.SuppressFinalize(this); - } -} \ No newline at end of file diff --git a/ProxyForge/Streaming/MfSession.cs b/ProxyForge/Streaming/MfSession.cs deleted file mode 100644 index 8641ade..0000000 --- a/ProxyForge/Streaming/MfSession.cs +++ /dev/null @@ -1,28 +0,0 @@ -using ProxyForge.Interop; - -namespace ProxyForge.Streaming; - -internal static class MfSession -{ - private static int _refCount; - private static readonly object Lock = new(); - - internal static void AddRef() - { - lock (Lock) - { - if (Interlocked.Increment(ref _refCount) == 1) - HResultExtensions.ThrowOnFailure( - MfNativeMethods.MFStartup(MfNativeMethods.MF_VERSION, 0), "MFStartup"); - } - } - - internal static void Release() - { - lock (Lock) - { - if (Interlocked.Decrement(ref _refCount) == 0) - MfNativeMethods.MFShutdown(); - } - } -} \ No newline at end of file diff --git a/ProxyForge/Streaming/StreamingMfEncoder.cs b/ProxyForge/Streaming/StreamingMfEncoder.cs deleted file mode 100644 index 9680a54..0000000 --- a/ProxyForge/Streaming/StreamingMfEncoder.cs +++ /dev/null @@ -1,596 +0,0 @@ -using ProxyForge.Core; -using ProxyForge.Interfaces; -using ProxyForge.Interop; -using ProxyForge.Memory; -using ProxyForge.Progress; -using System.IO; -using System.Runtime.InteropServices; - -namespace ProxyForge.Streaming; - -internal sealed class StreamingMfEncoder : IProxyEncoder -{ - private readonly MemoryBudget _memoryBudget; - private readonly string _fallbackDirectory; - private readonly EncoderConfig _config; - private readonly ChunkAllocator _chunkAllocator; - private int _disposed; - - internal StreamingMfEncoder( - MemoryBudget memoryBudget, - string fallbackDirectory, - EncoderConfig config, - ChunkAllocator chunkAllocator) - { - _memoryBudget = memoryBudget; - _fallbackDirectory = fallbackDirectory; - _config = config; - _chunkAllocator = chunkAllocator; - } - - public async Task EncodeAsync( - string inputPath, float scale, float bitrateFactor, int gopSize, - ProxyGenerationItem? progressItem, CancellationToken cancellationToken) - { - ObjectDisposedException.ThrowIf(Volatile.Read(ref _disposed) != 0, this); - ValidateInputPath(inputPath); - - ProxyCacheEntry? entry = null; - - try - { - cancellationToken.ThrowIfCancellationRequested(); - - var result = await Task.Run(() => EncodeCoreInMemory( - inputPath, scale, bitrateFactor, gopSize, - progressItem, cancellationToken), CancellationToken.None).ConfigureAwait(false); - - cancellationToken.ThrowIfCancellationRequested(); - - entry = new ProxyCacheEntry(inputPath, result.EffectiveScale, _memoryBudget.RecordDeallocation) - { - ProxyWidth = result.ProxyWidth, - ProxyHeight = result.ProxyHeight - }; - - if (result.Data is not null) - { - _memoryBudget.RecordAllocation(result.DataLength); - entry.SetMemoryData(result.Data, result.DataLength); - } - else if (result.DiskPath is not null) - { - var fi = new FileInfo(result.DiskPath); - entry.SetDiskPath(result.DiskPath, fi.Exists ? fi.Length : 0); - } - - return entry; - } - catch - { - entry?.Dispose(); - throw; - } - } - - private readonly record struct EncodeResult( - uint ProxyWidth, uint ProxyHeight, float EffectiveScale, - byte[]? Data, int DataLength, string? DiskPath); - - private EncodeResult EncodeCoreInMemory( - string inputPath, float scale, float bitrateFactor, int gopSize, - ProxyGenerationItem? progressItem, CancellationToken cancellationToken) - { - IMFSourceReader? reader = null; - IMFSinkWriter? writer = null; - IMFAttributes? readerAttrs = null; - IMFAttributes? writerAttrs = null; - IMFMediaType? outputType = null; - IMFAttributes? encoderParams = null; - IMFMediaType? converterInputType = null; - IMFMediaType? converterOutputType = null; - nint transformPtr = nint.Zero; - nint comStreamPtr = nint.Zero; - nint byteStreamPtr = nint.Zero; - - try - { - MfSession.AddRef(); - - HResultExtensions.ThrowOnFailure(MfNativeMethods.MFCreateAttributes(out readerAttrs, 4)); - readerAttrs.SetUINT32(MfAttributeKeys.MF_SOURCE_READER_ENABLE_ADVANCED_VIDEO_PROCESSING, 1u); - readerAttrs.SetUINT32(MfAttributeKeys.MF_LOW_LATENCY, 1u); - if (_config.EnableHardwareAcceleration) - readerAttrs.SetUINT32(MfAttributeKeys.MF_READWRITE_ENABLE_HARDWARE_TRANSFORMS, 1u); - - HResultExtensions.ThrowOnFailure( - MfNativeMethods.MFCreateSourceReaderFromURL(inputPath, readerAttrs, out reader)); - - reader.SetStreamSelection(0xFFFFFFFE, false); - reader.SetStreamSelection(MfNativeMethods.MF_SOURCE_READER_FIRST_VIDEO_STREAM, true); - - ExtractMetadata(reader, out var origWidth, out var origHeight, out var fps, out var durationHns); - - var proxyWidth = AlignTo16((uint)(origWidth * scale)); - var proxyHeight = AlignTo16((uint)(origHeight * scale)); - var bitrate = Math.Max((uint)(proxyWidth * proxyHeight * fps * 0.07 * bitrateFactor), 100_000u); - - var readerOutputType = ConfigureReaderOutput(reader, proxyWidth, proxyHeight, origWidth, origHeight, fps); - Guid readerSubtype; - try - { - readerOutputType.GetGUID(MfAttributeKeys.MF_MT_SUBTYPE, out readerSubtype); - } - finally - { - Marshal.ReleaseComObject(readerOutputType); - } - - var sinkInputSubtype = readerSubtype; - - HResultExtensions.ThrowOnFailure(MfNativeMethods.MFCreateAttributes(out writerAttrs, 4)); - if (_config.EnableHardwareAcceleration) - writerAttrs.SetUINT32(MfAttributeKeys.MF_READWRITE_ENABLE_HARDWARE_TRANSFORMS, 1u); - writerAttrs.SetUINT32(MfAttributeKeys.MF_SINK_WRITER_DISABLE_THROTTLING, 1u); - - HResultExtensions.ThrowOnFailure( - MfNativeMethods.CreateStreamOnHGlobal(nint.Zero, true, out comStreamPtr)); - HResultExtensions.ThrowOnFailure( - MfNativeMethods.MFCreateMFByteStreamOnStream(comStreamPtr, out byteStreamPtr)); - - HResultExtensions.ThrowOnFailure( - MfNativeMethods.MFCreateSinkWriterFromURL("output.mp4", byteStreamPtr, writerAttrs, out writer)); - - HResultExtensions.ThrowOnFailure(MfNativeMethods.MFCreateMediaType(out outputType)); - outputType.SetGUID(MfAttributeKeys.MF_MT_MAJOR_TYPE, MfAttributeKeys.MFMediaType_Video); - outputType.SetGUID(MfAttributeKeys.MF_MT_SUBTYPE, MfAttributeKeys.MFVideoFormat_H264); - outputType.SetUINT64(MfAttributeKeys.MF_MT_FRAME_SIZE, MfNativeMethods.PackSize(proxyWidth, proxyHeight)); - outputType.SetUINT64(MfAttributeKeys.MF_MT_FRAME_RATE, MfNativeMethods.PackRatio((uint)Math.Max(1, Math.Round(fps)), 1)); - outputType.SetUINT32(MfAttributeKeys.MF_MT_AVG_BITRATE, bitrate); - outputType.SetUINT32(MfAttributeKeys.MF_MT_INTERLACE_MODE, 2u); - outputType.SetUINT32(MfAttributeKeys.MF_MT_MPEG2_PROFILE, 77u); - - HResultExtensions.ThrowOnFailure(writer.AddStream(outputType, out var streamIndex)); - - HResultExtensions.ThrowOnFailure(MfNativeMethods.MFCreateAttributes(out encoderParams, 2)); - encoderParams.SetUINT32(MfGuids.MF_MT_MAX_KEYFRAME_SPACING, (uint)Math.Max(1, gopSize)); - - IMFMediaType sinkInputType; - HResultExtensions.ThrowOnFailure(MfNativeMethods.MFCreateMediaType(out sinkInputType)); - try - { - sinkInputType.SetGUID(MfAttributeKeys.MF_MT_MAJOR_TYPE, MfAttributeKeys.MFMediaType_Video); - sinkInputType.SetGUID(MfAttributeKeys.MF_MT_SUBTYPE, sinkInputSubtype); - sinkInputType.SetUINT64(MfAttributeKeys.MF_MT_FRAME_SIZE, MfNativeMethods.PackSize(proxyWidth, proxyHeight)); - sinkInputType.SetUINT64(MfAttributeKeys.MF_MT_FRAME_RATE, MfNativeMethods.PackRatio((uint)Math.Max(1, Math.Round(fps)), 1)); - sinkInputType.SetUINT32(MfAttributeKeys.MF_MT_INTERLACE_MODE, 2u); - - var sinkHr = writer.SetInputMediaType(streamIndex, sinkInputType, encoderParams); - - if (HResultExtensions.Failed(sinkHr) && !readerSubtype.Equals(MfAttributeKeys.MFVideoFormat_NV12)) - { - sinkInputType.SetGUID(MfAttributeKeys.MF_MT_SUBTYPE, MfAttributeKeys.MFVideoFormat_NV12); - sinkHr = writer.SetInputMediaType(streamIndex, sinkInputType, encoderParams); - if (HResultExtensions.Succeeded(sinkHr)) - sinkInputSubtype = MfAttributeKeys.MFVideoFormat_NV12; - } - - if (HResultExtensions.Failed(sinkHr) && !readerSubtype.Equals(MfAttributeKeys.MFVideoFormat_RGB32)) - { - sinkInputType.SetGUID(MfAttributeKeys.MF_MT_SUBTYPE, MfAttributeKeys.MFVideoFormat_RGB32); - sinkHr = writer.SetInputMediaType(streamIndex, sinkInputType, encoderParams); - if (HResultExtensions.Succeeded(sinkHr)) - sinkInputSubtype = MfAttributeKeys.MFVideoFormat_RGB32; - } - - HResultExtensions.ThrowOnFailure(sinkHr, "SetInputMediaType on SinkWriter"); - } - finally - { - Marshal.ReleaseComObject(sinkInputType); - } - - var needsColorConvert = !readerSubtype.Equals(sinkInputSubtype); - IMFTransform? colorConverter = null; - - if (needsColorConvert) - { - HResultExtensions.ThrowOnFailure( - MfNativeMethods.CoCreateInstance( - MfGuids.CLSID_CColorConvertDMO, - nint.Zero, 1u | 4u, - MfGuids.IID_IMFTransform, - out transformPtr), - "CoCreateInstance CColorConvertDMO"); - - colorConverter = (IMFTransform)Marshal.GetObjectForIUnknown(transformPtr); - - HResultExtensions.ThrowOnFailure(MfNativeMethods.MFCreateMediaType(out converterInputType)); - converterInputType.SetGUID(MfAttributeKeys.MF_MT_MAJOR_TYPE, MfAttributeKeys.MFMediaType_Video); - converterInputType.SetGUID(MfAttributeKeys.MF_MT_SUBTYPE, readerSubtype); - converterInputType.SetUINT64(MfAttributeKeys.MF_MT_FRAME_SIZE, MfNativeMethods.PackSize(proxyWidth, proxyHeight)); - converterInputType.SetUINT64(MfAttributeKeys.MF_MT_FRAME_RATE, MfNativeMethods.PackRatio((uint)Math.Max(1, Math.Round(fps)), 1)); - converterInputType.SetUINT32(MfAttributeKeys.MF_MT_INTERLACE_MODE, 2u); - HResultExtensions.ThrowOnFailure(colorConverter.SetInputType(0, converterInputType, 0), "SetInputType on converter"); - - HResultExtensions.ThrowOnFailure(MfNativeMethods.MFCreateMediaType(out converterOutputType)); - converterOutputType.SetGUID(MfAttributeKeys.MF_MT_MAJOR_TYPE, MfAttributeKeys.MFMediaType_Video); - converterOutputType.SetGUID(MfAttributeKeys.MF_MT_SUBTYPE, sinkInputSubtype); - converterOutputType.SetUINT64(MfAttributeKeys.MF_MT_FRAME_SIZE, MfNativeMethods.PackSize(proxyWidth, proxyHeight)); - converterOutputType.SetUINT64(MfAttributeKeys.MF_MT_FRAME_RATE, MfNativeMethods.PackRatio((uint)Math.Max(1, Math.Round(fps)), 1)); - converterOutputType.SetUINT32(MfAttributeKeys.MF_MT_INTERLACE_MODE, 2u); - HResultExtensions.ThrowOnFailure(colorConverter.SetOutputType(0, converterOutputType, 0), "SetOutputType on converter"); - - HResultExtensions.ThrowOnFailure(colorConverter.ProcessMessage(0u, nint.Zero), "ProcessMessage MFT_MESSAGE_NOTIFY_BEGIN_STREAMING"); - } - - HResultExtensions.ThrowOnFailure(writer.BeginWriting()); - - ProcessSamples(reader, writer, colorConverter, streamIndex, proxyWidth, proxyHeight, durationHns, progressItem, cancellationToken); - - HResultExtensions.ThrowOnFailure(writer.Finalize_()); - - if (writer is not null) { try { Marshal.ReleaseComObject(writer); } catch { } writer = null; } - - float effectiveScale = (float)proxyWidth / origWidth; - - var data = ExtractStreamData(comStreamPtr); - if (data is not null) - return new EncodeResult(proxyWidth, proxyHeight, effectiveScale, data.Value.buffer, data.Value.length, null); - - if (_config.EnableDiskFallback) - { - Directory.CreateDirectory(_fallbackDirectory); - var diskPath = WriteFallbackFile(comStreamPtr); - return new EncodeResult(proxyWidth, proxyHeight, effectiveScale, null, 0, diskPath); - } - - throw new InvalidOperationException("Insufficient memory for proxy and disk fallback is disabled."); - } - finally - { - if (converterOutputType is not null) { try { Marshal.ReleaseComObject(converterOutputType); } catch { } } - if (converterInputType is not null) { try { Marshal.ReleaseComObject(converterInputType); } catch { } } - if (transformPtr != nint.Zero) { try { Marshal.Release(transformPtr); } catch { } } - if (encoderParams is not null) { try { Marshal.ReleaseComObject(encoderParams); } catch { } } - if (outputType is not null) { try { Marshal.ReleaseComObject(outputType); } catch { } } - if (writer is not null) { try { Marshal.ReleaseComObject(writer); } catch { } } - if (writerAttrs is not null) { try { Marshal.ReleaseComObject(writerAttrs); } catch { } } - if (reader is not null) { try { Marshal.ReleaseComObject(reader); } catch { } } - if (readerAttrs is not null) { try { Marshal.ReleaseComObject(readerAttrs); } catch { } } - if (byteStreamPtr != nint.Zero) { try { Marshal.Release(byteStreamPtr); } catch { } } - if (comStreamPtr != nint.Zero) { try { Marshal.Release(comStreamPtr); } catch { } } - MfSession.Release(); - } - } - - private static (byte[] buffer, int length)? ExtractStreamData(nint comStreamPtr) - { - if (comStreamPtr == nint.Zero) - return null; - - try - { - var stream = (System.Runtime.InteropServices.ComTypes.IStream)Marshal.GetObjectForIUnknown(comStreamPtr); - System.Runtime.InteropServices.ComTypes.STATSTG stat; - stream.Stat(out stat, 1); - var size = (int)stat.cbSize; - - if (size <= 0) - return null; - - stream.Seek(0, 0, nint.Zero); - - var buffer = BufferPool.Rent(size); - stream.Read(buffer, size, nint.Zero); - return (buffer, size); - } - catch - { - return null; - } - } - - private string WriteFallbackFile(nint comStreamPtr) - { - Span fileNameBuf = stackalloc char[40]; - "zdp_".AsSpan().CopyTo(fileNameBuf); - Guid.NewGuid().TryFormat(fileNameBuf[4..], out _, "N"); - ".mp4".AsSpan().CopyTo(fileNameBuf[36..]); - var path = Path.Combine(_fallbackDirectory, new string(fileNameBuf)); - - var stream = (System.Runtime.InteropServices.ComTypes.IStream)Marshal.GetObjectForIUnknown(comStreamPtr); - System.Runtime.InteropServices.ComTypes.STATSTG stat; - stream.Stat(out stat, 1); - var size = (int)stat.cbSize; - - stream.Seek(0, 0, nint.Zero); - - using var fs = new FileStream(path, FileMode.CreateNew, FileAccess.Write, FileShare.None, 65536); - var chunk = new byte[65536]; - var remaining = size; - while (remaining > 0) - { - var toRead = Math.Min(remaining, chunk.Length); - stream.Read(chunk, toRead, nint.Zero); - fs.Write(chunk, 0, toRead); - remaining -= toRead; - } - - return path; - } - - private static void ExtractMetadata( - IMFSourceReader reader, - out uint width, out uint height, out double fps, out long durationHns) - { - width = 1920; - height = 1080; - fps = 30.0; - durationHns = 0; - - var hr = reader.GetCurrentMediaType( - MfNativeMethods.MF_SOURCE_READER_FIRST_VIDEO_STREAM, out var nativeType); - if (HResultExtensions.Failed(hr) || nativeType is null) - return; - - try - { - if (HResultExtensions.Succeeded( - nativeType.GetUINT64(MfAttributeKeys.MF_MT_FRAME_SIZE, out var packed))) - { - var w = (uint)(packed >> 32); - var h = (uint)(packed & 0xFFFFFFFF); - if (w > 0) width = w; - if (h > 0) height = h; - } - - if (HResultExtensions.Succeeded( - nativeType.GetUINT64(MfAttributeKeys.MF_MT_FRAME_RATE, out var packedRate))) - { - var num = (uint)(packedRate >> 32); - var den = (uint)(packedRate & 0xFFFFFFFF); - if (num > 0 && den > 0) - fps = (double)num / den; - } - } - finally - { - Marshal.ReleaseComObject(nativeType); - } - - durationHns = QueryDuration(reader); - } - - private static long QueryDuration(IMFSourceReader reader) - { - var pvPtr = Marshal.AllocHGlobal(24); - try - { - unsafe { new Span((void*)pvPtr, 24).Clear(); } - - var hr = reader.GetPresentationAttribute( - MfNativeMethods.MF_SOURCE_READER_MEDIASOURCE, - MfAttributeKeys.MF_PD_DURATION, - pvPtr); - - if (HResultExtensions.Succeeded(hr)) - { - var vt = Marshal.ReadInt16(pvPtr); - if (vt is 20 or 21) - return Marshal.ReadInt64(pvPtr, 8); - } - - return 0; - } - catch - { - return 0; - } - finally - { - MfNativeMethods.PropVariantClear(pvPtr); - Marshal.FreeHGlobal(pvPtr); - } - } - - private static IMFMediaType ConfigureReaderOutput( - IMFSourceReader reader, - uint proxyWidth, uint proxyHeight, - uint origWidth, uint origHeight, - double fps) - { - var candidates = new[] - { - (Subtype: MfAttributeKeys.MFVideoFormat_NV12, Width: proxyWidth, Height: proxyHeight), - (Subtype: MfAttributeKeys.MFVideoFormat_RGB32, Width: proxyWidth, Height: proxyHeight), - (Subtype: MfAttributeKeys.MFVideoFormat_NV12, Width: origWidth, Height: origHeight), - (Subtype: MfAttributeKeys.MFVideoFormat_RGB32, Width: origWidth, Height: origHeight), - }; - - foreach (var (subtype, width, height) in candidates) - { - IMFMediaType? attempt = null; - try - { - HResultExtensions.ThrowOnFailure(MfNativeMethods.MFCreateMediaType(out attempt)); - attempt.SetGUID(MfAttributeKeys.MF_MT_MAJOR_TYPE, MfAttributeKeys.MFMediaType_Video); - attempt.SetGUID(MfAttributeKeys.MF_MT_SUBTYPE, subtype); - attempt.SetUINT64(MfAttributeKeys.MF_MT_FRAME_SIZE, MfNativeMethods.PackSize(width, height)); - attempt.SetUINT64(MfAttributeKeys.MF_MT_FRAME_RATE, - MfNativeMethods.PackRatio((uint)Math.Max(1, Math.Round(fps)), 1)); - attempt.SetUINT32(MfAttributeKeys.MF_MT_INTERLACE_MODE, 2u); - - var hr = reader.SetCurrentMediaType( - MfNativeMethods.MF_SOURCE_READER_FIRST_VIDEO_STREAM, nint.Zero, attempt); - - if (HResultExtensions.Succeeded(hr)) - { - reader.GetCurrentMediaType( - MfNativeMethods.MF_SOURCE_READER_FIRST_VIDEO_STREAM, out var actual); - return actual; - } - - Marshal.ReleaseComObject(attempt); - attempt = null; - } - catch - { - if (attempt is not null) - Marshal.ReleaseComObject(attempt); - } - } - - throw new InvalidOperationException( - "Failed to configure source reader output. None of the candidate media types were accepted."); - } - - private static void ProcessSamples( - IMFSourceReader reader, IMFSinkWriter writer, - IMFTransform? colorConverter, uint streamIndex, - uint proxyWidth, uint proxyHeight, - long durationHns, ProxyGenerationItem? progressItem, - CancellationToken cancellationToken) - { - Action? applyProgress = progressItem is not null ? progressItem.ApplyPendingProgress : null; - var lastReportedCenti = 0L; - - IMFSample? reusableSample = null; - IMFMediaBuffer? reusableBuffer = null; - - if (colorConverter is not null) - { - var bufSize = (int)(proxyWidth * proxyHeight * 4); - HResultExtensions.ThrowOnFailure(MfNativeMethods.MFCreateSample(out var sample)); - HResultExtensions.ThrowOnFailure(MfNativeMethods.MFCreateMemoryBuffer(bufSize, out var buffer)); - sample.AddBuffer(buffer); - reusableSample = sample; - reusableBuffer = buffer; - } - - try - { - while (true) - { - cancellationToken.ThrowIfCancellationRequested(); - - var hr = reader.ReadSample( - MfNativeMethods.MF_SOURCE_READER_FIRST_VIDEO_STREAM, - 0, out _, out var flags, out var timestamp, out var sample); - - if (HResultExtensions.Failed(hr)) - { - if (sample is not null) Marshal.ReleaseComObject(sample); - HResultExtensions.ThrowOnFailure(hr); - } - - if ((flags & MfNativeMethods.MF_SOURCE_READERF_ERROR) != 0) - { - if (sample is not null) Marshal.ReleaseComObject(sample); - throw new InvalidOperationException("Source reader error during encode."); - } - - if ((flags & MfNativeMethods.MF_SOURCE_READERF_ENDOFSTREAM) != 0) - { - if (sample is not null) Marshal.ReleaseComObject(sample); - break; - } - - if (sample is null) - continue; - - try - { - var sampleToWrite = sample; - - if (colorConverter is not null && reusableSample is not null && reusableBuffer is not null) - { - var converted = ConvertSampleReusable(colorConverter, sample, reusableSample, reusableBuffer); - if (converted) - { - reusableSample.SetSampleTime(timestamp); - sample.GetSampleDuration(out var dur); - if (dur > 0) - reusableSample.SetSampleDuration(dur); - sampleToWrite = reusableSample; - } - } - - HResultExtensions.ThrowOnFailure(writer.WriteSample(streamIndex, sampleToWrite)); - - ReportProgress(progressItem, applyProgress, durationHns, timestamp, ref lastReportedCenti); - } - finally - { - Marshal.ReleaseComObject(sample); - } - } - } - finally - { - if (reusableBuffer is not null) - Marshal.ReleaseComObject(reusableBuffer); - if (reusableSample is not null) - Marshal.ReleaseComObject(reusableSample); - } - } - - private static bool ConvertSampleReusable( - IMFTransform converter, IMFSample inputSample, - IMFSample outputSample, IMFMediaBuffer outputBuffer) - { - var hr = converter.ProcessInput(0, inputSample, 0); - if (HResultExtensions.Failed(hr)) - return false; - - outputBuffer.SetCurrentLength(0); - - var outputBuf = new MFT_OUTPUT_DATA_BUFFER - { - dwStreamID = 0, - pSample = outputSample, - dwStatus = 0, - pEvents = null - }; - - hr = converter.ProcessOutput(0, 1, ref outputBuf, out _); - - return HResultExtensions.Succeeded(hr); - } - - private static void ReportProgress( - ProxyGenerationItem? progressItem, Action? applyProgress, - long durationHns, long timestamp, ref long lastReportedCenti) - { - if (progressItem is null || durationHns <= 0 || applyProgress is null) - return; - - var pct = Math.Min(99.0, (double)timestamp / durationHns * 100.0); - var centi = (long)(pct * 100); - if (centi - lastReportedCenti < 100 && pct < 99.0) - return; - - lastReportedCenti = centi; - progressItem.SetPendingProgress(pct); - System.Windows.Application.Current?.Dispatcher.BeginInvoke( - System.Windows.Threading.DispatcherPriority.Background, - applyProgress); - } - - 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)); - } - - public void Dispose() - { - Interlocked.Exchange(ref _disposed, 1); - } -} \ No newline at end of file diff --git a/ProxyForge/Streaming/StreamingMfEncoderFactory.cs b/ProxyForge/Streaming/StreamingMfEncoderFactory.cs deleted file mode 100644 index 70a6765..0000000 --- a/ProxyForge/Streaming/StreamingMfEncoderFactory.cs +++ /dev/null @@ -1,15 +0,0 @@ -using ProxyForge.Core; -using ProxyForge.Interfaces; -using ProxyForge.Memory; - -namespace ProxyForge.Streaming; - -internal sealed class StreamingMfEncoderFactory( - MemoryBudget memoryBudget, - string fallbackDirectory, - Func configProvider, - ChunkAllocator chunkAllocator) : IProxyEncoderFactory -{ - public IProxyEncoder Create() => - new StreamingMfEncoder(memoryBudget, fallbackDirectory, configProvider(), chunkAllocator); -} \ No newline at end of file diff --git a/ProxyForge/Streaming/VideoFileProbe.cs b/ProxyForge/Streaming/VideoFileProbe.cs deleted file mode 100644 index 3d046db..0000000 --- a/ProxyForge/Streaming/VideoFileProbe.cs +++ /dev/null @@ -1,123 +0,0 @@ -using ProxyForge.Interop; -using System.Runtime.InteropServices; - -namespace ProxyForge.Streaming; - -internal readonly record struct VideoMetadata( - uint Width, - uint Height, - double FrameRate, - long DurationHns, - bool IsValid -) -{ - internal TimeSpan Duration => new(DurationHns); - internal static VideoMetadata Invalid => new(0, 0, 0, 0, false); -} - -internal static class VideoFileProbe -{ - internal static VideoMetadata Probe(string filePath) - { - if (string.IsNullOrEmpty(filePath)) - return VideoMetadata.Invalid; - - IMFSourceReader? reader = null; - var sessionAcquired = false; - - try - { - MfSession.AddRef(); - sessionAcquired = true; - - var hr = MfNativeMethods.MFCreateSourceReaderFromURL(filePath, null, out reader); - if (HResultExtensions.Failed(hr) || reader is null) - return VideoMetadata.Invalid; - - hr = reader.GetCurrentMediaType( - MfNativeMethods.MF_SOURCE_READER_FIRST_VIDEO_STREAM, out var mediaType); - if (HResultExtensions.Failed(hr) || mediaType is null) - return VideoMetadata.Invalid; - - uint width = 0, height = 0; - var fps = 30.0; - - try - { - if (HResultExtensions.Succeeded( - mediaType.GetUINT64(MfAttributeKeys.MF_MT_FRAME_SIZE, out var packed))) - { - width = (uint)(packed >> 32); - height = (uint)(packed & 0xFFFFFFFF); - } - - if (HResultExtensions.Succeeded( - mediaType.GetUINT64(MfAttributeKeys.MF_MT_FRAME_RATE, out var packedRate))) - { - var num = (uint)(packedRate >> 32); - var den = (uint)(packedRate & 0xFFFFFFFF); - if (num > 0 && den > 0) - fps = (double)num / den; - } - } - finally - { - Marshal.ReleaseComObject(mediaType); - } - - var durationHns = QueryDuration(reader); - - if (width == 0) width = 1920; - if (height == 0) height = 1080; - - return new VideoMetadata(width, height, fps, durationHns, true); - } - catch - { - return VideoMetadata.Invalid; - } - finally - { - if (reader is not null) - { - try { Marshal.ReleaseComObject(reader); } - catch { } - } - - if (sessionAcquired) - MfSession.Release(); - } - } - - private static long QueryDuration(IMFSourceReader reader) - { - var pvPtr = Marshal.AllocHGlobal(24); - try - { - unsafe { new Span((void*)pvPtr, 24).Clear(); } - - var hr = reader.GetPresentationAttribute( - MfNativeMethods.MF_SOURCE_READER_MEDIASOURCE, - MfAttributeKeys.MF_PD_DURATION, - pvPtr); - - if (HResultExtensions.Succeeded(hr)) - { - var vt = Marshal.ReadInt16(pvPtr); - if (vt is 20 or 21) - return Marshal.ReadInt64(pvPtr, 8); - } - - return 0; - } - catch - { - return 0; - } - finally - { - MfNativeMethods.PropVariantClear(pvPtr); - Marshal.FreeHGlobal(pvPtr); - } - } -} \ No newline at end of file diff --git a/ProxyForge/Transcoding/FFmpegArguments.cs b/ProxyForge/Transcoding/FFmpegArguments.cs new file mode 100644 index 0000000..bf5a754 --- /dev/null +++ b/ProxyForge/Transcoding/FFmpegArguments.cs @@ -0,0 +1,134 @@ +using System.Collections.ObjectModel; +using System.Globalization; + +namespace ProxyForge.Transcoding; + +internal readonly record struct FFmpegEncodeRequest( + string OutputPath, + uint Width, + uint Height, + FrameRate FrameRate, + long BitrateBitsPerSecond, + int GopSize, + string VideoEncoder); + +internal static class FFmpegArguments +{ + internal const string SoftwareVideoEncoder = "h264"; + internal const string InputPixelFormat = "bgra"; + internal const string OutputPixelFormat = "yuv420p"; + internal const string ColorSpace = "bt709"; + + private const double BitratePerPixelPerSecond = 0.07; + private const long MinimumBitrate = 100_000L; + private const long MaximumBitrate = 100_000_000L; + private const double MinimumFrameRate = 1.0; + private const double MaximumFrameRate = 240.0; + + internal const double DefaultFrameRate = 30.0; + + internal const string ProbeShowEntries = + "stream=width,height,avg_frame_rate,r_frame_rate:stream_side_data=rotation:format=duration"; + + internal static void WriteProbe(Collection arguments, string inputPath) + { + arguments.Add("-hide_banner"); + arguments.Add("-loglevel"); + arguments.Add("error"); + arguments.Add("-select_streams"); + arguments.Add("v:0"); + arguments.Add("-show_entries"); + arguments.Add(ProbeShowEntries); + arguments.Add("-of"); + arguments.Add("default"); + arguments.Add("-i"); + arguments.Add(inputPath); + } + + internal static void WriteEncode(Collection arguments, in FFmpegEncodeRequest request) + { + arguments.Add("-hide_banner"); + arguments.Add("-loglevel"); + arguments.Add("error"); + arguments.Add("-y"); + arguments.Add("-f"); + arguments.Add("rawvideo"); + arguments.Add("-pix_fmt"); + arguments.Add(InputPixelFormat); + arguments.Add("-s"); + arguments.Add(BuildFrameSize(request.Width, request.Height)); + arguments.Add("-r"); + arguments.Add(BuildFrameRate(request.FrameRate)); + arguments.Add("-i"); + arguments.Add("-"); + arguments.Add("-an"); + arguments.Add("-sn"); + arguments.Add("-dn"); + arguments.Add("-c:v"); + arguments.Add(request.VideoEncoder); + arguments.Add("-b:v"); + arguments.Add(request.BitrateBitsPerSecond.ToString(CultureInfo.InvariantCulture)); + arguments.Add("-g"); + arguments.Add(request.GopSize.ToString(CultureInfo.InvariantCulture)); + arguments.Add("-pix_fmt"); + arguments.Add(OutputPixelFormat); + arguments.Add("-colorspace"); + arguments.Add(ColorSpace); + arguments.Add("-color_primaries"); + arguments.Add(ColorSpace); + arguments.Add("-color_trc"); + arguments.Add(ColorSpace); + arguments.Add("-color_range"); + arguments.Add("tv"); + arguments.Add("-f"); + arguments.Add("mp4"); + arguments.Add(request.OutputPath); + } + + internal static void WriteEncoderProbe(Collection arguments, string encoder, uint width, uint height) + { + arguments.Add("-hide_banner"); + arguments.Add("-nostdin"); + arguments.Add("-loglevel"); + arguments.Add("error"); + arguments.Add("-f"); + arguments.Add("lavfi"); + arguments.Add("-i"); + arguments.Add(BuildColorSource(width, height)); + arguments.Add("-frames:v"); + arguments.Add("1"); + arguments.Add("-pix_fmt"); + arguments.Add(OutputPixelFormat); + arguments.Add("-c:v"); + arguments.Add(encoder); + arguments.Add("-f"); + arguments.Add("null"); + arguments.Add("-"); + } + + internal static string BuildFrameSize(uint width, uint height) => + string.Create(CultureInfo.InvariantCulture, stackalloc char[32], $"{width}x{height}"); + + internal static string BuildFrameRate(FrameRate frameRate) => + string.Create(CultureInfo.InvariantCulture, stackalloc char[32], + $"{frameRate.Numerator}/{frameRate.Denominator}"); + + internal static string BuildColorSource(uint width, uint height) => + string.Create(CultureInfo.InvariantCulture, stackalloc char[64], + $"color=c=black:s={width}x{height}:r=30"); + + internal static long CalculateVideoBitrate(uint width, uint height, double frameRate, float bitrateFactor) + { + var rate = double.IsFinite(frameRate) && frameRate > 0 + ? Math.Clamp(frameRate, MinimumFrameRate, MaximumFrameRate) + : DefaultFrameRate; + + var factor = float.IsFinite(bitrateFactor) && bitrateFactor > 0 ? bitrateFactor : 1f; + var bitrate = (double)width * height * rate * BitratePerPixelPerSecond * factor; + + if (!double.IsFinite(bitrate)) + return MaximumBitrate; + + return (long)Math.Clamp(bitrate, MinimumBitrate, MaximumBitrate); + } +} diff --git a/ProxyForge/Transcoding/FFmpegEncoderSelector.cs b/ProxyForge/Transcoding/FFmpegEncoderSelector.cs new file mode 100644 index 0000000..6faac43 --- /dev/null +++ b/ProxyForge/Transcoding/FFmpegEncoderSelector.cs @@ -0,0 +1,159 @@ +using System.Collections.Concurrent; +using System.Diagnostics; +using Vortice.DXGI; + +namespace ProxyForge.Transcoding; + +internal static class FFmpegEncoderCandidates +{ + internal const int VendorNvidia = 0x10DE; + internal const int VendorAmd = 0x1002; + internal const int VendorIntel = 0x8086; + + private static readonly string[] Hardware = ["h264_nvenc", "h264_qsv", "h264_amf"]; + + internal static ReadOnlySpan Hardware264 => Hardware; + + internal static int VendorOf(string encoder) + { + if (encoder.Contains("nvenc", StringComparison.Ordinal)) + return VendorNvidia; + if (encoder.Contains("amf", StringComparison.Ordinal)) + return VendorAmd; + if (encoder.Contains("qsv", StringComparison.Ordinal)) + return VendorIntel; + return 0; + } + + internal static void Order( + ReadOnlySpan candidates, + IReadOnlySet discreteVendors, + Span destination) + { + ArgumentOutOfRangeException.ThrowIfLessThan(destination.Length, candidates.Length); + + var index = 0; + for (var i = 0; i < candidates.Length; i++) + { + if (discreteVendors.Contains(VendorOf(candidates[i]))) + destination[index++] = candidates[i]; + } + + for (var i = 0; i < candidates.Length; i++) + { + if (!discreteVendors.Contains(VendorOf(candidates[i]))) + destination[index++] = candidates[i]; + } + } +} + +internal static class FFmpegEncoderSelector +{ + private const int ProbeTimeoutMilliseconds = 15_000; + private const long DiscreteVideoMemoryThreshold = 512L * 1024L * 1024L; + + private static readonly ConcurrentDictionary ResolvedEncoders = new(); + + private static readonly Lazy> DiscreteGpuVendors = + new(DetectDiscreteGpuVendors, LazyThreadSafetyMode.ExecutionAndPublication); + + internal static async Task ResolveAsync( + string ffmpegPath, + bool hardwareAccelerationEnabled, + uint width, + uint height, + string workingDirectory, + CancellationToken cancellationToken) + { + if (!hardwareAccelerationEnabled) + return FFmpegArguments.SoftwareVideoEncoder; + + var key = ((long)width << 32) | height; + if (ResolvedEncoders.TryGetValue(key, out var cached)) + return cached; + + var candidates = FFmpegEncoderCandidates.Hardware264; + var ordered = new string[candidates.Length]; + FFmpegEncoderCandidates.Order(candidates, DiscreteGpuVendors.Value, ordered); + + foreach (var candidate in ordered) + { + cancellationToken.ThrowIfCancellationRequested(); + + if (!await ProbeEncoderAsync(ffmpegPath, candidate, width, height, workingDirectory, cancellationToken) + .ConfigureAwait(false)) + continue; + + ResolvedEncoders[key] = candidate; + return candidate; + } + + ResolvedEncoders[key] = FFmpegArguments.SoftwareVideoEncoder; + return FFmpegArguments.SoftwareVideoEncoder; + } + + private static async Task ProbeEncoderAsync( + string ffmpegPath, + string encoder, + uint width, + uint height, + string workingDirectory, + CancellationToken cancellationToken) + { + using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + timeout.CancelAfter(ProbeTimeoutMilliseconds); + + try + { + var result = await FFmpegProcessRunner.RunAsync( + ffmpegPath, + arguments => FFmpegArguments.WriteEncoderProbe(arguments, encoder, width, height), + workingDirectory, + null, + null, + ProcessPriorityClass.BelowNormal, + timeout.Token).ConfigureAwait(false); + + return result.IsSuccess; + } + catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested) + { + return false; + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + Debug.WriteLine(string.Concat("[FFmpegEncoderSelector] Probe of ", encoder, " failed: ", ex.Message)); + return false; + } + } + + private static IReadOnlySet DetectDiscreteGpuVendors() + { + var vendors = new HashSet(); + + try + { + using var factory = DXGI.CreateDXGIFactory1(); + + var index = 0; + while (factory.EnumAdapters1(index, out var adapter).Success) + { + using (adapter) + { + var description = adapter.Description1; + if ((description.Flags & AdapterFlags.Software) == 0 && + (long)description.DedicatedVideoMemory >= DiscreteVideoMemoryThreshold) + vendors.Add(description.VendorId); + } + + index++; + } + } + catch (Exception ex) + { + Debug.WriteLine(string.Concat("[FFmpegEncoderSelector] Adapter enumeration failed: ", ex.Message)); + } + + return vendors; + } +} diff --git a/ProxyForge/Transcoding/FFmpegProcessRunner.cs b/ProxyForge/Transcoding/FFmpegProcessRunner.cs new file mode 100644 index 0000000..c9d7a65 --- /dev/null +++ b/ProxyForge/Transcoding/FFmpegProcessRunner.cs @@ -0,0 +1,243 @@ +using System.Buffers; +using System.Collections.ObjectModel; +using System.ComponentModel; +using System.Diagnostics; +using System.IO; +using System.Text; + +namespace ProxyForge.Transcoding; + +internal delegate void FFmpegLineHandler(ReadOnlySpan line); + +internal delegate Task FFmpegInputWriter(Stream destination, CancellationToken cancellationToken); + +internal readonly record struct FFmpegProcessResult(int ExitCode, string Diagnostics) +{ + internal bool IsSuccess => ExitCode == 0; + + internal string FirstDiagnosticLine(int maximumLength) + { + var text = Diagnostics.AsSpan().Trim(); + if (text.IsEmpty) + return string.Empty; + + var index = text.IndexOf('\n'); + var line = index < 0 ? text : text[..index]; + return new string(line.Length > maximumLength ? line[..maximumLength] : line); + } +} + +internal sealed class FFmpegDiagnosticsBuffer(int capacity) +{ + private readonly StringBuilder _builder = new(); + + internal void Append(ReadOnlySpan line) + { + var trimmed = line.Trim(); + if (trimmed.IsEmpty || _builder.Length >= capacity) + return; + + if (_builder.Length != 0) + _builder.Append('\n'); + + var remaining = capacity - _builder.Length; + _builder.Append(trimmed.Length > remaining ? trimmed[..remaining] : trimmed); + } + + public override string ToString() => _builder.ToString(); +} + +internal static class FFmpegProcessRunner +{ + private const int LineBufferLength = 4096; + private const int DiagnosticsCapacity = 4096; + + private static readonly UTF8Encoding PipeEncoding = new(encoderShouldEmitUTF8Identifier: false); + + internal static async Task RunAsync( + string executablePath, + Action> argumentWriter, + string workingDirectory, + FFmpegLineHandler? standardOutputHandler, + FFmpegInputWriter? standardInputWriter, + ProcessPriorityClass priority, + CancellationToken cancellationToken) + { + cancellationToken.ThrowIfCancellationRequested(); + + var startInfo = new ProcessStartInfo(executablePath) + { + UseShellExecute = false, + CreateNoWindow = true, + RedirectStandardInput = standardInputWriter is not null, + RedirectStandardOutput = true, + RedirectStandardError = true, + StandardOutputEncoding = PipeEncoding, + StandardErrorEncoding = PipeEncoding, + WorkingDirectory = workingDirectory, + }; + argumentWriter(startInfo.ArgumentList); + + var diagnostics = new FFmpegDiagnosticsBuffer(DiagnosticsCapacity); + + using var process = new Process { StartInfo = startInfo }; + + try + { + process.Start(); + } + catch (Win32Exception ex) + { + throw new InvalidOperationException( + string.Concat("Failed to start the FFmpeg process: ", executablePath), ex); + } + + try + { + process.PriorityClass = priority; + } + catch (Exception ex) + { + Debug.WriteLine(string.Concat("[FFmpegProcessRunner] Priority assignment failed: ", ex.Message)); + } + + var standardOutputTask = PumpLinesAsync(process.StandardOutput, standardOutputHandler); + var standardErrorTask = PumpLinesAsync(process.StandardError, diagnostics.Append); + + var registration = cancellationToken.CanBeCanceled + ? cancellationToken.Register(static state => TryKill((Process)state!), process) + : default; + + Exception? inputFailure = null; + + try + { + if (standardInputWriter is not null) + { + try + { + await WriteStandardInputAsync(process, standardInputWriter, cancellationToken).ConfigureAwait(false); + } + catch (Exception ex) + { + inputFailure = ex; + } + } + + await process.WaitForExitAsync(CancellationToken.None).ConfigureAwait(false); + await standardOutputTask.ConfigureAwait(false); + await standardErrorTask.ConfigureAwait(false); + } + finally + { + await registration.DisposeAsync().ConfigureAwait(false); + } + + cancellationToken.ThrowIfCancellationRequested(); + + if (inputFailure is not null) + { + if (inputFailure is OperationCanceledException canceled) + throw canceled; + + throw new InvalidOperationException( + string.Concat("Failed to send frames to FFmpeg. ", diagnostics.ToString()), inputFailure); + } + + return new FFmpegProcessResult(process.ExitCode, diagnostics.ToString()); + } + + private static async Task WriteStandardInputAsync( + Process process, FFmpegInputWriter writer, CancellationToken cancellationToken) + { + var destination = process.StandardInput.BaseStream; + try + { + await writer(destination, cancellationToken).ConfigureAwait(false); + await destination.FlushAsync(CancellationToken.None).ConfigureAwait(false); + } + finally + { + try + { + destination.Close(); + } + catch (Exception ex) + { + Debug.WriteLine(string.Concat("[FFmpegProcessRunner] Closing stdin failed: ", ex.Message)); + } + } + } + + private static void TryKill(Process process) + { + try + { + if (!process.HasExited) + process.Kill(entireProcessTree: true); + } + catch (Exception ex) + { + Debug.WriteLine(string.Concat("[FFmpegProcessRunner] Kill failed: ", ex.Message)); + } + } + + private static async Task PumpLinesAsync(TextReader reader, FFmpegLineHandler? handler) + { + var buffer = ArrayPool.Shared.Rent(LineBufferLength); + try + { + if (handler is null) + { + while (await reader.ReadAsync(buffer).ConfigureAwait(false) > 0) + { + } + + return; + } + + var length = 0; + while (true) + { + var read = await reader.ReadAsync(buffer.AsMemory(length)).ConfigureAwait(false); + if (read == 0) + break; + + length += read; + var consumed = 0; + + while (true) + { + var pending = buffer.AsSpan(consumed, length - consumed); + var index = pending.IndexOf('\n'); + if (index < 0) + break; + + handler(TrimLineEnd(pending[..index])); + consumed += index + 1; + } + + if (consumed > 0) + { + buffer.AsSpan(consumed, length - consumed).CopyTo(buffer); + length -= consumed; + } + else if (length == buffer.Length) + { + handler(buffer.AsSpan(0, length)); + length = 0; + } + } + + if (length > 0) + handler(TrimLineEnd(buffer.AsSpan(0, length))); + } + finally + { + ArrayPool.Shared.Return(buffer); + } + } + + private static ReadOnlySpan TrimLineEnd(ReadOnlySpan line) => + line.Length > 0 && line[^1] == '\r' ? line[..^1] : line; +} diff --git a/ProxyForge/Transcoding/FFmpegRuntime.cs b/ProxyForge/Transcoding/FFmpegRuntime.cs new file mode 100644 index 0000000..d683135 --- /dev/null +++ b/ProxyForge/Transcoding/FFmpegRuntime.cs @@ -0,0 +1,63 @@ +using System.Diagnostics; +using System.IO; +using System.Runtime.CompilerServices; +using YukkuriMovieMaker.Plugin.FileSource.FFmpeg; + +namespace ProxyForge.Transcoding; + +internal readonly record struct FFmpegExecutables(string FFmpegPath) +{ + internal static FFmpegExecutables Unavailable => new(string.Empty); + + internal bool IsAvailable => FFmpegPath.Length != 0; +} + +internal static class FFmpegRuntime +{ + private const string FFmpegExecutableName = "ffmpeg.exe"; + + private static readonly Lazy Resolved = + new(Resolve, LazyThreadSafetyMode.ExecutionAndPublication); + + internal static FFmpegExecutables Executables => Resolved.Value; + + internal static FFmpegExecutables Require() + { + var executables = Resolved.Value; + if (!executables.IsAvailable) + throw new InvalidOperationException( + "The FFmpeg executable bundled with YukkuriMovieMaker could not be located."); + + return executables; + } + + private static FFmpegExecutables Resolve() + { + string directory; + try + { + directory = GetYmm4FFmpegDirectory(); + } + catch (Exception ex) + { + Debug.WriteLine(string.Concat("[FFmpegRuntime] FFmpeg directory lookup failed: ", ex.Message)); + return FFmpegExecutables.Unavailable; + } + + if (string.IsNullOrEmpty(directory)) + return FFmpegExecutables.Unavailable; + + var ffmpegPath = Path.Combine(directory, FFmpegExecutableName); + if (!File.Exists(ffmpegPath)) + { + Debug.WriteLine(string.Concat("[FFmpegRuntime] ffmpeg.exe missing in ", directory)); + return FFmpegExecutables.Unavailable; + } + + return new FFmpegExecutables(ffmpegPath); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static string GetYmm4FFmpegDirectory() => + FFmpegResourceLocator.GetFFmpegDirectory(); +} diff --git a/ProxyForge/Transcoding/FrameRate.cs b/ProxyForge/Transcoding/FrameRate.cs new file mode 100644 index 0000000..b323986 --- /dev/null +++ b/ProxyForge/Transcoding/FrameRate.cs @@ -0,0 +1,59 @@ +namespace ProxyForge.Transcoding; + +internal readonly record struct FrameRate(int Numerator, int Denominator) +{ + internal bool IsValid => Numerator > 0 && Denominator > 0; + + internal double Value => (double)Numerator / Denominator; + + internal static FrameRate FromFrameCountAndDuration(int frameCount, TimeSpan duration) + { + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(frameCount); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(duration.Ticks); + + var numerator = frameCount * (long)TimeSpan.TicksPerSecond; + var denominator = duration.Ticks; + + Reduce(ref numerator, ref denominator); + + while (numerator > int.MaxValue || denominator > int.MaxValue) + { + numerator = (numerator + 1) / 2; + denominator = (denominator + 1) / 2; + Reduce(ref numerator, ref denominator); + } + + return new FrameRate((int)numerator, (int)denominator); + } + + internal static TimeSpan GetSampleTime(int frameIndex, int frameCount, TimeSpan duration) + { + ArgumentOutOfRangeException.ThrowIfNegative(frameIndex); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(frameCount); + + var ticks = (2L * frameIndex + 1L) * duration.Ticks / (2L * frameCount); + return new TimeSpan(ticks); + } + + private static void Reduce(ref long numerator, ref long denominator) + { + var divisor = GreatestCommonDivisor(numerator, denominator); + if (divisor <= 1) + return; + + numerator /= divisor; + denominator /= divisor; + } + + private static long GreatestCommonDivisor(long left, long right) + { + while (right != 0) + { + var remainder = left % right; + left = right; + right = remainder; + } + + return left; + } +} diff --git a/ProxyForge/Transcoding/ProxyFrameRenderer.cs b/ProxyForge/Transcoding/ProxyFrameRenderer.cs new file mode 100644 index 0000000..2053d99 --- /dev/null +++ b/ProxyForge/Transcoding/ProxyFrameRenderer.cs @@ -0,0 +1,114 @@ +using System.Numerics; +using Vortice.DCommon; +using Vortice.Direct2D1; +using Vortice.Direct2D1.Effects; +using Vortice.DXGI; +using Vortice.Mathematics; +using YukkuriMovieMaker.Commons; + +namespace ProxyForge.Transcoding; + +internal sealed class ProxyFrameRenderer : IDisposable +{ + internal const float ReferenceDpi = 96f; + + private const int MaximumDimension = 16384; + + private readonly ID2D1DeviceContext6 _context; + private readonly ID2D1Bitmap1 _target; + private readonly ID2D1Bitmap1 _readback; + private readonly AffineTransform2D _transform; + private readonly ID2D1Image _transformOutput; + private readonly int _width; + private readonly int _height; + private readonly int _stride; + private int _disposed; + + internal int FrameByteCount => _stride * _height; + + internal ProxyFrameRenderer( + IGraphicsDevicesAndContext devices, + ID2D1Image source, + ProxyGeometry geometry, + uint displayWidth, + uint displayHeight) + { + _context = devices.DeviceContext; + _width = (int)geometry.Width; + _height = (int)geometry.Height; + _stride = _width * 4; + + var pixelFormat = new PixelFormat(Format.B8G8R8A8_UNorm, Vortice.DCommon.AlphaMode.Premultiplied); + var size = new SizeI(_width, _height); + + _target = _context.CreateBitmap(size, nint.Zero, _stride, + new BitmapProperties1(pixelFormat, ReferenceDpi, ReferenceDpi, BitmapOptions.Target)); + _readback = _context.CreateBitmap(size, nint.Zero, _stride, + new BitmapProperties1(pixelFormat, ReferenceDpi, ReferenceDpi, + BitmapOptions.CpuRead | BitmapOptions.CannotDraw)); + + _transform = new AffineTransform2D(_context); + _transform.SetInput(0, source, true); + _transform.InterPolationMode = AffineTransform2DInterpolationMode.HighQualityCubic; + _transform.TransformMatrix = + Matrix3x2.CreateScale(_width / (float)displayWidth, _height / (float)displayHeight) * + Matrix3x2.CreateTranslation(_width / 2f, _height / 2f); + _transformOutput = _transform.Output; + } + + internal static (uint Width, uint Height) MeasureDisplaySize(IGraphicsDevicesAndContext devices, ID2D1Image image) + { + var bounds = devices.DeviceContext.GetImageLocalBounds(image); + var width = (int)Math.Round(bounds.Right - bounds.Left, MidpointRounding.AwayFromZero); + var height = (int)Math.Round(bounds.Bottom - bounds.Top, MidpointRounding.AwayFromZero); + + if (width <= 0 || height <= 0 || width > MaximumDimension || height > MaximumDimension) + throw new InvalidOperationException("The video source reported an unusable image size."); + + return ((uint)width, (uint)height); + } + + internal void Render(Span destination) + { + ObjectDisposedException.ThrowIf(Volatile.Read(ref _disposed) != 0, this); + + _context.Target = _target; + _context.BeginDraw(); + _context.Clear(new Color4(0f, 0f, 0f, 1f)); + _context.DrawImage(_transformOutput, InterpolationMode.Linear, CompositeMode.SourceOver); + _context.EndDraw(); + _context.Target = null; + + _readback.CopyFromBitmap(_target); + + var mapped = _readback.Map(MapOptions.Read); + try + { + unsafe + { + var scanline = (byte*)mapped.Bits; + for (var y = 0; y < _height; y++) + { + new ReadOnlySpan(scanline + (long)y * mapped.Pitch, _stride) + .CopyTo(destination.Slice(y * _stride, _stride)); + } + } + } + finally + { + _readback.Unmap(); + } + } + + public void Dispose() + { + if (Interlocked.Exchange(ref _disposed, 1) != 0) + return; + + _transformOutput.Dispose(); + _transform.SetInput(0, null, true); + _transform.Dispose(); + _readback.Dispose(); + _target.Dispose(); + } +} diff --git a/ProxyForge/Transcoding/ProxyGeometry.cs b/ProxyForge/Transcoding/ProxyGeometry.cs new file mode 100644 index 0000000..7a88514 --- /dev/null +++ b/ProxyForge/Transcoding/ProxyGeometry.cs @@ -0,0 +1,48 @@ +namespace ProxyForge.Transcoding; + +internal readonly record struct ProxyGeometry(uint Width, uint Height, float EffectiveScale); + +internal static class ProxyGeometryCalculator +{ + internal const uint MinimumDimension = 2; + + internal static bool IsQuarterTurn(int rotationDegrees) + { + var normalized = rotationDegrees % 360; + if (normalized < 0) + normalized += 360; + return normalized is 90 or 270; + } + + internal static (uint Width, uint Height) GetDisplaySize(uint codedWidth, uint codedHeight, int rotationDegrees) => + IsQuarterTurn(rotationDegrees) + ? (codedHeight, codedWidth) + : (codedWidth, codedHeight); + + internal static uint AlignEven(uint value) + { + var aligned = value & ~1u; + return aligned < MinimumDimension ? MinimumDimension : aligned; + } + + internal static ProxyGeometry Calculate(uint displayWidth, uint displayHeight, float scale) + { + ArgumentOutOfRangeException.ThrowIfZero(displayWidth); + ArgumentOutOfRangeException.ThrowIfZero(displayHeight); + + var clamped = float.IsNaN(scale) ? 1f : Math.Clamp(scale, 0f, 1f); + var width = ClampDimension(ScaleDimension(displayWidth, clamped), displayWidth); + var height = ClampDimension(ScaleDimension(displayHeight, clamped), displayHeight); + + return new ProxyGeometry(width, height, (float)width / displayWidth); + } + + private static uint ScaleDimension(uint dimension, float scale) => + AlignEven((uint)Math.Round(dimension * (double)scale, MidpointRounding.AwayFromZero)); + + private static uint ClampDimension(uint value, uint maximum) + { + var limit = AlignEven(maximum); + return value > limit ? limit : value; + } +} diff --git a/ProxyForge/ViewModels/SettingsViewModel.cs b/ProxyForge/ViewModels/SettingsViewModel.cs index 0899e84..2840f65 100644 --- a/ProxyForge/ViewModels/SettingsViewModel.cs +++ b/ProxyForge/ViewModels/SettingsViewModel.cs @@ -2,7 +2,6 @@ using ProxyForge.Core; using ProxyForge.Interfaces; using ProxyForge.Localization; -using ProxyForge.Memory; using ProxyForge.Utilities; using System.Collections.ObjectModel; using System.Windows.Input; @@ -13,7 +12,6 @@ namespace ProxyForge.ViewModels; internal sealed class SettingsViewModel : Bindable { private readonly ProxyCacheManager? _cacheManager; - private readonly MemoryBudget? _budget; private readonly VideoCacheDatabase? _videoCache; private readonly IDialogService _dialogService; @@ -24,11 +22,11 @@ internal sealed class SettingsViewModel : Bindable set => Set(ref _cacheSummaryText, value); } - private string _memoryUsageText = ""; - public string MemoryUsageText + private string _cacheUsageText = ""; + public string CacheUsageText { - get => _memoryUsageText; - set => Set(ref _memoryUsageText, value); + get => _cacheUsageText; + set => Set(ref _cacheUsageText, value); } private bool _hasCacheEntries; @@ -62,10 +60,9 @@ internal sealed class SettingsViewModel : Bindable public ICommand ClearVideoCacheCommand { get; } public ICommand RemoveVideoCacheEntryCommand { get; } - internal SettingsViewModel(ProxyCacheManager? cacheManager, MemoryBudget? budget, VideoCacheDatabase? videoCache, IDialogService dialogService) + internal SettingsViewModel(ProxyCacheManager? cacheManager, VideoCacheDatabase? videoCache, IDialogService dialogService) { _cacheManager = cacheManager; - _budget = budget; _videoCache = videoCache; _dialogService = dialogService; ClearCacheCommand = new ActionCommand(ExecuteClearCache); @@ -101,27 +98,17 @@ internal sealed class SettingsViewModel : Bindable if (_cacheManager is null) { CacheSummaryText = Translate.CacheSummaryPluginNotInitialized; - MemoryUsageText = ""; + CacheUsageText = ""; HasCacheEntries = false; return; } - var (count, memSize, diskSize, memCount, diskCount) = _cacheManager.GetCacheInfo(); + var (count, totalSize) = _cacheManager.GetCacheInfo(); CacheSummaryText = string.Format(Translate.CacheSummaryCountFormat, count.ToString("N0")); - - var usageText = string.Format( - Translate.CacheUsageMemoryAndDiskFormat, - memCount.ToString("N0"), - ByteFormatter.Format(memSize), - diskCount.ToString("N0"), - ByteFormatter.Format(diskSize)); - - if (_budget is not null) - usageText = string.Concat( - usageText, - string.Format(Translate.CacheUsageAllocatedFormat, ByteFormatter.Format(_budget.AllocatedBytes))); - - MemoryUsageText = usageText; + CacheUsageText = string.Format( + Translate.CacheUsageDiskFormat, + count.ToString("N0"), + ByteFormatter.Format(totalSize)); CacheEntries.Clear(); var snapshots = _cacheManager.GetAllSnapshots(); @@ -201,8 +188,7 @@ internal sealed class CacheEntryViewModel(CacheEntrySnapshot snapshot) : Bindabl public string OriginalPath { get; } = snapshot.OriginalPath; public float Scale { get; } = snapshot.Scale; public string Resolution { get; } = string.Create(null, stackalloc char[24], $"{snapshot.ProxyWidth}\u00d7{snapshot.ProxyHeight}"); - public bool IsInMemory { get; } = snapshot.IsInMemory; - public string StorageType { get; } = snapshot.IsInMemory ? Translate.StorageMemory : Translate.StorageDisk; + public string StorageType { get; } = Translate.StorageDisk; public long DataSize { get; } = snapshot.DataSize; public string DataSizeText { get; } = ByteFormatter.Format(snapshot.DataSize); public string CreatedAtText { get; } = snapshot.CreatedAt.ToLocalTime().ToString("HH:mm:ss"); diff --git a/ProxyForge/Views/GenerationPopupView.xaml b/ProxyForge/Views/GenerationPopupView.xaml index e83337b..bd41be3 100644 --- a/ProxyForge/Views/GenerationPopupView.xaml +++ b/ProxyForge/Views/GenerationPopupView.xaml @@ -45,9 +45,6 @@ - diff --git a/ProxyForge/Views/ProxyForgeSettingsView.xaml b/ProxyForge/Views/ProxyForgeSettingsView.xaml index ec784dc..c4bfa08 100644 --- a/ProxyForge/Views/ProxyForgeSettingsView.xaml +++ b/ProxyForge/Views/ProxyForgeSettingsView.xaml @@ -179,41 +179,6 @@ - - - - - - - - - - - - - - - - - - - - - - - - - @@ -262,7 +227,7 @@ - diff --git a/ProxyForge/Views/ProxyForgeSettingsView.xaml.cs b/ProxyForge/Views/ProxyForgeSettingsView.xaml.cs index 9e1fe72..5396994 100644 --- a/ProxyForge/Views/ProxyForgeSettingsView.xaml.cs +++ b/ProxyForge/Views/ProxyForgeSettingsView.xaml.cs @@ -12,7 +12,7 @@ public partial class ProxyForgeSettingsView : UserControl { InitializeComponent(); var host = PluginHost.Instance; - DataContext = new SettingsViewModel(host?.CacheManager, host?.Budget, host?.VideoCache, new WpfDialogService()); + DataContext = new SettingsViewModel(host?.CacheManager, host?.VideoCache, new WpfDialogService()); VersionText.Text = string.Concat("v", Assembly.GetExecutingAssembly().GetName().Version?.ToString(3) ?? "0.0.0"); } } \ No newline at end of file