diff --git a/.gitattributes b/.gitattributes deleted file mode 100644 index 1ff0c42..0000000 --- a/.gitattributes +++ /dev/null @@ -1,63 +0,0 @@ -############################################################################### -# Set default behavior to automatically normalize line endings. -############################################################################### -* text=auto - -############################################################################### -# Set default behavior for command prompt diff. -# -# This is need for earlier builds of msysgit that does not have it on by -# default for csharp files. -# Note: This is only used by command line -############################################################################### -#*.cs diff=csharp - -############################################################################### -# Set the merge driver for project and solution files -# -# Merging from the command prompt will add diff markers to the files if there -# are conflicts (Merging from VS is not affected by the settings below, in VS -# the diff markers are never inserted). Diff markers may cause the following -# file extensions to fail to load in VS. An alternative would be to treat -# these files as binary and thus will always conflict and require user -# intervention with every merge. To do so, just uncomment the entries below -############################################################################### -#*.sln merge=binary -#*.csproj merge=binary -#*.vbproj merge=binary -#*.vcxproj merge=binary -#*.vcproj merge=binary -#*.dbproj merge=binary -#*.fsproj merge=binary -#*.lsproj merge=binary -#*.wixproj merge=binary -#*.modelproj merge=binary -#*.sqlproj merge=binary -#*.wwaproj merge=binary - -############################################################################### -# behavior for image files -# -# image files are treated as binary by default. -############################################################################### -#*.jpg binary -#*.png binary -#*.gif binary - -############################################################################### -# diff behavior for common document formats -# -# Convert binary document formats to text before diffing them. This feature -# is only available from the command line. Turn it on by uncommenting the -# entries below. -############################################################################### -#*.doc diff=astextplain -#*.DOC diff=astextplain -#*.docx diff=astextplain -#*.DOCX diff=astextplain -#*.dot diff=astextplain -#*.DOT diff=astextplain -#*.pdf diff=astextplain -#*.PDF diff=astextplain -#*.rtf diff=astextplain -#*.RTF diff=astextplain diff --git a/.gitignore b/.gitignore deleted file mode 100644 index 9491a2f..0000000 --- a/.gitignore +++ /dev/null @@ -1,363 +0,0 @@ -## Ignore Visual Studio temporary files, build results, and -## files generated by popular Visual Studio add-ons. -## -## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore - -# User-specific files -*.rsuser -*.suo -*.user -*.userosscache -*.sln.docstates - -# User-specific files (MonoDevelop/Xamarin Studio) -*.userprefs - -# Mono auto generated files -mono_crash.* - -# Build results -[Dd]ebug/ -[Dd]ebugPublic/ -[Rr]elease/ -[Rr]eleases/ -x64/ -x86/ -[Ww][Ii][Nn]32/ -[Aa][Rr][Mm]/ -[Aa][Rr][Mm]64/ -bld/ -[Bb]in/ -[Oo]bj/ -[Oo]ut/ -[Ll]og/ -[Ll]ogs/ - -# Visual Studio 2015/2017 cache/options directory -.vs/ -# Uncomment if you have tasks that create the project's static files in wwwroot -#wwwroot/ - -# Visual Studio 2017 auto generated files -Generated\ Files/ - -# MSTest test Results -[Tt]est[Rr]esult*/ -[Bb]uild[Ll]og.* - -# NUnit -*.VisualState.xml -TestResult.xml -nunit-*.xml - -# Build Results of an ATL Project -[Dd]ebugPS/ -[Rr]eleasePS/ -dlldata.c - -# Benchmark Results -BenchmarkDotNet.Artifacts/ - -# .NET Core -project.lock.json -project.fragment.lock.json -artifacts/ - -# ASP.NET Scaffolding -ScaffoldingReadMe.txt - -# StyleCop -StyleCopReport.xml - -# Files built by Visual Studio -*_i.c -*_p.c -*_h.h -*.ilk -*.meta -*.obj -*.iobj -*.pch -*.pdb -*.ipdb -*.pgc -*.pgd -*.rsp -*.sbr -*.tlb -*.tli -*.tlh -*.tmp -*.tmp_proj -*_wpftmp.csproj -*.log -*.vspscc -*.vssscc -.builds -*.pidb -*.svclog -*.scc - -# Chutzpah Test files -_Chutzpah* - -# Visual C++ cache files -ipch/ -*.aps -*.ncb -*.opendb -*.opensdf -*.sdf -*.cachefile -*.VC.db -*.VC.VC.opendb - -# Visual Studio profiler -*.psess -*.vsp -*.vspx -*.sap - -# Visual Studio Trace Files -*.e2e - -# TFS 2012 Local Workspace -$tf/ - -# Guidance Automation Toolkit -*.gpState - -# ReSharper is a .NET coding add-in -_ReSharper*/ -*.[Rr]e[Ss]harper -*.DotSettings.user - -# TeamCity is a build add-in -_TeamCity* - -# DotCover is a Code Coverage Tool -*.dotCover - -# AxoCover is a Code Coverage Tool -.axoCover/* -!.axoCover/settings.json - -# Coverlet is a free, cross platform Code Coverage Tool -coverage*.json -coverage*.xml -coverage*.info - -# Visual Studio code coverage results -*.coverage -*.coveragexml - -# NCrunch -_NCrunch_* -.*crunch*.local.xml -nCrunchTemp_* - -# MightyMoose -*.mm.* -AutoTest.Net/ - -# Web workbench (sass) -.sass-cache/ - -# Installshield output folder -[Ee]xpress/ - -# DocProject is a documentation generator add-in -DocProject/buildhelp/ -DocProject/Help/*.HxT -DocProject/Help/*.HxC -DocProject/Help/*.hhc -DocProject/Help/*.hhk -DocProject/Help/*.hhp -DocProject/Help/Html2 -DocProject/Help/html - -# Click-Once directory -publish/ - -# Publish Web Output -*.[Pp]ublish.xml -*.azurePubxml -# Note: Comment the next line if you want to checkin your web deploy settings, -# but database connection strings (with potential passwords) will be unencrypted -*.pubxml -*.publishproj - -# Microsoft Azure Web App publish settings. Comment the next line if you want to -# checkin your Azure Web App publish settings, but sensitive information contained -# in these scripts will be unencrypted -PublishScripts/ - -# NuGet Packages -*.nupkg -# NuGet Symbol Packages -*.snupkg -# The packages folder can be ignored because of Package Restore -**/[Pp]ackages/* -# except build/, which is used as an MSBuild target. -!**/[Pp]ackages/build/ -# Uncomment if necessary however generally it will be regenerated when needed -#!**/[Pp]ackages/repositories.config -# NuGet v3's project.json files produces more ignorable files -*.nuget.props -*.nuget.targets - -# Microsoft Azure Build Output -csx/ -*.build.csdef - -# Microsoft Azure Emulator -ecf/ -rcf/ - -# Windows Store app package directories and files -AppPackages/ -BundleArtifacts/ -Package.StoreAssociation.xml -_pkginfo.txt -*.appx -*.appxbundle -*.appxupload - -# Visual Studio cache files -# files ending in .cache can be ignored -*.[Cc]ache -# but keep track of directories ending in .cache -!?*.[Cc]ache/ - -# Others -ClientBin/ -~$* -*~ -*.dbmdl -*.dbproj.schemaview -*.jfm -*.pfx -*.publishsettings -orleans.codegen.cs - -# Including strong name files can present a security risk -# (https://github.com/github/gitignore/pull/2483#issue-259490424) -#*.snk - -# Since there are multiple workflows, uncomment next line to ignore bower_components -# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) -#bower_components/ - -# RIA/Silverlight projects -Generated_Code/ - -# Backup & report files from converting an old project file -# to a newer Visual Studio version. Backup files are not needed, -# because we have git ;-) -_UpgradeReport_Files/ -Backup*/ -UpgradeLog*.XML -UpgradeLog*.htm -ServiceFabricBackup/ -*.rptproj.bak - -# SQL Server files -*.mdf -*.ldf -*.ndf - -# Business Intelligence projects -*.rdl.data -*.bim.layout -*.bim_*.settings -*.rptproj.rsuser -*- [Bb]ackup.rdl -*- [Bb]ackup ([0-9]).rdl -*- [Bb]ackup ([0-9][0-9]).rdl - -# Microsoft Fakes -FakesAssemblies/ - -# GhostDoc plugin setting file -*.GhostDoc.xml - -# Node.js Tools for Visual Studio -.ntvs_analysis.dat -node_modules/ - -# Visual Studio 6 build log -*.plg - -# Visual Studio 6 workspace options file -*.opt - -# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) -*.vbw - -# Visual Studio LightSwitch build output -**/*.HTMLClient/GeneratedArtifacts -**/*.DesktopClient/GeneratedArtifacts -**/*.DesktopClient/ModelManifest.xml -**/*.Server/GeneratedArtifacts -**/*.Server/ModelManifest.xml -_Pvt_Extensions - -# Paket dependency manager -.paket/paket.exe -paket-files/ - -# FAKE - F# Make -.fake/ - -# CodeRush personal settings -.cr/personal - -# Python Tools for Visual Studio (PTVS) -__pycache__/ -*.pyc - -# Cake - Uncomment if you are using it -# tools/** -# !tools/packages.config - -# Tabs Studio -*.tss - -# Telerik's JustMock configuration file -*.jmconfig - -# BizTalk build output -*.btp.cs -*.btm.cs -*.odx.cs -*.xsd.cs - -# OpenCover UI analysis results -OpenCover/ - -# Azure Stream Analytics local run output -ASALocalRun/ - -# MSBuild Binary and Structured Log -*.binlog - -# NVidia Nsight GPU debugger configuration file -*.nvuser - -# MFractors (Xamarin productivity tool) working folder -.mfractor/ - -# Local History for Visual Studio -.localhistory/ - -# BeatPulse healthcheck temp database -healthchecksdb - -# Backup folder for Package Reference Convert tool in Visual Studio 2017 -MigrationBackup/ - -# Ionide (cross platform F# VS Code tools) working folder -.ionide/ - -# Fody - auto-generated XML schema -FodyWeavers.xsd \ No newline at end of file diff --git a/.gitmodules b/.gitmodules deleted file mode 100644 index 44c3757..0000000 --- a/.gitmodules +++ /dev/null @@ -1,3 +0,0 @@ -[submodule "YukkuriMovieMaker.Generator"] - path = YukkuriMovieMaker.Generator - url = https://github.com/manju-summoner/YukkuriMovieMaker.Generator.git diff --git a/LICENSE b/LICENSE deleted file mode 100644 index 7e17c10..0000000 --- a/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2026 routersys - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. \ No newline at end of file diff --git a/ProxyForge.Tests/FFmpegArgumentsTests.cs b/ProxyForge.Tests/FFmpegArgumentsTests.cs deleted file mode 100644 index 5bd284c..0000000 --- a/ProxyForge.Tests/FFmpegArgumentsTests.cs +++ /dev/null @@ -1,152 +0,0 @@ -using ProxyForge.Transcoding; -using System.Collections.ObjectModel; -using Xunit; - -namespace ProxyForge.Tests; - -public sealed class FFmpegArgumentsTests -{ - [Fact] - public void WriteEncode_EmitsDeterministicRawVideoPipeline() - { - var request = new FFmpegEncodeRequest( - @"C:\cache\tmp\zdp_proxy.mp4", - 960, - 540, - new FrameRate(30000, 1001), - 544_320, - 30, - "h264_qsv"); - - var arguments = new Collection(); - FFmpegArguments.WriteEncode(arguments, in request); - - string[] expected = - [ - "-hide_banner", - "-loglevel", "error", - "-y", - "-f", "rawvideo", - "-pix_fmt", "bgra", - "-s", "960x540", - "-r", "30000/1001", - "-i", "-", - "-an", "-sn", "-dn", - "-c:v", "h264_qsv", - "-b:v", "544320", - "-g", "30", - "-pix_fmt", "yuv420p", - "-colorspace", "bt709", - "-color_primaries", "bt709", - "-color_trc", "bt709", - "-color_range", "tv", - "-f", "mp4", - @"C:\cache\tmp\zdp_proxy.mp4", - ]; - - Assert.Equal(expected, arguments); - } - - [Fact] - public void WriteEncode_DoesNotDisableStandardInput() - { - var request = new FFmpegEncodeRequest( - @"C:\cache\tmp\zdp_proxy.mp4", 320, 240, new FrameRate(30, 1), 100_000, 1, "h264"); - - var arguments = new Collection(); - FFmpegArguments.WriteEncode(arguments, in request); - - Assert.DoesNotContain("-nostdin", arguments); - } - - [Fact] - public void WriteEncode_PassesOutputPathWithoutQuoting() - { - var request = new FFmpegEncodeRequest( - @"C:\cache tmp\a b'c,d.mp4", 320, 240, new FrameRate(30, 1), 100_000, 1, "h264"); - - var arguments = new Collection(); - FFmpegArguments.WriteEncode(arguments, in request); - - Assert.Contains(@"C:\cache tmp\a b'c,d.mp4", arguments); - Assert.DoesNotContain(arguments, argument => argument.Contains('"')); - } - - [Fact] - public void WriteEncoderProbe_MatchesSingleFrameNullMuxProbe() - { - var arguments = new Collection(); - FFmpegArguments.WriteEncoderProbe(arguments, "h264_nvenc", 960, 540); - - string[] expected = - [ - "-hide_banner", - "-nostdin", - "-loglevel", "error", - "-f", "lavfi", - "-i", "color=c=black:s=960x540:r=30", - "-frames:v", "1", - "-pix_fmt", "yuv420p", - "-c:v", "h264_nvenc", - "-f", "null", - "-", - ]; - - Assert.Equal(expected, arguments); - } - - [Theory] - [InlineData(960u, 540u, "960x540")] - [InlineData(2u, 2u, "2x2")] - [InlineData(3840u, 2160u, "3840x2160")] - public void BuildFrameSize_UsesInvariantNumbers(uint width, uint height, string expected) => - Assert.Equal(expected, FFmpegArguments.BuildFrameSize(width, height)); - - [Theory] - [InlineData(30, 1, "30/1")] - [InlineData(30000, 1001, "30000/1001")] - [InlineData(24, 1, "24/1")] - public void BuildFrameRate_EmitsRationalForm(int numerator, int denominator, string expected) => - Assert.Equal(expected, FFmpegArguments.BuildFrameRate(new FrameRate(numerator, denominator))); - - [Fact] - public void BuildColorSource_MatchesLavfiSyntax() => - Assert.Equal("color=c=black:s=1280x720:r=30", FFmpegArguments.BuildColorSource(1280, 720)); - - [Fact] - public void CalculateVideoBitrate_UsesPixelRateFormula() => - Assert.Equal(544_320L, FFmpegArguments.CalculateVideoBitrate(960, 540, 30.0, 0.5f)); - - [Fact] - public void CalculateVideoBitrate_ClampsToMinimum() => - Assert.Equal(100_000L, FFmpegArguments.CalculateVideoBitrate(2, 2, 1.0, 0.01f)); - - [Fact] - public void CalculateVideoBitrate_ClampsToMaximum() => - Assert.Equal(100_000_000L, FFmpegArguments.CalculateVideoBitrate(7680, 4320, 240.0, 2f)); - - [Theory] - [InlineData(0.0)] - [InlineData(-1.0)] - [InlineData(double.NaN)] - [InlineData(double.PositiveInfinity)] - public void CalculateVideoBitrate_UnknownFrameRateUsesDefault(double frameRate) => - Assert.Equal( - FFmpegArguments.CalculateVideoBitrate(960, 540, FFmpegArguments.DefaultFrameRate, 0.5f), - FFmpegArguments.CalculateVideoBitrate(960, 540, frameRate, 0.5f)); - - [Fact] - public void CalculateVideoBitrate_ClampsExcessiveFrameRate() => - Assert.Equal( - FFmpegArguments.CalculateVideoBitrate(960, 540, 240.0, 0.5f), - FFmpegArguments.CalculateVideoBitrate(960, 540, 100_000.0, 0.5f)); - - [Theory] - [InlineData(0f)] - [InlineData(-1f)] - [InlineData(float.NaN)] - public void CalculateVideoBitrate_InvalidFactorFallsBackToUnity(float factor) => - Assert.Equal( - FFmpegArguments.CalculateVideoBitrate(960, 540, 30.0, 1f), - FFmpegArguments.CalculateVideoBitrate(960, 540, 30.0, factor)); -} diff --git a/ProxyForge.Tests/FFmpegDiagnosticsTests.cs b/ProxyForge.Tests/FFmpegDiagnosticsTests.cs deleted file mode 100644 index e580c85..0000000 --- a/ProxyForge.Tests/FFmpegDiagnosticsTests.cs +++ /dev/null @@ -1,89 +0,0 @@ -using ProxyForge.Transcoding; -using Xunit; - -namespace ProxyForge.Tests; - -public sealed class FFmpegDiagnosticsTests -{ - [Fact] - public void Append_JoinsLinesWithNewline() - { - var buffer = new FFmpegDiagnosticsBuffer(4096); - buffer.Append("first"); - buffer.Append("second"); - - Assert.Equal("first\nsecond", buffer.ToString()); - } - - [Fact] - public void Append_SkipsBlankLines() - { - var buffer = new FFmpegDiagnosticsBuffer(4096); - buffer.Append(""); - buffer.Append(" "); - buffer.Append("real"); - buffer.Append("\t"); - - Assert.Equal("real", buffer.ToString()); - } - - [Fact] - public void Append_TrimsSurroundingWhitespace() - { - var buffer = new FFmpegDiagnosticsBuffer(4096); - buffer.Append(" padded "); - - Assert.Equal("padded", buffer.ToString()); - } - - [Fact] - public void Append_NeverExceedsCapacity() - { - var buffer = new FFmpegDiagnosticsBuffer(16); - for (var i = 0; i < 1000; i++) - buffer.Append("0123456789"); - - Assert.True(buffer.ToString().Length <= 16); - } - - [Fact] - public void Append_KeepsEarliestDiagnosticsWhenTruncating() - { - var buffer = new FFmpegDiagnosticsBuffer(16); - buffer.Append("root cause here"); - buffer.Append("cascading noise"); - - Assert.StartsWith("root cause here", buffer.ToString()); - } - - [Fact] - public void FirstDiagnosticLine_ReturnsLeadingLine() - { - var result = new FFmpegProcessResult(1, "Unknown encoder 'h264_nvenc'\nError selecting an encoder"); - - Assert.Equal("Unknown encoder 'h264_nvenc'", result.FirstDiagnosticLine(200)); - } - - [Fact] - public void FirstDiagnosticLine_TruncatesToRequestedLength() - { - var result = new FFmpegProcessResult(1, new string('x', 500)); - - Assert.Equal(200, result.FirstDiagnosticLine(200).Length); - } - - [Fact] - public void FirstDiagnosticLine_EmptyDiagnosticsReturnsEmptyString() - { - var result = new FFmpegProcessResult(1, " \n "); - - Assert.Equal(string.Empty, result.FirstDiagnosticLine(200)); - } - - [Theory] - [InlineData(0, true)] - [InlineData(1, false)] - [InlineData(-1, false)] - public void IsSuccess_OnlyZeroExitCodeSucceeds(int exitCode, bool expected) => - Assert.Equal(expected, new FFmpegProcessResult(exitCode, string.Empty).IsSuccess); -} diff --git a/ProxyForge.Tests/FFmpegEncoderCandidatesTests.cs b/ProxyForge.Tests/FFmpegEncoderCandidatesTests.cs deleted file mode 100644 index f3bc884..0000000 --- a/ProxyForge.Tests/FFmpegEncoderCandidatesTests.cs +++ /dev/null @@ -1,91 +0,0 @@ -using ProxyForge.Transcoding; -using Xunit; - -namespace ProxyForge.Tests; - -public sealed class FFmpegEncoderCandidatesTests -{ - [Theory] - [InlineData("h264_nvenc", FFmpegEncoderCandidates.VendorNvidia)] - [InlineData("av1_nvenc", FFmpegEncoderCandidates.VendorNvidia)] - [InlineData("h264_amf", FFmpegEncoderCandidates.VendorAmd)] - [InlineData("h264_qsv", FFmpegEncoderCandidates.VendorIntel)] - [InlineData("h264", 0)] - [InlineData("libopenh264", 0)] - public void VendorOf_MapsEncoderSuffixToVendorId(string encoder, int expected) => - Assert.Equal(expected, FFmpegEncoderCandidates.VendorOf(encoder)); - - [Fact] - public void Hardware264_ListsNvencQsvAmfInThatOrder() - { - string[] expected = ["h264_nvenc", "h264_qsv", "h264_amf"]; - - Assert.Equal(expected, Candidates()); - } - - [Fact] - public void Order_WithoutDiscreteGpu_PreservesDeclaredOrder() - { - string[] expected = ["h264_nvenc", "h264_qsv", "h264_amf"]; - - Assert.Equal(expected, Order([])); - } - - [Fact] - public void Order_WithDiscreteAmd_PromotesAmfAboveIntegratedIntel() - { - string[] expected = ["h264_amf", "h264_nvenc", "h264_qsv"]; - - Assert.Equal(expected, Order([FFmpegEncoderCandidates.VendorAmd])); - } - - [Fact] - public void Order_WithDiscreteNvidia_KeepsNvencFirst() - { - string[] expected = ["h264_nvenc", "h264_qsv", "h264_amf"]; - - Assert.Equal(expected, Order([FFmpegEncoderCandidates.VendorNvidia])); - } - - [Fact] - public void Order_WithDiscreteIntel_PromotesQsv() - { - string[] expected = ["h264_qsv", "h264_nvenc", "h264_amf"]; - - Assert.Equal(expected, Order([FFmpegEncoderCandidates.VendorIntel])); - } - - [Fact] - public void Order_WithSeveralDiscreteVendors_KeepsRelativeOrderStable() - { - string[] expected = ["h264_nvenc", "h264_amf", "h264_qsv"]; - - Assert.Equal(expected, Order([FFmpegEncoderCandidates.VendorAmd, FFmpegEncoderCandidates.VendorNvidia])); - } - - [Fact] - public void Order_IsAPermutationOfTheInput() - { - var ordered = Order([FFmpegEncoderCandidates.VendorAmd]); - - Assert.Equal(Candidates().Order(), ordered.Order()); - } - - [Fact] - public void Order_DestinationTooSmall_Throws() - { - var destination = new string[FFmpegEncoderCandidates.Hardware264.Length - 1]; - - Assert.Throws(() => - FFmpegEncoderCandidates.Order(FFmpegEncoderCandidates.Hardware264, new HashSet(), destination)); - } - - private static string[] Candidates() => FFmpegEncoderCandidates.Hardware264.ToArray(); - - private static string[] Order(int[] discreteVendors) - { - var destination = new string[FFmpegEncoderCandidates.Hardware264.Length]; - FFmpegEncoderCandidates.Order(FFmpegEncoderCandidates.Hardware264, new HashSet(discreteVendors), destination); - return destination; - } -} diff --git a/ProxyForge.Tests/FFmpegExecutablesTests.cs b/ProxyForge.Tests/FFmpegExecutablesTests.cs deleted file mode 100644 index ea81692..0000000 --- a/ProxyForge.Tests/FFmpegExecutablesTests.cs +++ /dev/null @@ -1,22 +0,0 @@ -using ProxyForge.Transcoding; -using Xunit; - -namespace ProxyForge.Tests; - -public sealed class FFmpegExecutablesTests -{ - [Fact] - public void Unavailable_ReportsNotAvailable() - { - var executables = FFmpegExecutables.Unavailable; - - Assert.False(executables.IsAvailable); - Assert.Equal(string.Empty, executables.FFmpegPath); - } - - [Theory] - [InlineData("", false)] - [InlineData(@"C:\ffmpeg.exe", true)] - public void IsAvailable_RequiresTheExecutablePath(string ffmpegPath, bool expected) => - Assert.Equal(expected, new FFmpegExecutables(ffmpegPath).IsAvailable); -} diff --git a/ProxyForge.Tests/FFmpegPipelineTests.cs b/ProxyForge.Tests/FFmpegPipelineTests.cs deleted file mode 100644 index fe48414..0000000 --- a/ProxyForge.Tests/FFmpegPipelineTests.cs +++ /dev/null @@ -1,511 +0,0 @@ -using ProxyForge.Core; -using ProxyForge.Plugin; -using ProxyForge.Transcoding; -using System.Collections.ObjectModel; -using System.Diagnostics; -using System.IO; -using Xunit; - -namespace ProxyForge.Tests; - -public sealed class FFmpegPipelineTests -{ - private const string SoftwareEncoder = FFmpegArguments.SoftwareVideoEncoder; - - private static void RequireFFmpeg() - { - if (!Ymm4TestEnvironment.IsAvailable) - Assert.Skip("YMM4 bundled FFmpeg is not available on this machine."); - } - - [Fact] - public async Task EncodeAsync_ProducesProxyAtRequestedScale() - { - RequireFFmpeg(); - using var workspace = new Workspace(); - - using var encoder = CreateEncoder(workspace, 1280, 720, 30, 1, 30); - using var entry = await encoder.EncodeAsync( - workspace.SourcePath, 0.5f, 0.5f, 30, null, TestContext.Current.CancellationToken); - - Assert.Equal(640u, entry.ProxyWidth); - Assert.Equal(360u, entry.ProxyHeight); - Assert.Equal(0.5f, entry.Scale); - - var proxyPath = entry.GetCurrentDiskPath(); - Assert.NotNull(proxyPath); - Assert.StartsWith(workspace.Path, proxyPath, StringComparison.OrdinalIgnoreCase); - Assert.Equal(new FileInfo(proxyPath).Length, entry.DataSize); - - Assert.Equal("640", await workspace.ReadStreamEntryAsync(proxyPath, "width")); - Assert.Equal("360", await workspace.ReadStreamEntryAsync(proxyPath, "height")); - Assert.Equal("yuv420p", await workspace.ReadStreamEntryAsync(proxyPath, "pix_fmt")); - Assert.Equal("h264", await workspace.ReadStreamEntryAsync(proxyPath, "codec_name")); - } - - [Fact] - public async Task EncodeAsync_RendersEveryFrameOfTheSource() - { - RequireFFmpeg(); - using var workspace = new Workspace(); - - using var encoder = CreateEncoder(workspace, 640, 360, 30, 1, 45); - using var entry = await encoder.EncodeAsync( - workspace.SourcePath, 0.5f, 0.5f, 30, null, TestContext.Current.CancellationToken); - - Assert.Equal("45", await workspace.ReadStreamEntryAsync(entry.GetCurrentDiskPath()!, "nb_frames")); - Assert.Equal(46, workspace.Source!.UpdateCount); - } - - [Fact] - public async Task EncodeAsync_PreservesIntegerFrameRate() - { - RequireFFmpeg(); - using var workspace = new Workspace(); - - using var encoder = CreateEncoder(workspace, 640, 360, 30, 1, 60); - using var entry = await encoder.EncodeAsync( - workspace.SourcePath, 0.5f, 0.5f, 30, null, TestContext.Current.CancellationToken); - - var proxyPath = entry.GetCurrentDiskPath()!; - Assert.Equal("30/1", await workspace.ReadStreamEntryAsync(proxyPath, "r_frame_rate")); - Assert.Equal("60", await workspace.ReadStreamEntryAsync(proxyPath, "nb_frames")); - Assert.Equal( - workspace.Source!.Duration.TotalSeconds, - await workspace.ReadDurationSecondsAsync(proxyPath), - 2); - } - - [Fact] - public async Task EncodeAsync_PreservesNtscFrameRate() - { - RequireFFmpeg(); - using var workspace = new Workspace(); - - using var encoder = CreateEncoder(workspace, 640, 360, 30000, 1001, 120); - using var entry = await encoder.EncodeAsync( - workspace.SourcePath, 0.5f, 0.5f, 30, null, TestContext.Current.CancellationToken); - - var proxyPath = entry.GetCurrentDiskPath()!; - Assert.Equal("30000/1001", await workspace.ReadStreamEntryAsync(proxyPath, "r_frame_rate")); - Assert.Equal("120", await workspace.ReadStreamEntryAsync(proxyPath, "nb_frames")); - Assert.Equal( - workspace.Source!.Duration.TotalSeconds, - await workspace.ReadDurationSecondsAsync(proxyPath), - 3); - } - - [Fact] - public async Task EncodeAsync_PreservesSourceColour() - { - RequireFFmpeg(); - using var workspace = new Workspace(); - - using var encoder = CreateEncoder(workspace, 640, 360, 30, 1, 10, blue: 32, green: 160, red: 200); - using var entry = await encoder.EncodeAsync( - workspace.SourcePath, 0.5f, 0.5f, 30, null, TestContext.Current.CancellationToken); - - var (blue, green, red) = await workspace.ReadCentrePixelAsync(entry.GetCurrentDiskPath()!, 320, 180); - - Assert.InRange(blue, 32 - 8, 32 + 8); - Assert.InRange(green, 160 - 8, 160 + 8); - Assert.InRange(red, 200 - 8, 200 + 8); - } - - [Fact] - public async Task EncodeAsync_UsesTheSourceDisplaySizeIncludingAspect() - { - RequireFFmpeg(); - using var workspace = new Workspace(); - - using var encoder = CreateEncoder(workspace, 1080, 1920, 30, 1, 10); - using var entry = await encoder.EncodeAsync( - workspace.SourcePath, 0.5f, 0.5f, 30, null, TestContext.Current.CancellationToken); - - Assert.Equal(540u, entry.ProxyWidth); - Assert.Equal(960u, entry.ProxyHeight); - } - - [Fact] - public async Task EncodeAsync_AlreadyCanceledToken_LeavesNoTemporaryFile() - { - RequireFFmpeg(); - using var workspace = new Workspace(); - - using var cancellation = new CancellationTokenSource(); - await cancellation.CancelAsync(); - - using var encoder = CreateEncoder(workspace, 640, 360, 30, 1, 10); - await Assert.ThrowsAnyAsync(() => encoder.EncodeAsync( - workspace.SourcePath, 0.5f, 0.5f, 30, null, cancellation.Token)); - - Assert.Empty(Directory.GetFiles(workspace.Path, "zdp_*.mp4")); - } - - [Fact] - public async Task EncodeAsync_WhenNoPluginAcceptsTheFile_Throws() - { - RequireFFmpeg(); - using var workspace = new Workspace(); - - using var encoder = new FFmpegProxyEncoder( - workspace.Path, - new EncoderConfig(false), - Ymm4TestEnvironment.Executables, - static (_, _) => null); - - var exception = await Assert.ThrowsAsync(() => encoder.EncodeAsync( - workspace.SourcePath, 0.5f, 0.5f, 30, null, TestContext.Current.CancellationToken)); - - Assert.Contains("video file source plugin", exception.Message, StringComparison.OrdinalIgnoreCase); - Assert.Empty(Directory.GetFiles(workspace.Path, "zdp_*.mp4")); - } - - [Fact] - public async Task EncodeAsync_RelativeInputPath_Throws() - { - RequireFFmpeg(); - using var workspace = new Workspace(); - - using var encoder = CreateEncoder(workspace, 640, 360, 30, 1, 10); - await Assert.ThrowsAsync(() => encoder.EncodeAsync( - "relative.mp4", 0.5f, 0.5f, 30, null, TestContext.Current.CancellationToken)); - } - - [Fact] - public async Task EncodeAsync_UnavailableExecutables_Throws() - { - using var workspace = new Workspace(); - - using var encoder = new FFmpegProxyEncoder( - workspace.Path, - new EncoderConfig(false), - FFmpegExecutables.Unavailable, - static (_, _) => null); - - await Assert.ThrowsAsync(() => encoder.EncodeAsync( - workspace.SourcePath, 0.5f, 0.5f, 30, null, TestContext.Current.CancellationToken)); - } - - [Fact] - public async Task RunAsync_CancellationKillsTheProcessPromptly() - { - RequireFFmpeg(); - using var workspace = new Workspace(); - - using var cancellation = new CancellationTokenSource(TimeSpan.FromMilliseconds(750)); - var stopwatch = Stopwatch.StartNew(); - - await Assert.ThrowsAnyAsync(() => FFmpegProcessRunner.RunAsync( - Ymm4TestEnvironment.FFmpegPath, - static arguments => - { - arguments.Add("-hide_banner"); - arguments.Add("-nostdin"); - arguments.Add("-loglevel"); - arguments.Add("error"); - arguments.Add("-f"); - arguments.Add("lavfi"); - arguments.Add("-i"); - arguments.Add("testsrc2=size=1920x1080:rate=30:duration=600"); - arguments.Add("-c:v"); - arguments.Add(SoftwareEncoder); - arguments.Add("-f"); - arguments.Add("null"); - arguments.Add("-"); - }, - workspace.Path, - null, - null, - ProcessPriorityClass.BelowNormal, - cancellation.Token)); - - stopwatch.Stop(); - Assert.True(stopwatch.Elapsed < TimeSpan.FromSeconds(30), $"Cancellation took {stopwatch.Elapsed}."); - } - - [Fact] - public async Task RunAsync_NonZeroExitCodeCapturesDiagnostics() - { - RequireFFmpeg(); - using var workspace = new Workspace(); - - var result = await FFmpegProcessRunner.RunAsync( - Ymm4TestEnvironment.FFmpegPath, - static arguments => - { - arguments.Add("-hide_banner"); - arguments.Add("-nostdin"); - arguments.Add("-loglevel"); - arguments.Add("error"); - arguments.Add("-i"); - arguments.Add("nonexistent-input-file.mp4"); - arguments.Add("-f"); - arguments.Add("null"); - arguments.Add("-"); - }, - workspace.Path, - null, - null, - ProcessPriorityClass.BelowNormal, - TestContext.Current.CancellationToken); - - Assert.False(result.IsSuccess); - Assert.NotEqual(string.Empty, result.FirstDiagnosticLine(200)); - } - - [Fact] - public async Task RunAsync_DecodesNonAsciiDiagnosticsAsUtf8() - { - RequireFFmpeg(); - using var workspace = new Workspace(); - - var broken = Path.Combine(workspace.Path, "壊れた動画ファイル.mp4"); - await File.WriteAllTextAsync(broken, "not a video", TestContext.Current.CancellationToken); - - var result = await FFmpegProcessRunner.RunAsync( - Ymm4TestEnvironment.FFmpegPath, - arguments => - { - arguments.Add("-hide_banner"); - arguments.Add("-nostdin"); - arguments.Add("-loglevel"); - arguments.Add("error"); - arguments.Add("-i"); - arguments.Add(broken); - arguments.Add("-f"); - arguments.Add("null"); - arguments.Add("-"); - }, - workspace.Path, - null, - null, - ProcessPriorityClass.BelowNormal, - TestContext.Current.CancellationToken); - - Assert.False(result.IsSuccess); - Assert.Contains("壊れた動画ファイル.mp4", result.Diagnostics); - } - - [Fact] - public async Task RunAsync_InputWriterFailurePropagates() - { - RequireFFmpeg(); - using var workspace = new Workspace(); - - var failure = await Assert.ThrowsAsync(() => FFmpegProcessRunner.RunAsync( - Ymm4TestEnvironment.FFmpegPath, - static arguments => - { - arguments.Add("-hide_banner"); - arguments.Add("-loglevel"); - arguments.Add("error"); - arguments.Add("-f"); - arguments.Add("rawvideo"); - arguments.Add("-pix_fmt"); - arguments.Add("bgra"); - arguments.Add("-s"); - arguments.Add("32x32"); - arguments.Add("-r"); - arguments.Add("30/1"); - arguments.Add("-i"); - arguments.Add("-"); - arguments.Add("-f"); - arguments.Add("null"); - arguments.Add("-"); - }, - workspace.Path, - null, - static (_, _) => throw new IOException("frame source exploded"), - ProcessPriorityClass.BelowNormal, - TestContext.Current.CancellationToken)); - - Assert.IsType(failure.InnerException); - } - - [Fact] - public async Task ResolveAsync_HardwareDisabled_SelectsSoftwareEncoder() - { - RequireFFmpeg(); - using var workspace = new Workspace(); - - var encoder = await FFmpegEncoderSelector.ResolveAsync( - Ymm4TestEnvironment.FFmpegPath, false, 960, 540, workspace.Path, - TestContext.Current.CancellationToken); - - Assert.Equal(SoftwareEncoder, encoder); - } - - [Fact] - public async Task ResolveAsync_HardwareEnabled_SelectsAnEncoderThatActuallyRuns() - { - RequireFFmpeg(); - using var workspace = new Workspace(); - - var encoder = await FFmpegEncoderSelector.ResolveAsync( - Ymm4TestEnvironment.FFmpegPath, true, 320, 240, workspace.Path, - TestContext.Current.CancellationToken); - - string[] permitted = [SoftwareEncoder, .. FFmpegEncoderCandidates.Hardware264.ToArray()]; - Assert.Contains(encoder, permitted); - - var repeated = await FFmpegEncoderSelector.ResolveAsync( - Ymm4TestEnvironment.FFmpegPath, true, 320, 240, workspace.Path, - TestContext.Current.CancellationToken); - - Assert.Equal(encoder, repeated); - } - - [Fact] - public async Task EncodeAsync_HandlesFullHdSourceAtRealisticLength() - { - RequireFFmpeg(); - using var workspace = new Workspace(); - - using var encoder = CreateEncoder(workspace, 1920, 1080, 30, 1, 300); - using var entry = await encoder.EncodeAsync( - workspace.SourcePath, 0.5f, 0.5f, 30, null, TestContext.Current.CancellationToken); - - Assert.Equal(960u, entry.ProxyWidth); - Assert.Equal(540u, entry.ProxyHeight); - Assert.Equal("300", await workspace.ReadStreamEntryAsync(entry.GetCurrentDiskPath()!, "nb_frames")); - } - - private static FFmpegProxyEncoder CreateEncoder( - Workspace workspace, - int width, - int height, - int frameRateNumerator, - int frameRateDenominator, - int frameCount, - byte blue = 64, - byte green = 64, - byte red = 64) - { - Ymm4VideoSourceFactory factory = (devices, _) => - { - var source = new SolidColorVideoSource( - devices, width, height, frameRateNumerator, frameRateDenominator, frameCount, blue, green, red); - workspace.Source = source; - return source; - }; - - return new FFmpegProxyEncoder( - workspace.Path, new EncoderConfig(false), Ymm4TestEnvironment.Executables, factory); - } - - private sealed class Workspace : IDisposable - { - internal string Path { get; } = - System.IO.Path.Combine(System.IO.Path.GetTempPath(), "ProxyForgeTests", Guid.NewGuid().ToString("N")); - - internal string SourcePath => System.IO.Path.Combine(Path, "source.mp4"); - - internal SolidColorVideoSource? Source { get; set; } - - internal Workspace() => Directory.CreateDirectory(Path); - - internal async Task ReadStreamEntryAsync(string path, string entry) - { - var values = await ProbeAsync(path, "stream=" + entry); - return values.Length > 0 ? values[0] : string.Empty; - } - - internal async Task ReadDurationSecondsAsync(string path) - { - var values = await ProbeAsync(path, "format=duration"); - return values.Length > 0 - ? double.Parse(values[0], System.Globalization.CultureInfo.InvariantCulture) - : 0d; - } - - internal async Task<(byte Blue, byte Green, byte Red)> ReadCentrePixelAsync(string path, int width, int height) - { - var rawPath = System.IO.Path.Combine(Path, "frame.raw"); - await RunFFmpegAsync(arguments => - { - arguments.Add("-hide_banner"); - arguments.Add("-nostdin"); - arguments.Add("-loglevel"); - arguments.Add("error"); - arguments.Add("-y"); - arguments.Add("-i"); - arguments.Add(path); - arguments.Add("-frames:v"); - arguments.Add("1"); - arguments.Add("-f"); - arguments.Add("rawvideo"); - arguments.Add("-pix_fmt"); - arguments.Add("bgra"); - arguments.Add(rawPath); - }); - - var bytes = await File.ReadAllBytesAsync(rawPath); - var offset = ((height / 2 * width) + (width / 2)) * 4; - return (bytes[offset], bytes[offset + 1], bytes[offset + 2]); - } - - private async Task ProbeAsync(string path, string showEntries) - { - var values = new List(); - - void Collect(ReadOnlySpan line) - { - var trimmed = line.Trim(); - if (!trimmed.IsEmpty) - values.Add(new string(trimmed)); - } - - var result = await FFmpegProcessRunner.RunAsync( - Ymm4TestEnvironment.FFprobePath, - arguments => - { - arguments.Add("-hide_banner"); - arguments.Add("-loglevel"); - arguments.Add("error"); - arguments.Add("-select_streams"); - arguments.Add("v:0"); - arguments.Add("-show_entries"); - arguments.Add(showEntries); - arguments.Add("-of"); - arguments.Add("csv=p=0"); - arguments.Add("-i"); - arguments.Add(path); - }, - Path, - Collect, - null, - ProcessPriorityClass.BelowNormal, - CancellationToken.None); - - Assert.True(result.IsSuccess, result.Diagnostics); - return [.. values]; - } - - private async Task RunFFmpegAsync(Action> argumentWriter) - { - var result = await FFmpegProcessRunner.RunAsync( - Ymm4TestEnvironment.FFmpegPath, - argumentWriter, - Path, - null, - null, - ProcessPriorityClass.BelowNormal, - CancellationToken.None); - - Assert.True(result.IsSuccess, result.Diagnostics); - } - - public void Dispose() - { - try - { - if (Directory.Exists(Path)) - Directory.Delete(Path, true); - } - catch - { - } - } - } -} diff --git a/ProxyForge.Tests/FrameRateTests.cs b/ProxyForge.Tests/FrameRateTests.cs deleted file mode 100644 index 326ab5d..0000000 --- a/ProxyForge.Tests/FrameRateTests.cs +++ /dev/null @@ -1,130 +0,0 @@ -using ProxyForge.Transcoding; -using Xunit; - -namespace ProxyForge.Tests; - -public sealed class FrameRateTests -{ - [Fact] - public void FromFrameCountAndDuration_ReproducesIntegerRate() - { - var rate = FrameRate.FromFrameCountAndDuration(180, TimeSpan.FromSeconds(6)); - - Assert.Equal(30, rate.Numerator); - Assert.Equal(1, rate.Denominator); - } - - [Fact] - public void FromFrameCountAndDuration_ReproducesNtscRateExactly() - { - var duration = TimeSpan.FromTicks(120L * TimeSpan.TicksPerSecond * 1001L / 30000L); - - var rate = FrameRate.FromFrameCountAndDuration(120, duration); - - Assert.Equal(30000, rate.Numerator); - Assert.Equal(1001, rate.Denominator); - } - - [Theory] - [InlineData(24, 1)] - [InlineData(25, 1)] - [InlineData(50, 1)] - [InlineData(60, 1)] - [InlineData(24000, 1001)] - [InlineData(60000, 1001)] - public void FromFrameCountAndDuration_RoundTripsCommonRates(int numerator, int denominator) - { - const int frameCount = 600; - var duration = TimeSpan.FromTicks( - frameCount * TimeSpan.TicksPerSecond * denominator / numerator); - - var rate = FrameRate.FromFrameCountAndDuration(frameCount, duration); - - Assert.Equal(numerator, rate.Numerator); - Assert.Equal(denominator, rate.Denominator); - } - - [Fact] - public void FromFrameCountAndDuration_LongDurationStaysWithinIntegerRange() - { - var duration = TimeSpan.FromHours(3); - var frameCount = (int)(duration.TotalSeconds * 30); - - var rate = FrameRate.FromFrameCountAndDuration(frameCount, duration); - - Assert.True(rate.IsValid); - Assert.Equal(30d, rate.Value, 9); - } - - [Fact] - public void FromFrameCountAndDuration_AwkwardDurationApproximatesRate() - { - var duration = TimeSpan.FromTicks(36_000_000_001L); - - var rate = FrameRate.FromFrameCountAndDuration(108_000, duration); - - Assert.True(rate.IsValid); - Assert.InRange(rate.Value, 29.999_999, 30.000_001); - } - - [Theory] - [InlineData(0)] - [InlineData(-1)] - public void FromFrameCountAndDuration_RejectsNonPositiveFrameCount(int frameCount) => - Assert.Throws(() => - FrameRate.FromFrameCountAndDuration(frameCount, TimeSpan.FromSeconds(1))); - - [Fact] - public void FromFrameCountAndDuration_RejectsZeroDuration() => - Assert.Throws(() => - FrameRate.FromFrameCountAndDuration(1, TimeSpan.Zero)); - - [Fact] - public void GetSampleTime_SamplesTheMiddleOfEachFrameInterval() - { - var duration = TimeSpan.FromSeconds(1); - - Assert.Equal(TimeSpan.FromTicks(TimeSpan.TicksPerSecond / 60), FrameRate.GetSampleTime(0, 30, duration)); - Assert.Equal(TimeSpan.FromTicks(TimeSpan.TicksPerSecond / 20), FrameRate.GetSampleTime(1, 30, duration)); - } - - [Fact] - public void GetSampleTime_StaysStrictlyInsideTheSourceDuration() - { - var duration = TimeSpan.FromSeconds(6); - - for (var index = 0; index < 180; index++) - { - var sample = FrameRate.GetSampleTime(index, 180, duration); - Assert.InRange(sample.Ticks, 0, duration.Ticks - 1); - } - } - - [Fact] - public void GetSampleTime_IsStrictlyIncreasing() - { - var duration = TimeSpan.FromSeconds(4.004); - var previous = TimeSpan.MinValue; - - for (var index = 0; index < 120; index++) - { - var sample = FrameRate.GetSampleTime(index, 120, duration); - Assert.True(sample > previous); - previous = sample; - } - } - - [Fact] - public void GetSampleTime_MapsBackToTheSameFrameIndex() - { - const int frameCount = 120; - var duration = TimeSpan.FromTicks(frameCount * TimeSpan.TicksPerSecond * 1001L / 30000L); - - for (var index = 0; index < frameCount; index++) - { - var sample = FrameRate.GetSampleTime(index, frameCount, duration); - var recovered = (int)(sample.TotalSeconds * 30000d / 1001d); - Assert.Equal(index, recovered); - } - } -} diff --git a/ProxyForge.Tests/ProxyForge.Tests.csproj b/ProxyForge.Tests/ProxyForge.Tests.csproj deleted file mode 100644 index 4540e04..0000000 --- a/ProxyForge.Tests/ProxyForge.Tests.csproj +++ /dev/null @@ -1,57 +0,0 @@ - - - - net10.0-windows10.0.19041.0 - true - Exe - enable - enable - AnyCPU;x64 - false - - - - - - - - - - - - - - - $(YMM4DirPath)SharpGen.Runtime.dll - false - - - $(YMM4DirPath)Vortice.Direct2D1.dll - false - - - $(YMM4DirPath)Vortice.DirectX.dll - false - - - $(YMM4DirPath)Vortice.DXGI.dll - false - - - $(YMM4DirPath)Vortice.Mathematics.dll - false - - - $(YMM4DirPath)YukkuriMovieMaker.Plugin.dll - false - - - - - - <_Parameter1>YMM4DirPath - <_Parameter2>$(YMM4DirPath) - - - - diff --git a/ProxyForge.Tests/ProxyGeometryCalculatorTests.cs b/ProxyForge.Tests/ProxyGeometryCalculatorTests.cs deleted file mode 100644 index 3f052dd..0000000 --- a/ProxyForge.Tests/ProxyGeometryCalculatorTests.cs +++ /dev/null @@ -1,137 +0,0 @@ -using ProxyForge.Transcoding; -using Xunit; - -namespace ProxyForge.Tests; - -public sealed class ProxyGeometryCalculatorTests -{ - [Theory] - [InlineData(0, false)] - [InlineData(90, true)] - [InlineData(180, false)] - [InlineData(270, true)] - [InlineData(360, false)] - [InlineData(-90, true)] - [InlineData(-180, false)] - [InlineData(-270, true)] - [InlineData(450, true)] - public void IsQuarterTurn_NormalizesRotation(int rotation, bool expected) => - Assert.Equal(expected, ProxyGeometryCalculator.IsQuarterTurn(rotation)); - - [Theory] - [InlineData(1920u, 1080u, 0, 1920u, 1080u)] - [InlineData(1920u, 1080u, 90, 1080u, 1920u)] - [InlineData(1920u, 1080u, 180, 1920u, 1080u)] - [InlineData(1920u, 1080u, 270, 1080u, 1920u)] - [InlineData(1920u, 1080u, -90, 1080u, 1920u)] - public void GetDisplaySize_SwapsOnQuarterTurns( - uint codedWidth, uint codedHeight, int rotation, uint expectedWidth, uint expectedHeight) - { - var (width, height) = ProxyGeometryCalculator.GetDisplaySize(codedWidth, codedHeight, rotation); - Assert.Equal(expectedWidth, width); - Assert.Equal(expectedHeight, height); - } - - [Theory] - [InlineData(0u, 2u)] - [InlineData(1u, 2u)] - [InlineData(2u, 2u)] - [InlineData(3u, 2u)] - [InlineData(540u, 540u)] - [InlineData(541u, 540u)] - public void AlignEven_RoundsDownWithMinimumOfTwo(uint value, uint expected) => - Assert.Equal(expected, ProxyGeometryCalculator.AlignEven(value)); - - [Fact] - public void Calculate_HalfScaleOfFullHd_PreservesAspectRatioExactly() - { - var geometry = ProxyGeometryCalculator.Calculate(1920, 1080, 0.5f); - - Assert.Equal(960u, geometry.Width); - Assert.Equal(540u, geometry.Height); - Assert.Equal(0.5f, geometry.EffectiveScale); - Assert.Equal(1920d / 1080d, (double)geometry.Width / geometry.Height, 12); - } - - [Fact] - public void Calculate_RotatedSource_ProducesPortraitProxy() - { - var (displayWidth, displayHeight) = ProxyGeometryCalculator.GetDisplaySize(1920, 1080, 90); - var geometry = ProxyGeometryCalculator.Calculate(displayWidth, displayHeight, 0.5f); - - Assert.Equal(540u, geometry.Width); - Assert.Equal(960u, geometry.Height); - Assert.Equal(0.5f, geometry.EffectiveScale); - } - - [Theory] - [InlineData(0.1f, 192u, 108u)] - [InlineData(0.25f, 480u, 270u)] - [InlineData(0.75f, 1440u, 810u)] - [InlineData(1.0f, 1920u, 1080u)] - public void Calculate_ProducesEvenDimensionsForFullHd(float scale, uint expectedWidth, uint expectedHeight) - { - var geometry = ProxyGeometryCalculator.Calculate(1920, 1080, scale); - - Assert.Equal(expectedWidth, geometry.Width); - Assert.Equal(expectedHeight, geometry.Height); - Assert.Equal(0u, geometry.Width % 2); - Assert.Equal(0u, geometry.Height % 2); - } - - [Theory] - [InlineData(2.0f)] - [InlineData(float.PositiveInfinity)] - [InlineData(float.NaN)] - public void Calculate_NeverExceedsSourceResolution(float scale) - { - var geometry = ProxyGeometryCalculator.Calculate(1920, 1080, scale); - - Assert.Equal(1920u, geometry.Width); - Assert.Equal(1080u, geometry.Height); - } - - [Fact] - public void Calculate_OddSourceDimensions_ClampsToEvenSource() - { - var geometry = ProxyGeometryCalculator.Calculate(1081, 1081, 1.0f); - - Assert.Equal(1080u, geometry.Width); - Assert.Equal(1080u, geometry.Height); - } - - [Theory] - [InlineData(-1f)] - [InlineData(0f)] - public void Calculate_NonPositiveScale_FallsBackToMinimumDimensions(float scale) - { - var geometry = ProxyGeometryCalculator.Calculate(1920, 1080, scale); - - Assert.Equal(ProxyGeometryCalculator.MinimumDimension, geometry.Width); - Assert.Equal(ProxyGeometryCalculator.MinimumDimension, geometry.Height); - } - - [Fact] - public void Calculate_TinySource_StaysAtMinimumDimensions() - { - var geometry = ProxyGeometryCalculator.Calculate(10, 10, 0.1f); - - Assert.Equal(2u, geometry.Width); - Assert.Equal(2u, geometry.Height); - Assert.Equal(0.2f, geometry.EffectiveScale); - } - - [Theory] - [InlineData(0u, 1080u)] - [InlineData(1920u, 0u)] - public void Calculate_ZeroDimension_Throws(uint width, uint height) => - Assert.Throws(() => ProxyGeometryCalculator.Calculate(width, height, 0.5f)); - - [Fact] - public void Calculate_EffectiveScaleRestoresSourceWidth() - { - var geometry = ProxyGeometryCalculator.Calculate(1440, 1080, 0.33f); - - Assert.Equal(1440d, geometry.Width / geometry.EffectiveScale, 3); - } -} diff --git a/ProxyForge.Tests/SolidColorVideoSource.cs b/ProxyForge.Tests/SolidColorVideoSource.cs deleted file mode 100644 index cdc7aa8..0000000 --- a/ProxyForge.Tests/SolidColorVideoSource.cs +++ /dev/null @@ -1,81 +0,0 @@ -using System.Numerics; -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.Tests; - -internal sealed class SolidColorVideoSource : IVideoFileSource -{ - private const float ReferenceDpi = 96f; - - private readonly ID2D1Bitmap1 _bitmap; - private readonly AffineTransform2D _centering; - private readonly ID2D1Image _output; - private readonly int _frameRateNumerator; - private readonly int _frameRateDenominator; - - internal int UpdateCount { get; private set; } - - public TimeSpan Duration { get; } - - public ID2D1Image Output => _output; - - internal SolidColorVideoSource( - IGraphicsDevicesAndContext devices, - int width, - int height, - int frameRateNumerator, - int frameRateDenominator, - int frameCount, - byte blue, - byte green, - byte red) - { - _frameRateNumerator = frameRateNumerator; - _frameRateDenominator = frameRateDenominator; - Duration = TimeSpan.FromTicks( - frameCount * TimeSpan.TicksPerSecond * frameRateDenominator / frameRateNumerator); - - var stride = width * 4; - var pixels = new byte[stride * height]; - for (var offset = 0; offset < pixels.Length; offset += 4) - { - pixels[offset] = blue; - pixels[offset + 1] = green; - pixels[offset + 2] = red; - pixels[offset + 3] = 255; - } - - var pixelFormat = new PixelFormat(Format.B8G8R8A8_UNorm, Vortice.DCommon.AlphaMode.Premultiplied); - _bitmap = devices.DeviceContext.CreateBitmap( - new SizeI(width, height), nint.Zero, stride, - new BitmapProperties1(pixelFormat, ReferenceDpi, ReferenceDpi, BitmapOptions.None)); - _bitmap.CopyFromMemory(pixels, stride); - - _centering = new AffineTransform2D(devices.DeviceContext); - _centering.SetInput(0, _bitmap, true); - _centering.TransformMatrix = Matrix3x2.CreateTranslation( - MathF.Floor(-width / 2f), MathF.Floor(-height / 2f)); - _output = _centering.Output; - } - - public void Update(TimeSpan time) => UpdateCount++; - - public int GetFrameIndex(TimeSpan time) => - (int)Math.Round( - time.TotalSeconds * _frameRateNumerator / _frameRateDenominator, - MidpointRounding.AwayFromZero); - - public void Dispose() - { - _output.Dispose(); - _centering.SetInput(0, null, true); - _centering.Dispose(); - _bitmap.Dispose(); - } -} diff --git a/ProxyForge.Tests/Ymm4AssemblyResolver.cs b/ProxyForge.Tests/Ymm4AssemblyResolver.cs deleted file mode 100644 index b5be728..0000000 --- a/ProxyForge.Tests/Ymm4AssemblyResolver.cs +++ /dev/null @@ -1,42 +0,0 @@ -using System.IO; -using System.Reflection; -using System.Runtime.CompilerServices; - -namespace ProxyForge.Tests; - -internal static class Ymm4AssemblyResolver -{ - private static readonly string Ymm4Directory = ReadYmm4Directory(); - - internal static bool IsConfigured => Ymm4Directory.Length != 0 && Directory.Exists(Ymm4Directory); - - [ModuleInitializer] - internal static void Initialize() - { - if (!IsConfigured) - return; - - AppDomain.CurrentDomain.AssemblyResolve += Resolve; - } - - private static Assembly? Resolve(object? sender, ResolveEventArgs args) - { - var simpleName = new AssemblyName(args.Name).Name; - if (string.IsNullOrEmpty(simpleName)) - return null; - - var candidate = Path.Combine(Ymm4Directory, simpleName + ".dll"); - return File.Exists(candidate) ? Assembly.LoadFrom(candidate) : null; - } - - private static string ReadYmm4Directory() - { - foreach (var attribute in typeof(Ymm4AssemblyResolver).Assembly.GetCustomAttributes()) - { - if (attribute.Key == "YMM4DirPath") - return attribute.Value ?? string.Empty; - } - - return string.Empty; - } -} diff --git a/ProxyForge.Tests/Ymm4TestEnvironment.cs b/ProxyForge.Tests/Ymm4TestEnvironment.cs deleted file mode 100644 index f9f03a8..0000000 --- a/ProxyForge.Tests/Ymm4TestEnvironment.cs +++ /dev/null @@ -1,37 +0,0 @@ -using ProxyForge.Transcoding; -using System.IO; -using System.Reflection; - -namespace ProxyForge.Tests; - -internal static class Ymm4TestEnvironment -{ - private static readonly string BundledFFmpegDirectory = ResolveDirectory(); - - internal static bool IsAvailable => File.Exists(FFmpegPath) && File.Exists(FFprobePath); - - internal static string FFmpegPath => Path.Combine(BundledFFmpegDirectory, "ffmpeg.exe"); - - internal static string FFprobePath => Path.Combine(BundledFFmpegDirectory, "ffprobe.exe"); - - internal static FFmpegExecutables Executables => new(FFmpegPath); - - private static string ResolveDirectory() - { - var ymm4Directory = ReadYmm4Directory(); - return ymm4Directory.Length == 0 - ? string.Empty - : Path.Combine(ymm4Directory, "resources", "bin", "x64", "ffmpeg"); - } - - private static string ReadYmm4Directory() - { - foreach (var attribute in typeof(Ymm4TestEnvironment).Assembly.GetCustomAttributes()) - { - if (attribute.Key == "YMM4DirPath") - return attribute.Value ?? string.Empty; - } - - return string.Empty; - } -} diff --git a/ProxyForge.slnx b/ProxyForge.slnx deleted file mode 100644 index a13fbd4..0000000 --- a/ProxyForge.slnx +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - - - - - - - diff --git a/ProxyForge/Cache/VideoCacheDatabase.cs b/ProxyForge/Cache/VideoCacheDatabase.cs deleted file mode 100644 index bca8974..0000000 --- a/ProxyForge/Cache/VideoCacheDatabase.cs +++ /dev/null @@ -1,614 +0,0 @@ -using ProxyForge.Interfaces; -using System.Diagnostics; -using System.IO; -using System.IO.Hashing; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -namespace ProxyForge.Cache; - -internal sealed class VideoCacheDatabase : IVideoCacheDatabase -{ - private const long MagicNumber = 0x0042_4456_5F50_445A; - private const int FormatVersion = 1; - private const int HeaderSize = 32; - private const int HeaderCrcOffset = 16; - private const string OldDbFileName = "zerodiskproxy.vdb"; - private const string DbFileName = "proxyforge.vdb"; - private const string BackupSuffix = ".bak"; - private const string TempSuffix = ".tmp"; - - private readonly string _dbPath; - private readonly string _backupPath; - private readonly string _cacheDirectory; - private readonly VideoCacheDiskStore _diskStore; - private readonly Mutex _mutex; - private List _records; - private int _disposed; - - public string CacheDirectory => _cacheDirectory; - - internal VideoCacheDatabase(string cacheDirectory) - { - _cacheDirectory = cacheDirectory; - Directory.CreateDirectory(_cacheDirectory); - _dbPath = Path.Combine(_cacheDirectory, DbFileName); - _backupPath = _dbPath + BackupSuffix; - - var oldDbPath = Path.Combine(_cacheDirectory, OldDbFileName); - if (File.Exists(oldDbPath) && !File.Exists(_dbPath)) - { - Debug.WriteLine("[VideoCacheDatabase] Starting robust data migration to ProxyForge format."); - try - { - var migrationTempPath = _dbPath + ".migration.tmp"; - File.Copy(oldDbPath, migrationTempPath, true); - - var oldBackupPath = oldDbPath + BackupSuffix; - var migrationBackupTempPath = _backupPath + ".migration.tmp"; - var hasBackup = File.Exists(oldBackupPath); - if (hasBackup) - { - File.Copy(oldBackupPath, migrationBackupTempPath, true); - } - - File.Move(migrationTempPath, _dbPath, true); - if (hasBackup) - { - File.Move(migrationBackupTempPath, _backupPath, true); - } - - File.Delete(oldDbPath); - if (hasBackup) - { - File.Delete(oldBackupPath); - } - var oldTempPath = oldDbPath + TempSuffix; - if (File.Exists(oldTempPath)) - { - File.Delete(oldTempPath); - } - - Debug.WriteLine("[VideoCacheDatabase] Migration completed successfully. Legacy files removed."); - } - catch (Exception ex) - { - Debug.WriteLine(string.Concat("[VideoCacheDatabase] Migration failed: ", ex.Message)); - } - } - - _diskStore = new VideoCacheDiskStore(_cacheDirectory); - - Span hashBuf = stackalloc byte[32]; - VideoCacheRecord.ComputePathHashToSpan(_cacheDirectory.AsSpan(), hashBuf); - Span mutexName = stackalloc char[64]; - "Global\\ZDP_VDB_".AsSpan().CopyTo(mutexName); - for (var i = 0; i < 16; i++) - hashBuf[i].TryFormat(mutexName[(15 + i * 2)..], out _, "X2"); - _mutex = new Mutex(false, new string(mutexName[..47])); - - _records = []; - LoadDatabase(); - } - - public bool TryGet(string originalPath, float scale, out VideoCacheLookupResult result) - { - ObjectDisposedException.ThrowIf(Volatile.Read(ref _disposed) != 0, this); - - Span hashBuf = stackalloc byte[VideoCacheRecord.HashBytes]; - VideoCacheRecord.ComputePathHashToSpan(originalPath.AsSpan(), hashBuf); - - lock (_records) - { - for (var i = 0; i < _records.Count; i++) - { - ref var rec = ref CollectionsMarshal.AsSpan(_records)[i]; - if (!rec.IsActive) - continue; - - if (!rec.MatchesPathAndScale(originalPath.AsSpan(), hashBuf, scale)) - continue; - - if (!_diskStore.FileExists(rec.Uuid)) - { - rec.Flags = 0; - rec.RecomputeCrc32(); - ScheduleFlush(); - continue; - } - - rec.UpdateLastAccess(); - result = ToLookupResult(in rec); - return true; - } - } - - result = default; - return false; - } - - public VideoCacheLookupResult[] GetAll() - { - ObjectDisposedException.ThrowIf(Volatile.Read(ref _disposed) != 0, this); - - lock (_records) - { - if (_records.Count == 0) - return []; - - var count = 0; - var span = CollectionsMarshal.AsSpan(_records); - for (var i = 0; i < span.Length; i++) - { - if (span[i].IsActive) - count++; - } - - if (count == 0) - return []; - - var results = new VideoCacheLookupResult[count]; - var idx = 0; - for (var i = 0; i < span.Length; i++) - { - if (span[i].IsActive) - results[idx++] = ToLookupResult(in span[i]); - } - return results; - } - } - - public void Add(string originalPath, float scale, uint proxyWidth, uint proxyHeight, - long fileSize, uint fileCrc32, Guid uuid) - { - ObjectDisposedException.ThrowIf(Volatile.Read(ref _disposed) != 0, this); - - Span hashBuf = stackalloc byte[VideoCacheRecord.HashBytes]; - VideoCacheRecord.ComputePathHashToSpan(originalPath.AsSpan(), hashBuf); - - lock (_records) - { - var span = CollectionsMarshal.AsSpan(_records); - for (var i = 0; i < span.Length; i++) - { - if (span[i].IsActive && span[i].MatchesPathAndScale(originalPath.AsSpan(), hashBuf, scale)) - { - _diskStore.DeleteFile(span[i].Uuid); - span[i].Flags = 0; - span[i].RecomputeCrc32(); - } - } - - var record = new VideoCacheRecord - { - Uuid = uuid, - PathLength = Math.Min(originalPath.Length, VideoCacheRecord.PathMaxChars), - Scale = scale, - ProxyWidth = proxyWidth, - ProxyHeight = proxyHeight, - FileSize = fileSize, - CreatedAtTicks = DateTime.UtcNow.Ticks, - LastAccessedTicks = DateTime.UtcNow.Ticks, - Flags = VideoCacheRecord.FlagActive, - FileCrc32 = fileCrc32 - }; - - VideoCacheRecord.ComputePathHash(originalPath.AsSpan(), ref record.PathHash); - WritePathToRecord(originalPath, ref record); - record.RecomputeCrc32(); - - _records.Add(record); - } - - FlushToFile(); - } - - public bool Remove(Guid uuid) - { - ObjectDisposedException.ThrowIf(Volatile.Read(ref _disposed) != 0, this); - - lock (_records) - { - var span = CollectionsMarshal.AsSpan(_records); - for (var i = 0; i < span.Length; i++) - { - if (span[i].Uuid == uuid && span[i].IsActive) - { - _diskStore.DeleteFile(span[i].Uuid); - span[i].Flags = 0; - span[i].RecomputeCrc32(); - FlushToFile(); - return true; - } - } - } - return false; - } - - public int RemoveByPath(string originalPath) - { - ObjectDisposedException.ThrowIf(Volatile.Read(ref _disposed) != 0, this); - - Span hashBuf = stackalloc byte[VideoCacheRecord.HashBytes]; - VideoCacheRecord.ComputePathHashToSpan(originalPath.AsSpan(), hashBuf); - var removed = 0; - - lock (_records) - { - var span = CollectionsMarshal.AsSpan(_records); - for (var i = 0; i < span.Length; i++) - { - if (!span[i].IsActive) - continue; - - if (!span[i].MatchesPath(originalPath.AsSpan(), hashBuf)) - continue; - - _diskStore.DeleteFile(span[i].Uuid); - span[i].Flags = 0; - span[i].RecomputeCrc32(); - removed++; - } - } - - if (removed > 0) - FlushToFile(); - - return removed; - } - - public int ClearAll() - { - ObjectDisposedException.ThrowIf(Volatile.Read(ref _disposed) != 0, this); - - int count; - lock (_records) - { - count = 0; - var span = CollectionsMarshal.AsSpan(_records); - for (var i = 0; i < span.Length; i++) - { - if (span[i].IsActive) - { - _diskStore.DeleteFile(span[i].Uuid); - count++; - } - } - _records.Clear(); - } - - FlushToFile(); - return count; - } - - public void UpdateLastAccess(Guid uuid) - { - lock (_records) - { - var span = CollectionsMarshal.AsSpan(_records); - for (var i = 0; i < span.Length; i++) - { - if (span[i].Uuid == uuid) - { - span[i].UpdateLastAccess(); - break; - } - } - } - } - - public string GetCacheFilePath(Guid uuid) => - _diskStore.GetFilePath(uuid); - - internal VideoCacheDiskStore DiskStore => _diskStore; - - private void LoadDatabase() - { - _mutex.WaitOne(); - try - { - if (TryLoadFromFile(_dbPath)) - return; - - Debug.WriteLine("[VideoCacheDatabase] Primary DB failed, trying backup"); - if (TryLoadFromFile(_backupPath)) - { - FlushToFileCore(); - return; - } - - Debug.WriteLine("[VideoCacheDatabase] Both DB files failed, rebuilding from disk"); - RebuildFromDisk(); - FlushToFileCore(); - } - finally - { - _mutex.ReleaseMutex(); - } - } - - private bool TryLoadFromFile(string path) - { - if (!File.Exists(path)) - return false; - - try - { - using var fs = new FileStream( - path, FileMode.Open, FileAccess.Read, FileShare.Read, 65536, - FileOptions.SequentialScan); - - if (fs.Length < HeaderSize) - return false; - - Span headerBuf = stackalloc byte[HeaderSize]; - if (fs.Read(headerBuf) < HeaderSize) - return false; - - var magic = MemoryMarshal.Read(headerBuf); - if (magic != MagicNumber) - return false; - - var version = MemoryMarshal.Read(headerBuf[8..]); - if (version != FormatVersion) - return false; - - var headerCrc = MemoryMarshal.Read(headerBuf[HeaderCrcOffset..]); - headerBuf.Slice(HeaderCrcOffset, 4).Clear(); - var computedHeaderCrc = Crc32.HashToUInt32(headerBuf[..HeaderCrcOffset]); - if (headerCrc != computedHeaderCrc) - return false; - - var recordCount = MemoryMarshal.Read(headerBuf[12..]); - if (recordCount < 0 || recordCount > 100_000) - return false; - - var expectedSize = HeaderSize + (long)recordCount * VideoCacheRecord.RecordSize; - if (fs.Length < expectedSize) - return false; - - var records = new List(recordCount); - var recordBuf = new byte[VideoCacheRecord.RecordSize]; - var repairNeeded = false; - - for (var i = 0; i < recordCount; i++) - { - if (fs.Read(recordBuf) < VideoCacheRecord.RecordSize) - break; - - var record = MemoryMarshal.Read(recordBuf); - - if (!record.ValidateCrc32()) - { - Debug.WriteLine(string.Concat("[VideoCacheDatabase] Corrupt record at index ", i.ToString())); - if (TryRepairRecord(ref record)) - { - repairNeeded = true; - records.Add(record); - } - continue; - } - - if (record.IsActive && !_diskStore.FileExists(record.Uuid)) - { - record.Flags = 0; - record.RecomputeCrc32(); - repairNeeded = true; - } - - records.Add(record); - } - - lock (_records) - { - _records = records; - } - - if (repairNeeded) - FlushToFileCore(); - - return true; - } - catch (Exception ex) - { - Debug.WriteLine(string.Concat("[VideoCacheDatabase] Load failed: ", ex.Message)); - return false; - } - } - - private bool TryRepairRecord(ref VideoCacheRecord record) - { - if (!_diskStore.FileExists(record.Uuid)) - return false; - - try - { - var fileSize = _diskStore.GetFileSize(record.Uuid); - if (fileSize <= 0) - return false; - - record.FileSize = fileSize; - record.FileCrc32 = _diskStore.ComputeFileCrc32(record.Uuid); - record.Flags = VideoCacheRecord.FlagActive; - record.LastAccessedTicks = DateTime.UtcNow.Ticks; - record.RecomputeCrc32(); - return true; - } - catch - { - return false; - } - } - - private void RebuildFromDisk() - { - var records = new List(); - - try - { - foreach (var file in Directory.EnumerateFiles(_cacheDirectory, "*.mp4")) - { - var name = Path.GetFileNameWithoutExtension(file); - if (!Guid.TryParse(name, out var uuid)) - continue; - - try - { - var info = new FileInfo(file); - if (!info.Exists || info.Length == 0) - continue; - - var record = new VideoCacheRecord - { - Uuid = uuid, - PathLength = 0, - Scale = 0.5f, - ProxyWidth = 0, - ProxyHeight = 0, - FileSize = info.Length, - CreatedAtTicks = info.CreationTimeUtc.Ticks, - LastAccessedTicks = info.LastAccessTimeUtc.Ticks, - Flags = VideoCacheRecord.FlagActive, - FileCrc32 = _diskStore.ComputeFileCrc32(uuid) - }; - record.RecomputeCrc32(); - records.Add(record); - } - catch { } - } - } - catch { } - - lock (_records) - { - _records = records; - } - } - - private void FlushToFile() - { - _mutex.WaitOne(); - try - { - FlushToFileCore(); - } - finally - { - _mutex.ReleaseMutex(); - } - } - - private void FlushToFileCore() - { - List snapshot; - lock (_records) - { - snapshot = new List(_records.Count); - var span = CollectionsMarshal.AsSpan(_records); - for (var i = 0; i < span.Length; i++) - { - if (span[i].IsActive) - snapshot.Add(span[i]); - } - } - - try - { - if (File.Exists(_dbPath)) - { - try { File.Copy(_dbPath, _backupPath, true); } - catch { } - } - - var tempPath = _dbPath + TempSuffix; - - using (var fs = new FileStream( - tempPath, FileMode.Create, FileAccess.Write, FileShare.None, 65536, - FileOptions.WriteThrough)) - { - WriteHeader(fs, snapshot.Count); - - var span = CollectionsMarshal.AsSpan(snapshot); - for (var i = 0; i < span.Length; i++) - { - WriteRecord(fs, in span[i]); - } - - fs.Flush(true); - } - - File.Move(tempPath, _dbPath, true); - } - catch (Exception ex) - { - Debug.WriteLine(string.Concat("[VideoCacheDatabase] Flush failed: ", ex.Message)); - } - } - - private static void WriteHeader(FileStream fs, int recordCount) - { - Span header = stackalloc byte[HeaderSize]; - header.Clear(); - var magic = MagicNumber; - var version = FormatVersion; - MemoryMarshal.Write(header, in magic); - MemoryMarshal.Write(header[8..], in version); - MemoryMarshal.Write(header[12..], in recordCount); - var crc = Crc32.HashToUInt32(header[..HeaderCrcOffset]); - MemoryMarshal.Write(header[HeaderCrcOffset..], in crc); - fs.Write(header); - } - - private static void WriteRecord(FileStream fs, in VideoCacheRecord record) - { - ReadOnlySpan span = MemoryMarshal.CreateReadOnlySpan( - ref Unsafe.As(ref Unsafe.AsRef(in record)), - VideoCacheRecord.RecordSize); - fs.Write(span); - } - - private void ScheduleFlush() - { - _ = Task.Run(() => - { - try { FlushToFile(); } - catch { } - }); - } - - private static void WritePathToRecord(string path, ref VideoCacheRecord record) - { - Span raw = record.PathChars; - raw.Clear(); - var chars = MemoryMarshal.Cast(raw); - var len = Math.Min(path.Length, VideoCacheRecord.PathMaxChars); - path.AsSpan(0, len).CopyTo(chars); - record.PathLength = len; - } - - private static VideoCacheLookupResult ToLookupResult(in VideoCacheRecord rec) => - new(rec.Uuid, - rec.GetOriginalPath(), - rec.GetFileName(), - rec.Scale, - rec.ProxyWidth, - rec.ProxyHeight, - rec.FileSize, - rec.FileCrc32, - new DateTime(rec.CreatedAtTicks, DateTimeKind.Utc), - new DateTime(rec.LastAccessedTicks, DateTimeKind.Utc)); - - public void Dispose() - { - if (Interlocked.Exchange(ref _disposed, 1) != 0) - return; - - try - { - FlushToFile(); - } - catch { } - - _mutex.Dispose(); - } -} \ No newline at end of file diff --git a/ProxyForge/Cache/VideoCacheDiskStore.cs b/ProxyForge/Cache/VideoCacheDiskStore.cs deleted file mode 100644 index 23e403f..0000000 --- a/ProxyForge/Cache/VideoCacheDiskStore.cs +++ /dev/null @@ -1,192 +0,0 @@ -using ProxyForge.Memory; -using System.IO; -using System.IO.Hashing; - -namespace ProxyForge.Cache; - -internal sealed class VideoCacheDiskStore -{ - private readonly string _cacheDirectory; - - internal VideoCacheDiskStore(string cacheDirectory) - { - _cacheDirectory = cacheDirectory; - Directory.CreateDirectory(_cacheDirectory); - } - - internal string GetFilePath(Guid uuid) - { - Span buf = stackalloc char[36 + 4]; - uuid.TryFormat(buf, out _, "D"); - ".mp4".AsSpan().CopyTo(buf[36..]); - return Path.Combine(_cacheDirectory, new string(buf)); - } - - internal bool FileExists(Guid uuid) => - File.Exists(GetFilePath(uuid)); - - internal long GetFileSize(Guid uuid) - { - var path = GetFilePath(uuid); - try - { - var info = new FileInfo(path); - return info.Exists ? info.Length : 0; - } - catch - { - return 0; - } - } - - internal void SaveFromEntry(Guid uuid, byte[] data, int length) - { - var path = GetFilePath(uuid); - using var fs = new FileStream( - path, FileMode.Create, FileAccess.Write, FileShare.None, 65536, - FileOptions.SequentialScan | FileOptions.WriteThrough); - fs.Write(data, 0, length); - fs.Flush(true); - } - - internal void SaveFromStream(Guid uuid, Stream source) - { - var path = GetFilePath(uuid); - var buf = BufferPool.Rent(65536); - try - { - using var fs = new FileStream( - path, FileMode.Create, FileAccess.Write, FileShare.None, 65536, - FileOptions.SequentialScan | FileOptions.WriteThrough); - - int read; - while ((read = source.Read(buf, 0, buf.Length)) > 0) - fs.Write(buf, 0, read); - - fs.Flush(true); - } - finally - { - BufferPool.Return(buf); - } - } - - internal void CopyFromFile(Guid uuid, string sourcePath) - { - var destPath = GetFilePath(uuid); - var buf = BufferPool.Rent(65536); - try - { - using var src = new FileStream( - sourcePath, FileMode.Open, FileAccess.Read, FileShare.Read, 65536, - FileOptions.SequentialScan); - using var dst = new FileStream( - destPath, FileMode.Create, FileAccess.Write, FileShare.None, 65536, - FileOptions.SequentialScan | FileOptions.WriteThrough); - - int read; - while ((read = src.Read(buf, 0, buf.Length)) > 0) - dst.Write(buf, 0, read); - - dst.Flush(true); - } - finally - { - BufferPool.Return(buf); - } - } - - internal bool DeleteFile(Guid uuid) - { - var path = GetFilePath(uuid); - try - { - if (!File.Exists(path)) - return false; - File.Delete(path); - return true; - } - catch - { - return false; - } - } - - internal uint ComputeFileCrc32(Guid uuid) - { - var path = GetFilePath(uuid); - if (!File.Exists(path)) - return 0; - - var buf = BufferPool.Rent(65536); - try - { - using var fs = new FileStream( - path, FileMode.Open, FileAccess.Read, FileShare.Read, 65536, - FileOptions.SequentialScan); - - var crc = new Crc32(); - int read; - while ((read = fs.Read(buf, 0, buf.Length)) > 0) - crc.Append(buf.AsSpan(0, read)); - - Span hash = stackalloc byte[4]; - crc.GetHashAndReset(hash); - return System.Buffers.Binary.BinaryPrimitives.ReadUInt32LittleEndian(hash); - } - finally - { - BufferPool.Return(buf); - } - } - - internal uint ComputeFileCrc32FromPath(string filePath) - { - if (!File.Exists(filePath)) - return 0; - - var buf = BufferPool.Rent(65536); - try - { - using var fs = new FileStream( - filePath, FileMode.Open, FileAccess.Read, FileShare.Read, 65536, - FileOptions.SequentialScan); - - var crc = new Crc32(); - int read; - while ((read = fs.Read(buf, 0, buf.Length)) > 0) - crc.Append(buf.AsSpan(0, read)); - - Span hash = stackalloc byte[4]; - crc.GetHashAndReset(hash); - return System.Buffers.Binary.BinaryPrimitives.ReadUInt32LittleEndian(hash); - } - finally - { - BufferPool.Return(buf); - } - } - - internal int CleanupOrphanedFiles(HashSet knownUuids) - { - var removed = 0; - try - { - foreach (var file in Directory.EnumerateFiles(_cacheDirectory, "*.mp4")) - { - var name = Path.GetFileNameWithoutExtension(file); - if (Guid.TryParse(name, out var uuid) && !knownUuids.Contains(uuid)) - { - try - { - File.Delete(file); - removed++; - } - catch { } - } - } - } - catch { } - return removed; - } -} \ No newline at end of file diff --git a/ProxyForge/Cache/VideoCacheRecord.cs b/ProxyForge/Cache/VideoCacheRecord.cs deleted file mode 100644 index a674342..0000000 --- a/ProxyForge/Cache/VideoCacheRecord.cs +++ /dev/null @@ -1,173 +0,0 @@ -using System.IO.Hashing; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using System.Security.Cryptography; - -namespace ProxyForge.Cache; - -[StructLayout(LayoutKind.Sequential, Pack = 1)] -internal struct VideoCacheRecord : IEquatable -{ - internal const int PathMaxChars = 260; - internal const int PathBufferBytes = PathMaxChars * 2; - internal const int HashBytes = 32; - internal const int ReservedBytes = 36; - internal const int RecordSize = 656; - internal const int CrcOffset = 616; - - internal Guid Uuid; - internal PathHashBuffer PathHash; - internal int PathLength; - internal PathCharBuffer PathChars; - internal float Scale; - internal uint ProxyWidth; - internal uint ProxyHeight; - internal long FileSize; - internal long CreatedAtTicks; - internal long LastAccessedTicks; - internal int Flags; - internal uint FileCrc32; - internal uint RecordCrc32; - internal ReservedBuffer Reserved; - - [InlineArray(HashBytes)] - internal struct PathHashBuffer - { - private byte _element; - } - - [InlineArray(PathBufferBytes)] - internal struct PathCharBuffer - { - private byte _element; - } - - [InlineArray(ReservedBytes)] - internal struct ReservedBuffer - { - private byte _element; - } - - internal const int FlagActive = 1; - - internal readonly bool IsActive - { - [MethodImpl(MethodImplOptions.AggressiveInlining)] - get => (Flags & FlagActive) != 0; - } - - internal static VideoCacheRecord Create( - string originalPath, float scale, uint proxyWidth, uint proxyHeight, - long fileSize, uint fileCrc32) - { - var record = new VideoCacheRecord - { - Uuid = Guid.NewGuid(), - PathLength = Math.Min(originalPath.Length, PathMaxChars), - Scale = scale, - ProxyWidth = proxyWidth, - ProxyHeight = proxyHeight, - FileSize = fileSize, - CreatedAtTicks = DateTime.UtcNow.Ticks, - LastAccessedTicks = DateTime.UtcNow.Ticks, - Flags = FlagActive, - FileCrc32 = fileCrc32 - }; - - ComputePathHash(originalPath, ref record.PathHash); - WritePathChars(originalPath, ref record.PathChars, record.PathLength); - record.RecordCrc32 = record.ComputeCrc32(); - - return record; - } - - internal readonly string GetOriginalPath() - { - ReadOnlySpan raw = PathChars; - var chars = MemoryMarshal.Cast(raw); - return new string(chars[..PathLength]); - } - - internal readonly string GetFileName() - { - ReadOnlySpan raw = PathChars; - var chars = MemoryMarshal.Cast(raw)[..PathLength]; - var lastSep = chars.LastIndexOfAny('\\', '/'); - return lastSep >= 0 ? new string(chars[(lastSep + 1)..]) : new string(chars); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - internal readonly bool MatchesPath(ReadOnlySpan path, ReadOnlySpan pathHash) - { - ReadOnlySpan storedHash = PathHash; - if (!storedHash.SequenceEqual(pathHash)) - return false; - - ReadOnlySpan raw = PathChars; - var storedPath = MemoryMarshal.Cast(raw)[..PathLength]; - return storedPath.Equals(path, StringComparison.OrdinalIgnoreCase); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - internal readonly bool MatchesPathAndScale(ReadOnlySpan path, ReadOnlySpan pathHash, float scale) - { - return Scale == scale && MatchesPath(path, pathHash); - } - - internal readonly bool ValidateCrc32() - { - return RecordCrc32 == ComputeCrc32(); - } - - internal void RecomputeCrc32() - { - RecordCrc32 = ComputeCrc32(); - } - - internal void UpdateLastAccess() - { - LastAccessedTicks = DateTime.UtcNow.Ticks; - RecomputeCrc32(); - } - - private readonly uint ComputeCrc32() - { - ReadOnlySpan span = MemoryMarshal.CreateReadOnlySpan( - ref Unsafe.As(ref Unsafe.AsRef(in this)), - CrcOffset); - return Crc32.HashToUInt32(span); - } - - internal static void ComputePathHash(ReadOnlySpan path, ref PathHashBuffer hash) - { - Span upper = stackalloc char[Math.Min(path.Length, PathMaxChars)]; - path[..upper.Length].ToUpperInvariant(upper); - var bytes = MemoryMarshal.AsBytes(upper); - Span dest = hash; - SHA256.TryHashData(bytes, dest, out _); - } - - internal static void ComputePathHashToSpan(ReadOnlySpan path, Span dest) - { - Span upper = stackalloc char[Math.Min(path.Length, PathMaxChars)]; - path[..upper.Length].ToUpperInvariant(upper); - var bytes = MemoryMarshal.AsBytes(upper); - SHA256.TryHashData(bytes, dest, out _); - } - - private static void WritePathChars(string path, ref PathCharBuffer buffer, int length) - { - Span raw = buffer; - raw.Clear(); - var chars = MemoryMarshal.Cast(raw); - path.AsSpan(0, length).CopyTo(chars); - } - - public readonly bool Equals(VideoCacheRecord other) => - Uuid.Equals(other.Uuid); - - public override readonly bool Equals(object? obj) => - obj is VideoCacheRecord other && Equals(other); - - public override readonly int GetHashCode() => Uuid.GetHashCode(); -} \ No newline at end of file diff --git a/ProxyForge/Core/EncoderConfig.cs b/ProxyForge/Core/EncoderConfig.cs deleted file mode 100644 index e44595d..0000000 --- a/ProxyForge/Core/EncoderConfig.cs +++ /dev/null @@ -1,5 +0,0 @@ -namespace ProxyForge.Core; - -internal readonly record struct EncoderConfig( - bool EnableHardwareAcceleration -); diff --git a/ProxyForge/Core/FFmpegProxyEncoder.cs b/ProxyForge/Core/FFmpegProxyEncoder.cs deleted file mode 100644 index cc0ea60..0000000 --- a/ProxyForge/Core/FFmpegProxyEncoder.cs +++ /dev/null @@ -1,254 +0,0 @@ -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 deleted file mode 100644 index d1db582..0000000 --- a/ProxyForge/Core/FFmpegProxyEncoderFactory.cs +++ /dev/null @@ -1,14 +0,0 @@ -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/ProxyCacheEntry.cs b/ProxyForge/Core/ProxyCacheEntry.cs deleted file mode 100644 index 1d52bc3..0000000 --- a/ProxyForge/Core/ProxyCacheEntry.cs +++ /dev/null @@ -1,115 +0,0 @@ -using System.Diagnostics; -using System.IO; - -namespace ProxyForge.Core; - -internal sealed class ProxyCacheEntry : IDisposable -{ - private string? _diskPath; - private long _cachedSize; - private long _lastAccessedTicks = DateTime.UtcNow.Ticks; - private int _disposed; - private int _persistentDiskEntry; - - internal string OriginalPath { get; } - internal float Scale { get; } - internal uint ProxyWidth { get; init; } - internal uint ProxyHeight { get; init; } - - internal bool IsValid => - Volatile.Read(ref _disposed) == 0 && - 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) - { - OriginalPath = originalPath; - Scale = scale; - } - - internal void SetDiskPath(string path, long size) - { - Interlocked.Exchange(ref _cachedSize, size); - Volatile.Write(ref _diskPath, path); - UpdateLastAccess(); - } - - internal void MarkPersistent() => - Volatile.Write(ref _persistentDiskEntry, 1); - - internal string? GetCurrentDiskPath() => - Volatile.Read(ref _diskPath); - - internal void ReplaceDiskPath(string newPath) - { - Volatile.Write(ref _diskPath, newPath); - MarkPersistent(); - } - - internal Stream OpenReadStream() - { - var path = GetExistingFilePath(); - return new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, 65536, FileOptions.SequentialScan); - } - - internal string GetFilePath() => GetExistingFilePath(); - - internal CacheEntrySnapshot CreateSnapshot() => - new(OriginalPath, - Path.GetFileName(OriginalPath), - Scale, - ProxyWidth, - ProxyHeight, - DataSize, - CreatedAt, - LastAccessedAt); - - private string GetExistingFilePath() - { - ObjectDisposedException.ThrowIf(Volatile.Read(ref _disposed) != 0, this); - - var path = Volatile.Read(ref _diskPath); - if (path is null || !File.Exists(path)) - throw new InvalidOperationException("Proxy data unavailable"); - - UpdateLastAccess(); - return path; - } - - private void UpdateLastAccess() => - Interlocked.Exchange(ref _lastAccessedTicks, DateTime.UtcNow.Ticks); - - public void Dispose() - { - if (Interlocked.Exchange(ref _disposed, 1) != 0) - return; - - var disk = Interlocked.Exchange(ref _diskPath, null); - if (disk is null || Volatile.Read(ref _persistentDiskEntry) != 0) - return; - - try - { - if (File.Exists(disk)) - File.Delete(disk); - } - catch (Exception ex) - { - Debug.WriteLine(string.Concat("[ProxyCacheEntry] Delete failed: ", ex.Message)); - } - } -} - -internal readonly record struct CacheEntrySnapshot( - string OriginalPath, - string FileName, - float Scale, - uint ProxyWidth, - uint ProxyHeight, - long DataSize, - DateTime CreatedAt, - DateTime LastAccessedAt -); diff --git a/ProxyForge/Core/ProxyCacheManager.cs b/ProxyForge/Core/ProxyCacheManager.cs deleted file mode 100644 index ae91b64..0000000 --- a/ProxyForge/Core/ProxyCacheManager.cs +++ /dev/null @@ -1,343 +0,0 @@ -using ProxyForge.Cache; -using ProxyForge.Interfaces; -using ProxyForge.Localization; -using ProxyForge.Progress; -using ProxyForge.Settings; -using System.Collections.Concurrent; -using System.Collections.ObjectModel; -using System.Diagnostics; -using System.IO; -using System.Windows; - -namespace ProxyForge.Core; - -internal sealed class ProxyCacheManager : IDisposable -{ - private readonly record struct CacheKey(string Path, float Scale) : IEquatable - { - public bool Equals(CacheKey other) => - Scale == other.Scale && - string.Equals(Path, other.Path, StringComparison.OrdinalIgnoreCase); - - public override int GetHashCode() => - HashCode.Combine(StringComparer.OrdinalIgnoreCase.GetHashCode(Path), Scale); - } - - 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; - private int _disposed; - - internal ObservableCollection ActiveGenerations { get; } = []; - internal event Action? ProxyCompleted; - - internal ProxyCacheManager(IProxyEncoderFactory encoderFactory, VideoCacheDatabase? videoCache = null, string tmpDirectory = "") - { - _encoderFactory = encoderFactory; - _videoCache = videoCache; - _tmpDirectory = tmpDirectory; - } - - private static CacheKey MakeKey(string path, float scale) => - new(GetFullPath(path), scale); - - private static string GetFullPath(string path) - { - try { return Path.GetFullPath(path); } - catch { return path; } - } - - internal ProxyCacheEntry? TryGetProxy(string originalPath, float scale) - { - var key = MakeKey(originalPath, scale); - if (_cache.TryGetValue(key, out var entry) && entry.IsValid) - return entry; - - if (_videoCache is not null && - ProxyForgeSettings.Default.EnableVideoCache && - _videoCache.TryGet(originalPath, scale, out var dbResult)) - { - var cachePath = _videoCache.GetCacheFilePath(dbResult.Uuid); - if (File.Exists(cachePath)) - { - var diskEntry = new ProxyCacheEntry(originalPath, scale) - { - ProxyWidth = dbResult.ProxyWidth, - ProxyHeight = dbResult.ProxyHeight - }; - diskEntry.SetDiskPath(cachePath, dbResult.FileSize); - diskEntry.MarkPersistent(); - var stored = _cache.GetOrAdd(key, diskEntry); - if (!ReferenceEquals(stored, diskEntry)) - diskEntry.Dispose(); - _videoCache.UpdateLastAccess(dbResult.Uuid); - return stored.IsValid ? stored : null; - } - } - - return null; - } - - internal bool ProxyExists(string originalPath, float scale) - { - var key = MakeKey(originalPath, scale); - if (_cache.TryGetValue(key, out var entry) && entry.IsValid) - return true; - - if (_videoCache is not null && - ProxyForgeSettings.Default.EnableVideoCache && - _videoCache.TryGet(originalPath, scale, out _)) - return true; - - return false; - } - - internal void StartProxyGeneration(string originalPath, float scale, ProxyForgeSettings settings) - { - if (Volatile.Read(ref _disposed) != 0) - return; - - var key = MakeKey(originalPath, scale); - - if (_cache.TryGetValue(key, out var existing) && existing.IsValid) - return; - - var cts = new CancellationTokenSource(); - if (!_pendingGenerations.TryAdd(key, cts)) - { - cts.Dispose(); - return; - } - - _ = Task.Run(() => RunGenerationAsync(key, originalPath, scale, settings, cts), CancellationToken.None); - } - - private async Task RunGenerationAsync(CacheKey key, string originalPath, float scale, ProxyForgeSettings settings, CancellationTokenSource cts) - { - var progressItem = new ProxyGenerationItem(originalPath); - DispatchInvoke(() => ActiveGenerations.Add(progressItem)); - - var delayMs = 2000; - - try - { - 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)) - entry.Dispose(); - - if (_videoCache is not null && ProxyForgeSettings.Default.EnableVideoCache) - PersistToVideoCache(originalPath, scale, stored); - - DispatchInvoke(() => - { - progressItem.Progress = 100; - progressItem.IsCompleted = true; - progressItem.StatusMessage = Translate.ProxyGenerationStatusCompleted; - }); - - ProxyCompleted?.Invoke(originalPath, stored); - } - catch (OperationCanceledException) - { - delayMs = 3000; - DispatchInvoke(() => - { - progressItem.StatusMessage = Translate.ProxyGenerationStatusCanceled; - progressItem.IsFailed = true; - }); - } - catch (Exception ex) - { - delayMs = 8000; - var msg = ex.Message; - Debug.WriteLine(string.Concat("[ProxyForge] Proxy generation failed for ", originalPath, ": ", ex)); - DispatchInvoke(() => - { - progressItem.StatusMessage = string.Concat(Translate.ProxyGenerationStatusFailedPrefix, msg); - progressItem.IsFailed = true; - }); - } - finally - { - _pendingGenerations.TryRemove(key, out _); - cts.Dispose(); - } - - await Task.Delay(delayMs, CancellationToken.None).ConfigureAwait(false); - 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; - if (app is null) - return; - - if (app.Dispatcher.CheckAccess()) - action(); - else - app.Dispatcher.Invoke(action); - } - - internal void RemoveProxy(string originalPath, float scale) - { - var key = MakeKey(originalPath, scale); - if (_cache.TryRemove(key, out var entry)) - entry.Dispose(); - - _videoCache?.RemoveByPath(originalPath); - } - - internal (int count, long totalSize) ClearAll() - { - foreach (var kvp in _pendingGenerations) - { - if (_pendingGenerations.TryRemove(kvp.Key, out var removed)) - { - try { removed.Cancel(); removed.Dispose(); } - catch { } - } - } - - long totalSize = 0; - var count = 0; - foreach (var kvp in _cache) - { - if (_cache.TryRemove(kvp.Key, out var removed)) - { - totalSize += removed.DataSize; - removed.Dispose(); - count++; - } - } - - return (count, totalSize); - } - - internal CacheEntrySnapshot[] GetAllSnapshots() - { - var resultList = new List(); - - foreach (var entry in _cache.Values) - { - if (entry.IsValid) - resultList.Add(entry.CreateSnapshot()); - } - - if (_videoCache is not null && ProxyForgeSettings.Default.EnableVideoCache) - { - var dbEntries = _videoCache.GetAll(); - foreach (var db in dbEntries) - { - var alreadyInMemory = false; - foreach (var existing in resultList) - { - if (string.Equals(existing.OriginalPath, db.OriginalPath, StringComparison.OrdinalIgnoreCase) && - existing.Scale == db.Scale) - { - alreadyInMemory = true; - break; - } - } - if (!alreadyInMemory) - { - resultList.Add(new CacheEntrySnapshot( - db.OriginalPath, db.FileName, db.Scale, - db.ProxyWidth, db.ProxyHeight, - db.FileSize, db.CreatedAt, db.LastAccessedAt)); - } - } - } - - return resultList.Count > 0 ? [.. resultList] : []; - } - - internal (int entryCount, long totalSize) GetCacheInfo() - { - long totalSize = 0; - var count = 0; - foreach (var e in _cache.Values) - { - if (!e.IsValid) - continue; - - totalSize += e.DataSize; - count++; - } - return (count, totalSize); - } - - public void Dispose() - { - if (Interlocked.Exchange(ref _disposed, 1) != 0) - return; - - ClearAll(); - } - - private void PersistToVideoCache(string originalPath, float scale, ProxyCacheEntry entry) - { - if (_videoCache is null) - return; - - try - { - var uuid = Guid.NewGuid(); - var diskStore = _videoCache.DiskStore; - var destPath = diskStore.GetFilePath(uuid); - - var tmpPath = entry.GetCurrentDiskPath(); - if (tmpPath is not null && File.Exists(tmpPath) && IsTmpFile(tmpPath)) - { - File.Move(tmpPath, destPath, true); - entry.ReplaceDiskPath(destPath); - } - else - { - using var stream = entry.OpenReadStream(); - diskStore.SaveFromStream(uuid, stream); - } - - var fileCrc = diskStore.ComputeFileCrc32FromPath(destPath); - var fileSize = new FileInfo(destPath).Length; - - _videoCache.Add(originalPath, scale, entry.ProxyWidth, entry.ProxyHeight, - fileSize, fileCrc, uuid); - } - catch (Exception ex) - { - Debug.WriteLine(string.Concat("[ProxyCacheManager] PersistToVideoCache failed: ", ex.Message)); - } - } - - private bool IsTmpFile(string path) => - !string.IsNullOrEmpty(_tmpDirectory) && - path.StartsWith(_tmpDirectory, StringComparison.OrdinalIgnoreCase); -} \ No newline at end of file diff --git a/ProxyForge/Detection/ExportDetector.cs b/ProxyForge/Detection/ExportDetector.cs deleted file mode 100644 index 06d5f16..0000000 --- a/ProxyForge/Detection/ExportDetector.cs +++ /dev/null @@ -1,94 +0,0 @@ -using ProxyForge.Interfaces; -using System.Diagnostics; -using System.Runtime.InteropServices; -using YukkuriMovieMaker.Resources.Localization; - -namespace ProxyForge.Detection; - -internal sealed partial class ExportDetector : IExportDetector -{ - [LibraryImport("user32.dll")] - private static partial uint GetWindowThreadProcessId(nint hWnd, out uint lpdwProcessId); - - [DllImport("user32.dll", CharSet = CharSet.Unicode)] - private static extern int GetWindowText(nint hWnd, char[] lpString, int nMaxCount); - - [DllImport("user32.dll")] - [return: MarshalAs(UnmanagedType.Bool)] - private static extern bool EnumWindows(EnumWindowsProc enumProc, nint lParam); - - private delegate bool EnumWindowsProc(nint hWnd, nint lParam); - - [ThreadStatic] - private static bool t_found; - [ThreadStatic] - private static uint t_processId; - [ThreadStatic] - private static char[]? t_titleBuffer; - - private const int WindowTitleBufferSize = 512; - private const long CacheIntervalMs = 2000L; - private const long StateUnknown = 0L; - private const long StateFalse = 1L; - private const long StateTrue = 2L; - - private static readonly EnumWindowsProc s_enumWindowsCallback = EnumWindowsCallback; - - private long _packed; - - public bool IsExporting() - { - var nowMs = Environment.TickCount64; - var packed = Interlocked.Read(ref _packed); - var state = packed & 3L; - - if (state != StateUnknown && (nowMs - (packed >> 2)) < CacheIntervalMs) - return state == StateTrue; - - var result = CheckExportWindow(); - Interlocked.Exchange(ref _packed, (nowMs << 2) | (result ? StateTrue : StateFalse)); - return result; - } - - private static bool CheckExportWindow() - { - Debug.Assert( - SynchronizationContext.Current is null || !Thread.CurrentThread.IsThreadPoolThread, - "CheckExportWindow relies on ThreadStatic fields and must not be called from async continuations on thread pool threads."); - - try - { - t_processId = (uint)Environment.ProcessId; - t_found = false; - EnumWindows(s_enumWindowsCallback, nint.Zero); - return t_found; - } - catch - { - return false; - } - } - - private static bool EnumWindowsCallback(nint hWnd, nint _) - { - GetWindowThreadProcessId(hWnd, out var pid); - if (pid != t_processId) - return true; - - t_titleBuffer ??= new char[WindowTitleBufferSize]; - var len = GetWindowText(hWnd, t_titleBuffer, t_titleBuffer.Length); - if (len <= 0) - return true; - - var title = t_titleBuffer.AsSpan(0, len); - if (title.SequenceEqual(Texts.OutputProgressWindowTitle.AsSpan()) || - title.SequenceEqual(Texts.VideoExportWindowTitle.AsSpan())) - { - t_found = true; - return false; - } - return true; - } - - public void Reset() => Interlocked.Exchange(ref _packed, 0L); -} \ No newline at end of file diff --git a/ProxyForge/Directory.Build.props b/ProxyForge/Directory.Build.props deleted file mode 100644 index 8f6c269..0000000 --- a/ProxyForge/Directory.Build.props +++ /dev/null @@ -1,5 +0,0 @@ - - - C:\Program Files\YukkuriMovieMaker_v4_Lite_Dev\ - - \ No newline at end of file diff --git a/ProxyForge/Interfaces/IDialogService.cs b/ProxyForge/Interfaces/IDialogService.cs deleted file mode 100644 index ec4fef8..0000000 --- a/ProxyForge/Interfaces/IDialogService.cs +++ /dev/null @@ -1,6 +0,0 @@ -namespace ProxyForge.Interfaces; - -internal interface IDialogService -{ - void ShowInformation(string message, string title); -} \ No newline at end of file diff --git a/ProxyForge/Interfaces/IExportDetector.cs b/ProxyForge/Interfaces/IExportDetector.cs deleted file mode 100644 index 44dcb06..0000000 --- a/ProxyForge/Interfaces/IExportDetector.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace ProxyForge.Interfaces; - -internal interface IExportDetector -{ - bool IsExporting(); - void Reset(); -} \ No newline at end of file diff --git a/ProxyForge/Interfaces/IProxyEncoder.cs b/ProxyForge/Interfaces/IProxyEncoder.cs deleted file mode 100644 index a1f7a4e..0000000 --- a/ProxyForge/Interfaces/IProxyEncoder.cs +++ /dev/null @@ -1,11 +0,0 @@ -using ProxyForge.Core; -using ProxyForge.Progress; - -namespace ProxyForge.Interfaces; - -internal interface IProxyEncoder : IDisposable -{ - Task EncodeAsync( - string inputPath, float scale, float bitrateFactor, int gopSize, - ProxyGenerationItem? progressItem, CancellationToken cancellationToken); -} \ No newline at end of file diff --git a/ProxyForge/Interfaces/IProxyEncoderFactory.cs b/ProxyForge/Interfaces/IProxyEncoderFactory.cs deleted file mode 100644 index 1346706..0000000 --- a/ProxyForge/Interfaces/IProxyEncoderFactory.cs +++ /dev/null @@ -1,6 +0,0 @@ -namespace ProxyForge.Interfaces; - -internal interface IProxyEncoderFactory -{ - IProxyEncoder Create(); -} \ No newline at end of file diff --git a/ProxyForge/Interfaces/IVideoCacheDatabase.cs b/ProxyForge/Interfaces/IVideoCacheDatabase.cs deleted file mode 100644 index a21049c..0000000 --- a/ProxyForge/Interfaces/IVideoCacheDatabase.cs +++ /dev/null @@ -1,28 +0,0 @@ -namespace ProxyForge.Interfaces; - -internal interface IVideoCacheDatabase : IDisposable -{ - bool TryGet(string originalPath, float scale, out VideoCacheLookupResult result); - VideoCacheLookupResult[] GetAll(); - void Add(string originalPath, float scale, uint proxyWidth, uint proxyHeight, - long fileSize, uint fileCrc32, Guid uuid); - bool Remove(Guid uuid); - int RemoveByPath(string originalPath); - int ClearAll(); - void UpdateLastAccess(Guid uuid); - string GetCacheFilePath(Guid uuid); - string CacheDirectory { get; } -} - -internal readonly record struct VideoCacheLookupResult( - Guid Uuid, - string OriginalPath, - string FileName, - float Scale, - uint ProxyWidth, - uint ProxyHeight, - long FileSize, - uint FileCrc32, - DateTime CreatedAt, - DateTime LastAccessedAt -); \ No newline at end of file diff --git a/ProxyForge/Interfaces/IWindowThemeService.cs b/ProxyForge/Interfaces/IWindowThemeService.cs deleted file mode 100644 index 35b706f..0000000 --- a/ProxyForge/Interfaces/IWindowThemeService.cs +++ /dev/null @@ -1,8 +0,0 @@ -using System.Windows; - -namespace ProxyForge.Interfaces; - -internal interface IWindowThemeService -{ - void Bind(Window window); -} \ No newline at end of file diff --git a/ProxyForge/Localization/Texts.ar-sa.resx b/ProxyForge/Localization/Texts.ar-sa.resx deleted file mode 100644 index 85d4d4b..0000000 --- a/ProxyForge/Localization/Texts.ar-sa.resx +++ /dev/null @@ -1,114 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - -ar-sa -ProxyForge -إعدادات ProxyForge -القرص -جارٍ الإنشاء... -في الانتظار... -مكتمل -تم الإلغاء -فشل: -جارٍ التحميل... -لا توجد ذاكرة تخزين مؤقت للحذف. -تم حذف {0} عنصرًا ({1}). -لم تتم تهيئة المكوّن الإضافي -عدد عناصر التخزين المؤقت: {0} -القرص: {0} عنصر ({1}) -ProxyForge - جارٍ إنشاء الوكيل -جارٍ إنشاء فيديو وكيل... -لا توجد عناصر وكيل قيد الإنشاء. -تسريع التحرير باستخدام فيديوهات وكيلة منخفضة الدقة -الإعدادات الأساسية -اضبط السلوك الأساسي لفيديوهات الوكيل -استخدام الوكيل -استخدم فيديو وكيل منخفض الدقة أثناء التحرير.&#10;يتم التبديل تلقائيًا إلى الأصل عند التصدير. -مقياس الدقة -معامل مقياس الدقة لفيديو الوكيل -الحد الأدنى لحجم الملف -إنشاء وكيل فقط للفيديوهات الأكبر من هذا الحجم -إعدادات الجودة -اضبط التوازن بين جودة الترميز والأداء -معامل معدل البت -القيمة الأعلى تعطي جودة أفضل لكن حجم ملف أكبر -حجم GOP -الفاصل بين الإطارات المفتاحية -إعدادات الأتمتة -إنشاء تلقائي -مسح التخزين المؤقت عند الإنهاء -الإعدادات المتقدمة -تمكين الإعدادات المتقدمة -تسريع العتاد -إدارة التخزين المؤقت -تحديث المعلومات -مسح التخزين المؤقت -قائمة التخزين المؤقت -لا توجد ذاكرة تخزين مؤقت. -ذاكرة الفيديو المؤقتة -حفظ فيديوهات الوكيل على القرص لتقليل وقت البدء -تمكين ذاكرة الفيديو المؤقتة -حفظ فيديوهات الوكيل على القرص وتحميلها تلقائيًا.&#10;يلغي إعادة الإنشاء. -التخزين المؤقت الدائم: {0} عناصر ({1}) -قائمة التخزين المؤقت الدائم -لا يوجد تخزين مؤقت دائم. -مسح التخزين المؤقت الدائم -دائم - diff --git a/ProxyForge/Localization/Texts.cs b/ProxyForge/Localization/Texts.cs deleted file mode 100644 index 80ce855..0000000 --- a/ProxyForge/Localization/Texts.cs +++ /dev/null @@ -1,9 +0,0 @@ -using YukkuriMovieMaker.Generator; - -namespace ProxyForge.Localization; - -[AutoGenLocalizer] -partial class Translate -{ - -} \ No newline at end of file diff --git a/ProxyForge/Localization/Texts.csv b/ProxyForge/Localization/Texts.csv deleted file mode 100644 index d2f7f6c..0000000 --- a/ProxyForge/Localization/Texts.csv +++ /dev/null @@ -1,53 +0,0 @@ -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, -"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: , -"CacheSummaryLoading",Cache summary loading text,読み込み中...,Loading...,加载中...,載入中...,불러오는 중...,Cargando...,جارٍ التحميل...,Memuat..., -"CacheNoEntriesToDelete",No cache entries to delete message,削除するキャッシュがありません。,There is no cache to delete.,没有可删除的缓存。,沒有可刪除的快取。,삭제할 캐시가 없습니다.,No hay caché para eliminar.,لا توجد ذاكرة تخزين مؤقت للحذف.,Tidak ada cache untuk dihapus., -"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, -"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 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 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, -"SettingMinFileSizeTooltip",Minimum file size setting tooltip,このサイズ以上の動画のみプロキシを生成します,Generate proxy only for videos larger than this size,仅为大于此大小的视频生成代理,僅為大於此大小的影片產生代理,이 크기 이상의 영상만 프록시를 생성합니다,Solo genera proxy para videos mayores que este tamaño,إنشاء وكيل فقط للفيديوهات الأكبر من هذا الحجم,Buat proksi hanya untuk video yang lebih besar dari ukuran ini, -"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 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, -"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, -"SectionAdvancedSettingsHeader",Advanced settings section header,詳細設定,Advanced Settings,高级设置,進階設定,고급 설정,Configuración avanzada,الإعدادات المتقدمة,Pengaturan Lanjutan, -"SettingEnableAdvancedLabel",Enable advanced settings label,詳細設定を有効にする,Enable Advanced Settings,启用高级设置,啟用進階設定,고급 설정 활성화,Habilitar configuración avanzada,تمكين الإعدادات المتقدمة,Aktifkan Pengaturan Lanjutan, -"SettingHardwareAccelerationLabel",Hardware acceleration setting label,ハードウェアアクセラレーション,Hardware Acceleration,硬件加速,硬體加速,하드웨어 가속,Aceleración por hardware,تسريع العتاد,Akselerasi Perangkat Keras, -"SectionCacheManagementHeader",Cache management section header,キャッシュ管理,Cache Management,缓存管理,快取管理,캐시 관리,Gestión de caché,إدارة التخزين المؤقت,Manajemen Cache, -"ButtonRefreshInfo",Refresh info button label,情報を更新,Refresh Info,刷新信息,更新資訊,정보 새로고침,Actualizar información,تحديث المعلومات,Perbarui Info, -"ButtonClearCache",Clear cache button label,キャッシュをクリア,Clear Cache,清除缓存,清除快取,캐시 지우기,Borrar caché,مسح التخزين المؤقت,Hapus Cache, -"CacheListHeader",Cache list header,キャッシュ一覧,Cache List,缓存列表,快取清單,캐시 목록,Lista de caché,قائمة التخزين المؤقت,Daftar Cache, -"CacheListEmpty",Empty cache list message,キャッシュはありません,There is no cache.,没有缓存。,沒有快取。,캐시가 없습니다.,No hay caché.,لا توجد ذاكرة تخزين مؤقت.,Tidak ada cache., -"SectionVideoCacheHeader",Video cache section header,映像キャッシュ,Video Cache,视频缓存,影片快取,영상 캐시,Caché de video,ذاكرة الفيديو المؤقتة,Cache Video, -"SectionVideoCacheDescription",Video cache section description,プロキシ動画をディスクに永続保存し起動時間を短縮します,Persist proxy videos to disk to reduce startup time,将代理视频持久保存到磁盘以缩短启动时间,將代理影片永久保存到磁碟以縮短啟動時間,프록시 영상을 디스크에 영구 저장하여 시작 시간을 단축합니다,Guarda videos proxy en disco para reducir el tiempo de inicio,حفظ فيديوهات الوكيل على القرص لتقليل وقت البدء,Simpan video proksi ke disk untuk mengurangi waktu startup, -"SettingEnableVideoCacheLabel",Enable video cache label,映像キャッシュを有効にする,Enable Video Cache,启用视频缓存,啟用影片快取,영상 캐시 활성화,Habilitar caché de video,تمكين ذاكرة الفيديو المؤقتة,Aktifkan Cache Video, -"SettingEnableVideoCacheTooltip",Enable video cache tooltip,プロキシ動画をディスクに保存し次回起動時に自動ロードします。 生成の手間を省きます。,Save proxy videos to disk and auto-load on next startup. Eliminates regeneration overhead.,将代理视频保存到磁盘并在下次启动时自动加载。 免去重新生成。,將代理影片儲存到磁碟並在下次啟動時自動載入。 免去重新產生。,프록시 영상을 디스크에 저장하고 다음 시작 시 자동 로드합니다. 재생성을 생략합니다.,Guarda videos proxy en disco y los carga automáticamente. Elimina la regeneración.,حفظ فيديوهات الوكيل على القرص وتحميلها تلقائيًا. يلغي إعادة الإنشاء.,Simpan video proksi ke disk dan muat otomatis saat startup berikutnya. Menghilangkan regenerasi., -"VideoCacheSummaryFormat",Video cache summary format,永続キャッシュ: {0} 件 ({1}),Persistent cache: {0} items ({1}),持久缓存: {0} 项({1}),永久快取: {0} 項({1}),영구 캐시: {0}개({1}),Caché persistente: {0} elementos ({1}),التخزين المؤقت الدائم: {0} عناصر ({1}),Cache persisten: {0} item ({1}), -"VideoCacheListHeader",Video cache list header,永続キャッシュ一覧,Persistent Cache List,持久缓存列表,永久快取清單,영구 캐시 목록,Lista de caché persistente,قائمة التخزين المؤقت الدائم,Daftar Cache Persisten, -"VideoCacheListEmpty",Video cache list empty message,永続キャッシュはありません,No persistent cache entries.,没有持久缓存。,沒有永久快取。,영구 캐시가 없습니다.,No hay caché persistente.,لا يوجد تخزين مؤقت دائم.,Tidak ada cache persisten., -"ButtonClearVideoCache",Clear video cache button label,永続キャッシュをクリア,Clear Persistent Cache,清除持久缓存,清除永久快取,영구 캐시 지우기,Borrar caché persistente,مسح التخزين المؤقت الدائم,Hapus Cache Persisten, -"StoragePersistent",Storage type persistent,永続,Persistent,持久,永久,영구,Persistente,دائم,Persisten, \ No newline at end of file diff --git a/ProxyForge/Localization/Texts.en-us.resx b/ProxyForge/Localization/Texts.en-us.resx deleted file mode 100644 index b974d16..0000000 --- a/ProxyForge/Localization/Texts.en-us.resx +++ /dev/null @@ -1,114 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - -en-us -ProxyForge -ProxyForge Settings -Disk -Generating... -Queued... -Completed -Canceled -Failed: -Loading... -There is no cache to delete. -Deleted {0} items ({1}). -Plugin not initialized -Cache count: {0} items -Disk: {0} items ({1}) -ProxyForge - Generating Proxy -Generating proxy video... -There are no proxies being generated. -Speed up editing with low-resolution proxy videos -Basic Settings -Configure the basic behavior of proxy videos -Use proxy -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 -Generate proxy only for videos larger than this size -Quality Settings -Adjust the balance between encoding quality and performance -Bitrate Factor -Higher value gives better quality but a larger file -GOP Size -Keyframe interval -Automation Settings -Auto Generate -Clear Cache on Exit -Advanced Settings -Enable Advanced Settings -Hardware Acceleration -Cache Management -Refresh Info -Clear Cache -Cache List -There is no cache. -Video Cache -Persist proxy videos to disk to reduce startup time -Enable Video Cache -Save proxy videos to disk and auto-load on next startup.&#10;Eliminates regeneration overhead. -Persistent cache: {0} items ({1}) -Persistent Cache List -No persistent cache entries. -Clear Persistent Cache -Persistent - diff --git a/ProxyForge/Localization/Texts.es-es.resx b/ProxyForge/Localization/Texts.es-es.resx deleted file mode 100644 index 149c63d..0000000 --- a/ProxyForge/Localization/Texts.es-es.resx +++ /dev/null @@ -1,114 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - -es-es -ProxyForge -Configuración de ProxyForge -Disco -Generando... -En cola... -Completado -Cancelado -Error: -Cargando... -No hay caché para eliminar. -Se eliminaron {0} elementos ({1}). -Plugin no inicializado -Conteo de caché: {0} elementos -Disco: {0} elementos ({1}) -ProxyForge - Generando proxy -Generando video proxy... -No hay proxies en generación. -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 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 -Solo genera proxy para videos mayores que este tamaño -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 tamaño del archivo -Tamaño GOP -Intervalo de fotogramas clave -Configuración de automatización -Generación automática -Borrar caché al salir -Configuración avanzada -Habilitar configuración avanzada -Aceleración por hardware -Gestión de caché -Actualizar información -Borrar caché -Lista de caché -No hay caché. -Caché de video -Guarda videos proxy en disco para reducir el tiempo de inicio -Habilitar caché de video -Guarda videos proxy en disco y los carga automáticamente.&#10;Elimina la regeneración. -Caché persistente: {0} elementos ({1}) -Lista de caché persistente -No hay caché persistente. -Borrar caché persistente -Persistente - diff --git a/ProxyForge/Localization/Texts.id-id.resx b/ProxyForge/Localization/Texts.id-id.resx deleted file mode 100644 index 50f991a..0000000 --- a/ProxyForge/Localization/Texts.id-id.resx +++ /dev/null @@ -1,114 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - -id-id -ProxyForge -Pengaturan ProxyForge -Disk -Sedang membuat... -Menunggu... -Selesai -Dibatalkan -Gagal: -Memuat... -Tidak ada cache untuk dihapus. -{0} item ({1}) telah dihapus. -Plugin belum diinisialisasi -Jumlah cache: {0} item -Disk: {0} item ({1}) -ProxyForge - Sedang Membuat Proksi -Sedang membuat video proksi... -Tidak ada proksi yang sedang dibuat. -Tingkatkan kecepatan edit dengan video proksi resolusi rendah -Pengaturan Dasar -Atur perilaku dasar video proksi -Gunakan proksi -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 -Buat proksi hanya untuk video yang lebih besar dari ukuran ini -Pengaturan Kualitas -Sesuaikan keseimbangan antara kualitas encoding dan performa -Faktor Bitrate -Nilai lebih tinggi memberi kualitas lebih baik tetapi ukuran file lebih besar -Ukuran GOP -Interval keyframe -Pengaturan Otomatisasi -Buat Otomatis -Hapus Cache saat Keluar -Pengaturan Lanjutan -Aktifkan Pengaturan Lanjutan -Akselerasi Perangkat Keras -Manajemen Cache -Perbarui Info -Hapus Cache -Daftar Cache -Tidak ada cache. -Cache Video -Simpan video proksi ke disk untuk mengurangi waktu startup -Aktifkan Cache Video -Simpan video proksi ke disk dan muat otomatis saat startup berikutnya.&#10;Menghilangkan regenerasi. -Cache persisten: {0} item ({1}) -Daftar Cache Persisten -Tidak ada cache persisten. -Hapus Cache Persisten -Persisten - diff --git a/ProxyForge/Localization/Texts.ko-kr.resx b/ProxyForge/Localization/Texts.ko-kr.resx deleted file mode 100644 index d2d41d4..0000000 --- a/ProxyForge/Localization/Texts.ko-kr.resx +++ /dev/null @@ -1,114 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - -ko-kr -ProxyForge -ProxyForge 설정 -디스크 -생성 중... -대기 중... -완료 -취소됨 -실패: -불러오는 중... -삭제할 캐시가 없습니다. -{0}개 항목({1})을 삭제했습니다. -플러그인이 초기화되지 않음 -캐시 수: {0}개 -디스크: {0}개({1}) -ProxyForge - 프록시 생성 중 -프록시 영상을 생성하는 중... -생성 중인 프록시가 없습니다. -저해상도 프록시 영상으로 편집 속도 향상 -기본 설정 -프록시 영상의 기본 동작을 설정합니다 -프록시 사용 -편집 중에는 저해상도 프록시 영상을 사용합니다.&#10;내보낼 때는 원본으로 자동 전환됩니다. -해상도 배율 -프록시 영상의 해상도 배율 -최소 파일 크기 -이 크기 이상의 영상만 프록시를 생성합니다 -품질 설정 -인코딩 품질과 성능의 균형을 조정합니다 -비트레이트 계수 -값이 높을수록 품질은 좋아지지만 파일이 커집니다 -GOP 크기 -키프레임 간격 -자동화 설정 -자동 생성 -종료 시 캐시 지우기 -고급 설정 -고급 설정 활성화 -하드웨어 가속 -캐시 관리 -정보 새로고침 -캐시 지우기 -캐시 목록 -캐시가 없습니다. -영상 캐시 -프록시 영상을 디스크에 영구 저장하여 시작 시간을 단축합니다 -영상 캐시 활성화 -프록시 영상을 디스크에 저장하고 다음 시작 시 자동 로드합니다.&#10;재생성을 생략합니다. -영구 캐시: {0}개({1}) -영구 캐시 목록 -영구 캐시가 없습니다. -영구 캐시 지우기 -영구 - diff --git a/ProxyForge/Localization/Texts.resx b/ProxyForge/Localization/Texts.resx deleted file mode 100644 index 7ea69f8..0000000 --- a/ProxyForge/Localization/Texts.resx +++ /dev/null @@ -1,114 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - -ja-jp -ProxyForge -ProxyForge 設定 -ディスク -生成中... -待機中... -完了 -キャンセル -失敗: -読み込み中... -削除するキャッシュがありません。 -{0} 件 ({1}) を削除しました。 -プラグイン未初期化 -キャッシュ数: {0} 件 -ディスク: {0} 件 ({1}) -ProxyForge - プロキシ生成中 -プロキシ動画を生成しています... -生成中のプロキシはありません -低解像度のプロキシ動画で編集を高速化 -基本設定 -プロキシ動画の基本的な動作を設定します -プロキシを使用する -編集中に低解像度のプロキシ動画を使用します。&#10;出力時は自動でオリジナルに切り替わります。 -解像度スケール -プロキシ動画の解像度倍率 -最小ファイルサイズ -このサイズ以上の動画のみプロキシを生成します -品質設定 -エンコード品質とパフォーマンスのバランスを調整します -ビットレート係数 -高いほど高品質ですがファイルサイズが増えます -GOPサイズ -キーフレーム間隔 -自動化設定 -自動生成 -終了時にキャッシュクリア -詳細設定 -詳細設定を有効にする -ハードウェアアクセラレーション -キャッシュ管理 -情報を更新 -キャッシュをクリア -キャッシュ一覧 -キャッシュはありません -映像キャッシュ -プロキシ動画をディスクに永続保存し起動時間を短縮します -映像キャッシュを有効にする -プロキシ動画をディスクに保存し次回起動時に自動ロードします。&#10;生成の手間を省きます。 -永続キャッシュ: {0} 件 ({1}) -永続キャッシュ一覧 -永続キャッシュはありません -永続キャッシュをクリア -永続 - diff --git a/ProxyForge/Localization/Texts.zh-cn.resx b/ProxyForge/Localization/Texts.zh-cn.resx deleted file mode 100644 index a7caa65..0000000 --- a/ProxyForge/Localization/Texts.zh-cn.resx +++ /dev/null @@ -1,114 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - -zh-cn -ProxyForge -ProxyForge 设置 -磁盘 -正在生成... -排队中... -完成 -已取消 -失败: -加载中... -没有可删除的缓存。 -已删除 {0} 项({1})。 -插件未初始化 -缓存数: {0} 项 -磁盘: {0} 项({1}) -ProxyForge - 正在生成代理 -正在生成代理视频... -当前没有正在生成的代理。 -通过低分辨率代理视频加速编辑 -基本设置 -设置代理视频的基本行为 -使用代理 -编辑时使用低分辨率代理视频。&#10;导出时自动切换为原始视频。 -分辨率缩放 -代理视频的分辨率倍率 -最小文件大小 -仅为大于此大小的视频生成代理 -质量设置 -调整编码质量与性能之间的平衡 -比特率系数 -值越高画质越好但文件越大 -GOP 大小 -关键帧间隔 -自动化设置 -自动生成 -退出时清除缓存 -高级设置 -启用高级设置 -硬件加速 -缓存管理 -刷新信息 -清除缓存 -缓存列表 -没有缓存。 -视频缓存 -将代理视频持久保存到磁盘以缩短启动时间 -启用视频缓存 -将代理视频保存到磁盘并在下次启动时自动加载。&#10;免去重新生成。 -持久缓存: {0} 项({1}) -持久缓存列表 -没有持久缓存。 -清除持久缓存 -持久 - diff --git a/ProxyForge/Localization/Texts.zh-tw.resx b/ProxyForge/Localization/Texts.zh-tw.resx deleted file mode 100644 index 1d15d8c..0000000 --- a/ProxyForge/Localization/Texts.zh-tw.resx +++ /dev/null @@ -1,114 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - -zh-tw -ProxyForge -ProxyForge 設定 -磁碟 -正在產生... -佇列中... -完成 -已取消 -失敗: -載入中... -沒有可刪除的快取。 -已刪除 {0} 項({1})。 -外掛未初始化 -快取數: {0} 項 -磁碟: {0} 項({1}) -ProxyForge - 正在產生代理 -正在產生代理影片... -目前沒有正在產生的代理。 -透過低解析度代理影片加速編輯 -基本設定 -設定代理影片的基本行為 -使用代理 -編輯時使用低解析度代理影片。&#10;輸出時會自動切換為原始影片。 -解析度縮放 -代理影片的解析度倍率 -最小檔案大小 -僅為大於此大小的影片產生代理 -品質設定 -調整編碼品質與效能之間的平衡 -位元率係數 -值越高畫質越好但檔案越大 -GOP 大小 -關鍵影格間隔 -自動化設定 -自動產生 -結束時清除快取 -進階設定 -啟用進階設定 -硬體加速 -快取管理 -更新資訊 -清除快取 -快取清單 -沒有快取。 -影片快取 -將代理影片永久保存到磁碟以縮短啟動時間 -啟用影片快取 -將代理影片儲存到磁碟並在下次啟動時自動載入。&#10;免去重新產生。 -永久快取: {0} 項({1}) -永久快取清單 -沒有永久快取。 -清除永久快取 -永久 - diff --git a/ProxyForge/Memory/BufferPool.cs b/ProxyForge/Memory/BufferPool.cs deleted file mode 100644 index c565ba6..0000000 --- a/ProxyForge/Memory/BufferPool.cs +++ /dev/null @@ -1,15 +0,0 @@ -using System.Buffers; - -namespace ProxyForge.Memory; - -internal static class BufferPool -{ - private const int MaxPoolableSize = 1024 * 1024; - internal static byte[] Rent(int minimumLength) => ArrayPool.Shared.Rent(minimumLength); - - internal static void Return(byte[] buffer, bool clearArray = false) - { - if (buffer.Length <= MaxPoolableSize) - ArrayPool.Shared.Return(buffer, clearArray); - } -} diff --git a/ProxyForge/Plugin/PluginHost.cs b/ProxyForge/Plugin/PluginHost.cs deleted file mode 100644 index 99b807b..0000000 --- a/ProxyForge/Plugin/PluginHost.cs +++ /dev/null @@ -1,171 +0,0 @@ -using ProxyForge.Cache; -using ProxyForge.Core; -using ProxyForge.Detection; -using ProxyForge.Interfaces; -using ProxyForge.Services; -using ProxyForge.Settings; -using ProxyForge.ViewModels; -using ProxyForge.Views; -using System.IO; -using System.Windows; -using System.Windows.Interop; -using YukkuriMovieMaker.Commons; - -namespace ProxyForge.Plugin; - -internal sealed class PluginHost : IDisposable -{ - private static PluginHost? _instance; - private static readonly object Lock = new(); - private int _disposed; - private GenerationPopupView? _popupView; - - internal static PluginHost? Instance => _instance; - internal ProxyCacheManager CacheManager { get; } - internal IExportDetector ExportDetector { get; } - internal string FallbackDirectory { get; } - internal string TmpDirectory { get; } - internal VideoCacheDatabase? VideoCache { get; } - - private PluginHost( - IProxyEncoderFactory encoderFactory, - IExportDetector exportDetector, - string fallbackDirectory, - string tmpDirectory, - VideoCacheDatabase? videoCache) - { - ExportDetector = exportDetector; - FallbackDirectory = fallbackDirectory; - TmpDirectory = tmpDirectory; - VideoCache = videoCache; - CacheManager = new ProxyCacheManager(encoderFactory, videoCache, tmpDirectory); - - CacheManager.ActiveGenerations.CollectionChanged += OnGenerationsChanged; - } - - private static PluginHost CreateDefault() - { - var settings = ProxyForgeSettings.Default; - var pluginDir = Path.GetDirectoryName(typeof(PluginHost).Assembly.Location) ?? AppDirectories.TemporaryDirectory; - var cacheDir = Path.Combine(pluginDir, "cache"); - var tmpDirectory = Path.Combine(cacheDir, "tmp"); - - WindowThemeRegistry.Register(new WindowThemeService()); - - IProxyEncoderFactory encoderFactory = new FFmpegProxyEncoderFactory( - tmpDirectory, - static () => new EncoderConfig(ProxyForgeSettings.Default.EnableHardwareAcceleration)); - - VideoCacheDatabase? videoCache = null; - if (settings.EnableVideoCache) - { - try - { - videoCache = new VideoCacheDatabase(cacheDir); - } - catch { } - } - - IExportDetector exportDetector = new ExportDetector(); - return new PluginHost(encoderFactory, exportDetector, tmpDirectory, tmpDirectory, videoCache); - } - - internal static PluginHost EnsureInitialized() - { - if (_instance is not null) - return _instance; - - lock (Lock) - { - _instance ??= CreateDefault(); - } - - return _instance; - } - - internal static void TearDown() - { - lock (Lock) - { - if (_instance is null) - return; - - _instance.Dispose(); - _instance = null; - } - } - - private void OnGenerationsChanged(object? sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e) - { - Application.Current?.Dispatcher.BeginInvoke(() => - { - if (CacheManager.ActiveGenerations.Count > 0) - EnsurePopupVisible(); - else - _popupView?.Hide(); - }); - } - - private void EnsurePopupVisible() - { - if (_popupView is null) - { - var vm = new GenerationPopupViewModel(CacheManager.ActiveGenerations); - _popupView = new GenerationPopupView(vm); - WindowThemeRegistry.Bind(_popupView); - - var mainWindow = Application.Current?.MainWindow; - if (mainWindow is { IsLoaded: true }) - { - try - { - _popupView.Owner = mainWindow; - } - catch - { - var helper = new WindowInteropHelper(_popupView); - var mainHelper = new WindowInteropHelper(mainWindow); - if (mainHelper.Handle != nint.Zero) - helper.Owner = mainHelper.Handle; - } - } - } - - if (!_popupView.IsVisible) - _popupView.Show(); - } - - public void Dispose() - { - if (Interlocked.Exchange(ref _disposed, 1) != 0) - return; - - CacheManager.ActiveGenerations.CollectionChanged -= OnGenerationsChanged; - - Application.Current?.Dispatcher.Invoke(() => - { - _popupView?.ForceClose(); - _popupView = null; - }); - - CacheManager.Dispose(); - VideoCache?.Dispose(); - CleanupTmpDirectory(); - } - - private void CleanupTmpDirectory() - { - try - { - if (!Directory.Exists(TmpDirectory)) - return; - - foreach (var file in Directory.GetFiles(TmpDirectory)) - { - try { File.Delete(file); } - catch { } - } - } - catch { } - } -} \ No newline at end of file diff --git a/ProxyForge/Plugin/ProxyForgePlugin.cs b/ProxyForge/Plugin/ProxyForgePlugin.cs deleted file mode 100644 index 35c48b8..0000000 --- a/ProxyForge/Plugin/ProxyForgePlugin.cs +++ /dev/null @@ -1,146 +0,0 @@ -using ProxyForge.Core; -using ProxyForge.Settings; -using System.Diagnostics; -using System.IO; -using System.Windows; -using YukkuriMovieMaker.Commons; -using YukkuriMovieMaker.Plugin; -using YukkuriMovieMaker.Plugin.FileSource; - -namespace ProxyForge.Plugin; - -internal sealed class ProxyForgePlugin : IVideoFileSourcePlugin -{ - public string Name => "ProxyForge"; - - public ProxyForgePlugin() - { - PluginHost.EnsureInitialized(); - if (Application.Current is not null) - Application.Current.Exit += OnApplicationExit; - } - - public IVideoFileSource? CreateVideoFileSource(IGraphicsDevicesAndContext devices, string filePath) - { - try - { - return CreateCore(devices, filePath); - } - catch (Exception ex) - { - Debug.WriteLine(string.Concat("[ProxyForge] CreateCore failed for ", filePath, ": ", ex.Message)); - return null; - } - } - - private static IVideoFileSource? CreateCore(IGraphicsDevicesAndContext devices, string filePath) - { - var host = PluginHost.Instance; - if (host is null) - return null; - - var settings = ProxyForgeSettings.Default; - if (!settings.UseProxy && !settings.AutoGenerate) - return null; - - if (host.ExportDetector.IsExporting()) - return null; - - if (!IsLargeEnough(filePath, settings.MinFileSizeForProxy)) - return null; - - var proxyScale = settings.Scale / 100f; - - if (settings.UseProxy) - { - var cached = host.CacheManager.TryGetProxy(filePath, proxyScale); - if (cached is { IsValid: true }) - return LoadFromCache(devices, cached); - - var initialSource = LoadRaw(devices, filePath); - if (initialSource is null) - return null; - - var generationStarted = 0; - return new ProxyForgeVideoSource(initialSource, devices, - () => - { - if (Interlocked.Exchange(ref generationStarted, 1) == 0) - host.CacheManager.StartProxyGeneration(filePath, proxyScale, settings); - return TryLoadProxy(devices, filePath, proxyScale, host); - }); - } - - if (settings.AutoGenerate) - { - if (!host.CacheManager.ProxyExists(filePath, proxyScale)) - host.CacheManager.StartProxyGeneration(filePath, proxyScale, settings); - - return null; - } - - return null; - } - - private static IVideoFileSource? LoadFromCache( - IGraphicsDevicesAndContext devices, ProxyCacheEntry entry) - { - try - { - var source = LoadRaw(devices, entry.GetFilePath()); - if (source is null) - return null; - - return entry.Scale < 0.99f - ? new ProxyForgeVideoSourceWithScale(source, devices, entry.Scale) - : new ProxyForgeVideoSource(source, devices); - } - catch (Exception ex) - { - Debug.WriteLine(string.Concat("[ProxyForge] LoadFromCache failed: ", 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) - { - var cached = host.CacheManager.TryGetProxy(filePath, proxyScale); - if (cached is null || !cached.IsValid) - return null; - - var source = LoadFromCache(devices, cached); - if (source is null) - host.CacheManager.RemoveProxy(filePath, proxyScale); - - return source; - } - - private static bool IsLargeEnough(string filePath, int minSizeMb) - { - try - { - var info = new FileInfo(filePath); - return info.Exists && info.Length >= (long)minSizeMb * 1048576L; - } - catch - { - return false; - } - } - - private static void OnApplicationExit(object? sender, ExitEventArgs e) - { - try - { - if (ProxyForgeSettings.Default.ClearCacheOnExit) - PluginHost.Instance?.CacheManager.ClearAll(); - - PluginHost.TearDown(); - } - catch { } - } -} \ No newline at end of file diff --git a/ProxyForge/Plugin/ProxyForgeVideoSource.cs b/ProxyForge/Plugin/ProxyForgeVideoSource.cs deleted file mode 100644 index 092dfde..0000000 --- a/ProxyForge/Plugin/ProxyForgeVideoSource.cs +++ /dev/null @@ -1,150 +0,0 @@ -using System.Diagnostics; -using System.Numerics; -using Vortice.Direct2D1; -using Vortice.Direct2D1.Effects; -using YukkuriMovieMaker.Commons; -using YukkuriMovieMaker.Plugin.FileSource; - -namespace ProxyForge.Plugin; - -internal sealed class ProxyForgeVideoSource : IVideoFileSource -{ - private IVideoFileSource _inner; - private Func? _tryUpgradeSource; - private readonly AffineTransform2D _switchEffect; - private readonly ID2D1Image _output; - private readonly object _gate = new(); - private volatile bool _upgraded; - private volatile IVideoFileSource? _pendingUpgrade; - private int _upgradeFetching; - private long _nextUpgradeAttemptTicks; - private int _disposed; - - public TimeSpan Duration - { - get - { - lock (_gate) - return _inner.Duration; - } - } - - public ID2D1Image Output => _output; - - internal ProxyForgeVideoSource(IVideoFileSource inner, IGraphicsDevicesAndContext devices) - { - _inner = inner; - _switchEffect = new AffineTransform2D(devices.DeviceContext); - _switchEffect.SetInput(0, inner.Output, true); - _switchEffect.TransformMatrix = Matrix3x2.Identity; - _output = _switchEffect.Output; - } - - internal ProxyForgeVideoSource(IVideoFileSource inner, IGraphicsDevicesAndContext devices, Func tryUpgradeSource) - { - _inner = inner; - _switchEffect = new AffineTransform2D(devices.DeviceContext); - _switchEffect.SetInput(0, inner.Output, true); - _switchEffect.TransformMatrix = Matrix3x2.Identity; - _output = _switchEffect.Output; - _tryUpgradeSource = tryUpgradeSource; - } - - public void Update(TimeSpan time) - { - if (!_upgraded && _tryUpgradeSource is not null) - TryApplyUpgrade(); - - if (_upgraded) - { - if (Volatile.Read(ref _disposed) == 0) - _inner.Update(time); - return; - } - - lock (_gate) - { - if (Volatile.Read(ref _disposed) == 0) - _inner.Update(time); - } - } - - private void TryApplyUpgrade() - { - var pending = _pendingUpgrade; - if (pending is not null) - { - _pendingUpgrade = null; - lock (_gate) - { - if (!_upgraded && Volatile.Read(ref _disposed) == 0) - { - var old = _inner; - _inner = pending; - _switchEffect.SetInput(0, pending.Output, true); - _upgraded = true; - _tryUpgradeSource = null; - old.Dispose(); - } - else - { - pending.Dispose(); - } - } - } - else - { - var now = Stopwatch.GetTimestamp(); - if (now >= Volatile.Read(ref _nextUpgradeAttemptTicks) && - Interlocked.Exchange(ref _upgradeFetching, 1) == 0) - { - Volatile.Write(ref _nextUpgradeAttemptTicks, now + Stopwatch.Frequency / 2); - ThreadPool.UnsafeQueueUserWorkItem(static s => s.FetchUpgradeAsync(), this, preferLocal: false); - } - } - } - - private void FetchUpgradeAsync() - { - try - { - var upgraded = _tryUpgradeSource!(); - if (upgraded is not null) - _pendingUpgrade = upgraded; - } - catch { } - finally - { - Volatile.Write(ref _upgradeFetching, 0); - } - } - - public int GetFrameIndex(TimeSpan time) - { - lock (_gate) - return _inner.GetFrameIndex(time); - } - - public void Dispose() - { - if (Interlocked.Exchange(ref _disposed, 1) != 0) - return; - - lock (_gate) - { - _output.Dispose(); - _switchEffect.SetInput(0, null, true); - _switchEffect.Dispose(); - _inner.Dispose(); - } - - var orphan = _pendingUpgrade; - if (orphan is not null) - { - _pendingUpgrade = null; - orphan.Dispose(); - } - - GC.SuppressFinalize(this); - } -} \ No newline at end of file diff --git a/ProxyForge/Plugin/ProxyForgeVideoSourceWithScale.cs b/ProxyForge/Plugin/ProxyForgeVideoSourceWithScale.cs deleted file mode 100644 index b2059dd..0000000 --- a/ProxyForge/Plugin/ProxyForgeVideoSourceWithScale.cs +++ /dev/null @@ -1,42 +0,0 @@ -using System.Numerics; -using Vortice.Direct2D1; -using Vortice.Direct2D1.Effects; -using YukkuriMovieMaker.Commons; -using YukkuriMovieMaker.Plugin.FileSource; - -namespace ProxyForge.Plugin; - -internal sealed class ProxyForgeVideoSourceWithScale : IVideoFileSource -{ - private readonly IVideoFileSource _inner; - private readonly AffineTransform2D _scaleEffect; - private readonly ID2D1Image _output; - private int _disposed; - - public TimeSpan Duration => _inner.Duration; - public ID2D1Image Output => _output; - - internal ProxyForgeVideoSourceWithScale(IVideoFileSource inner, IGraphicsDevicesAndContext devices, float proxyScale) - { - _inner = inner; - _scaleEffect = new AffineTransform2D(devices.DeviceContext); - _scaleEffect.SetInput(0, inner.Output, true); - _scaleEffect.TransformMatrix = Matrix3x2.CreateScale(1f / proxyScale); - _output = _scaleEffect.Output; - } - - public void Update(TimeSpan time) => _inner.Update(time); - public int GetFrameIndex(TimeSpan time) => _inner.GetFrameIndex(time); - - public void Dispose() - { - if (Interlocked.Exchange(ref _disposed, 1) != 0) - return; - - _output.Dispose(); - _scaleEffect.SetInput(0, null, true); - _scaleEffect.Dispose(); - _inner.Dispose(); - GC.SuppressFinalize(this); - } -} \ No newline at end of file diff --git a/ProxyForge/Plugin/Ymm4VideoSourceLoader.cs b/ProxyForge/Plugin/Ymm4VideoSourceLoader.cs deleted file mode 100644 index b8c66d6..0000000 --- a/ProxyForge/Plugin/Ymm4VideoSourceLoader.cs +++ /dev/null @@ -1,35 +0,0 @@ -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 deleted file mode 100644 index 8d724f0..0000000 --- a/ProxyForge/Progress/ProxyGenerationItem.cs +++ /dev/null @@ -1,73 +0,0 @@ -using ProxyForge.Localization; -using YukkuriMovieMaker.Commons; - -namespace ProxyForge.Progress; - -public sealed class ProxyGenerationItem : Bindable -{ - public string FileName { get; } - public string OriginalPath { get; } - public DateTime StartedAt { get; } = DateTime.Now; - - private long _pendingProgressBits; - - private double _progress; - public double Progress - { - get => _progress; - set - { - if (Set(ref _progress, value)) - { - OnPropertyChanged(nameof(ProgressText)); - OnPropertyChanged(nameof(ElapsedText)); - } - } - } - - public string ProgressText => string.Create(null, stackalloc char[16], $"{Progress:F1}%"); - - public string ElapsedText - { - get - { - var elapsed = DateTime.Now - StartedAt; - return elapsed.TotalMinutes >= 1 - ? string.Create(null, stackalloc char[16], $"{(int)elapsed.TotalMinutes}m{elapsed.Seconds}s") - : string.Create(null, stackalloc char[8], $"{elapsed.Seconds}s"); - } - } - - private bool _isCompleted; - public bool IsCompleted - { - get => _isCompleted; - set => Set(ref _isCompleted, value); - } - - private bool _isFailed; - public bool IsFailed - { - get => _isFailed; - set => Set(ref _isFailed, value); - } - - private string _statusMessage = Translate.ProxyGenerationStatusGenerating; - public string StatusMessage - { - get => _statusMessage; - set => Set(ref _statusMessage, value); - } - - internal ProxyGenerationItem(string originalPath) - { - OriginalPath = originalPath; - FileName = System.IO.Path.GetFileName(originalPath); - } - - internal void SetPendingProgress(double value) => - Interlocked.Exchange(ref _pendingProgressBits, BitConverter.DoubleToInt64Bits(value)); - - internal void ApplyPendingProgress() => - Progress = BitConverter.Int64BitsToDouble(Interlocked.Read(ref _pendingProgressBits)); -} \ No newline at end of file diff --git a/ProxyForge/Properties/launchSettings.json b/ProxyForge/Properties/launchSettings.json deleted file mode 100644 index 6ceb197..0000000 --- a/ProxyForge/Properties/launchSettings.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "profiles": { - "ZeroDiskProxy": { - "commandName": "Project" - }, - "YMM4": { - "commandName": "Executable", - "executablePath": "C:\\Program Files\\YukkuriMovieMaker_v4_Lite_Dev\\YukkuriMovieMaker.exe" - } - } -} diff --git a/ProxyForge/ProxyForge.csproj b/ProxyForge/ProxyForge.csproj deleted file mode 100644 index cdda06c..0000000 --- a/ProxyForge/ProxyForge.csproj +++ /dev/null @@ -1,119 +0,0 @@ - - - - net10.0-windows10.0.19041.0 - true - enable - enable - 1.0.2 - AnyCPU;x64;x64 - True - - - - - - - - - - - - $(YMM4DirPath)AvalonDock.dll - false - - - $(YMM4DirPath)NAudio.dll - false - - - $(YMM4DirPath)NAudio.Core.dll - false - - - $(YMM4DirPath)NAudio.Midi.dll - false - - - $(YMM4DirPath)NCalc.Core.dll - false - - - $(YMM4DirPath)Newtonsoft.Json.dll - - - $(YMM4DirPath)SharpGen.Runtime.dll - false - - - $(YMM4DirPath)Vortice.Direct2D1.dll - false - - - $(YMM4DirPath)Vortice.Direct3D11.dll - false - - - $(YMM4DirPath)Vortice.DirectX.dll - false - - - $(YMM4DirPath)Vortice.D3DCompiler.dll - false - - - $(YMM4DirPath)Vortice.DXGI.dll - false - - - $(YMM4DirPath)Vortice.Mathematics.dll - false - - - $(YMM4DirPath)YukkuriMovieMaker.dll - false - - - $(YMM4DirPath)YukkuriMovieMaker.Controls.dll - false - - - $(YMM4DirPath)YukkuriMovieMaker.Plugin.dll - false - - - $(YMM4DirPath)YukkuriMovieMaker.Plugin.FileSource.FFmpeg.dll - false - - - $(YMM4DirPath)SharpGen.Runtime.COM.dll - false - - - $(YMM4DirPath)Vortice.DirectX.dll - false - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/ProxyForge/Services/WindowThemeRegistry.cs b/ProxyForge/Services/WindowThemeRegistry.cs deleted file mode 100644 index 33085a8..0000000 --- a/ProxyForge/Services/WindowThemeRegistry.cs +++ /dev/null @@ -1,22 +0,0 @@ -using ProxyForge.Interfaces; -using System.Windows; - -namespace ProxyForge.Services; - -internal static class WindowThemeRegistry -{ - private static IWindowThemeService _service = NullWindowThemeService.Instance; - - internal static void Register(IWindowThemeService service) - => Interlocked.Exchange(ref _service, service ?? NullWindowThemeService.Instance); - - internal static void Bind(Window window) - => _service.Bind(window); - - private sealed class NullWindowThemeService : IWindowThemeService - { - internal static readonly NullWindowThemeService Instance = new(); - private NullWindowThemeService() { } - public void Bind(Window window) { } - } -} \ No newline at end of file diff --git a/ProxyForge/Services/WindowThemeService.cs b/ProxyForge/Services/WindowThemeService.cs deleted file mode 100644 index 731611b..0000000 --- a/ProxyForge/Services/WindowThemeService.cs +++ /dev/null @@ -1,47 +0,0 @@ -using ProxyForge.Interfaces; -using System.Runtime.InteropServices; -using System.Windows; -using System.Windows.Interop; -using System.Windows.Media; - -namespace ProxyForge.Services; - -internal sealed class WindowThemeService : IWindowThemeService -{ - public void Bind(Window window) - { - if (window is null) return; - window.SourceInitialized += (_, _) => ApplyCurrentTheme(window); - window.Loaded += (_, _) => ApplyCurrentTheme(window); - } - - private static void ApplyCurrentTheme(Window window) - { - if (!OperatingSystem.IsWindowsVersionAtLeast(10, 0, 22000)) return; - var hwnd = new WindowInteropHelper(window).Handle; - if (hwnd == nint.Zero) return; - - var captionBrush = (window.TryFindResource(SystemColors.ControlBrushKey) as SolidColorBrush) ?? Brushes.White; - var textBrush = (window.TryFindResource(SystemColors.WindowTextBrushKey) as SolidColorBrush) ?? Brushes.Black; - - SetDwmColor(hwnd, NativeMethods.DwmwaCaption, captionBrush.Color); - SetDwmColor(hwnd, NativeMethods.DwmwaBorder, captionBrush.Color); - SetDwmColor(hwnd, NativeMethods.DwmwaText, textBrush.Color); - } - - private static void SetDwmColor(nint hwnd, uint attribute, Color color) - { - uint colorRef = color.R | ((uint)color.G << 8) | ((uint)color.B << 16); - NativeMethods.DwmSetWindowAttribute(hwnd, attribute, ref colorRef, sizeof(uint)); - } - - private static class NativeMethods - { - internal const uint DwmwaCaption = 35; - internal const uint DwmwaBorder = 34; - internal const uint DwmwaText = 36; - - [DllImport("dwmapi.dll")] - internal static extern int DwmSetWindowAttribute(nint hwnd, uint dwAttribute, ref uint pvAttribute, uint cbAttribute); - } -} \ No newline at end of file diff --git a/ProxyForge/Services/WpfDialogService.cs b/ProxyForge/Services/WpfDialogService.cs deleted file mode 100644 index 1a084ad..0000000 --- a/ProxyForge/Services/WpfDialogService.cs +++ /dev/null @@ -1,10 +0,0 @@ -using ProxyForge.Interfaces; -using System.Windows; - -namespace ProxyForge.Services; - -internal sealed class WpfDialogService : IDialogService -{ - public void ShowInformation(string message, string title) - => MessageBox.Show(message, title, MessageBoxButton.OK, MessageBoxImage.Information); -} \ No newline at end of file diff --git a/ProxyForge/Settings/ProxyForgeSettings.cs b/ProxyForge/Settings/ProxyForgeSettings.cs deleted file mode 100644 index 6ac587a..0000000 --- a/ProxyForge/Settings/ProxyForgeSettings.cs +++ /dev/null @@ -1,84 +0,0 @@ -using ProxyForge.Localization; -using YukkuriMovieMaker.Plugin; - -namespace ProxyForge.Settings; - -internal sealed class ProxyForgeSettings : SettingsBase -{ - public override SettingsCategory Category => SettingsCategory.VideoFileSource; - public override string Name => Translate.SettingsName; - public override bool HasSettingView => true; - public override object? SettingView => new Views.ProxyForgeSettingsView(); - - private bool _useProxy = true; - public bool UseProxy - { - get => _useProxy; - set => Set(ref _useProxy, value); - } - - private int _scale = 50; - public int Scale - { - get => _scale; - set => Set(ref _scale, Math.Clamp(value, 10, 100)); - } - - private int _minFileSizeForProxy = 100; - public int MinFileSizeForProxy - { - get => _minFileSizeForProxy; - set => Set(ref _minFileSizeForProxy, Math.Clamp(value, 1, 10000)); - } - - private int _bitrateFactor = 50; - public int BitrateFactor - { - get => _bitrateFactor; - set => Set(ref _bitrateFactor, Math.Clamp(value, 1, 200)); - } - - private int _gopSize = 30; - public int GopSize - { - get => _gopSize; - set => Set(ref _gopSize, Math.Clamp(value, 1, 300)); - } - - private bool _autoGenerate = true; - public bool AutoGenerate - { - get => _autoGenerate; - set => Set(ref _autoGenerate, value); - } - - private bool _clearCacheOnExit; - public bool ClearCacheOnExit - { - get => _clearCacheOnExit; - set => Set(ref _clearCacheOnExit, value); - } - - private bool _useAdvancedSetting; - public bool UseAdvancedSetting - { - get => _useAdvancedSetting; - set => Set(ref _useAdvancedSetting, value); - } - - private bool _enableHardwareAcceleration = true; - public bool EnableHardwareAcceleration - { - get => _enableHardwareAcceleration; - set => Set(ref _enableHardwareAcceleration, value); - } - - private bool _enableVideoCache = true; - public bool EnableVideoCache - { - get => _enableVideoCache; - set => Set(ref _enableVideoCache, value); - } - - public override void Initialize() { } -} \ No newline at end of file diff --git a/ProxyForge/Transcoding/FFmpegArguments.cs b/ProxyForge/Transcoding/FFmpegArguments.cs deleted file mode 100644 index bf5a754..0000000 --- a/ProxyForge/Transcoding/FFmpegArguments.cs +++ /dev/null @@ -1,134 +0,0 @@ -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 deleted file mode 100644 index 6faac43..0000000 --- a/ProxyForge/Transcoding/FFmpegEncoderSelector.cs +++ /dev/null @@ -1,159 +0,0 @@ -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 deleted file mode 100644 index c9d7a65..0000000 --- a/ProxyForge/Transcoding/FFmpegProcessRunner.cs +++ /dev/null @@ -1,243 +0,0 @@ -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 deleted file mode 100644 index d683135..0000000 --- a/ProxyForge/Transcoding/FFmpegRuntime.cs +++ /dev/null @@ -1,63 +0,0 @@ -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 deleted file mode 100644 index b323986..0000000 --- a/ProxyForge/Transcoding/FrameRate.cs +++ /dev/null @@ -1,59 +0,0 @@ -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 deleted file mode 100644 index 2053d99..0000000 --- a/ProxyForge/Transcoding/ProxyFrameRenderer.cs +++ /dev/null @@ -1,114 +0,0 @@ -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 deleted file mode 100644 index 7a88514..0000000 --- a/ProxyForge/Transcoding/ProxyGeometry.cs +++ /dev/null @@ -1,48 +0,0 @@ -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/Utilities/ByteFormatter.cs b/ProxyForge/Utilities/ByteFormatter.cs deleted file mode 100644 index 49166d5..0000000 --- a/ProxyForge/Utilities/ByteFormatter.cs +++ /dev/null @@ -1,22 +0,0 @@ -namespace ProxyForge.Utilities; - -internal static class ByteFormatter -{ - private static readonly string[] s_units = ["B", "KB", "MB", "GB", "TB"]; - - internal static string Format(long bytes) - { - if (bytes <= 0) - return "0 B"; - - double value = bytes; - int order = 0; - while (value >= 1024.0 && order < s_units.Length - 1) - { - order++; - value /= 1024.0; - } - - return string.Create(null, stackalloc char[32], $"{value:0.##} {s_units[order]}"); - } -} \ No newline at end of file diff --git a/ProxyForge/ViewModels/GenerationPopupViewModel.cs b/ProxyForge/ViewModels/GenerationPopupViewModel.cs deleted file mode 100644 index deb9c0f..0000000 --- a/ProxyForge/ViewModels/GenerationPopupViewModel.cs +++ /dev/null @@ -1,24 +0,0 @@ -using ProxyForge.Progress; -using System.Collections.ObjectModel; -using YukkuriMovieMaker.Commons; - -namespace ProxyForge.ViewModels; - -internal sealed class GenerationPopupViewModel : Bindable -{ - public ObservableCollection Items { get; } - - private bool _hasItems; - public bool HasItems - { - get => _hasItems; - set => Set(ref _hasItems, value); - } - - internal GenerationPopupViewModel(ObservableCollection items) - { - Items = items; - Items.CollectionChanged += (_, _) => HasItems = Items.Count > 0; - HasItems = Items.Count > 0; - } -} \ No newline at end of file diff --git a/ProxyForge/ViewModels/SettingsViewModel.cs b/ProxyForge/ViewModels/SettingsViewModel.cs deleted file mode 100644 index 2840f65..0000000 --- a/ProxyForge/ViewModels/SettingsViewModel.cs +++ /dev/null @@ -1,230 +0,0 @@ -using ProxyForge.Cache; -using ProxyForge.Core; -using ProxyForge.Interfaces; -using ProxyForge.Localization; -using ProxyForge.Utilities; -using System.Collections.ObjectModel; -using System.Windows.Input; -using YukkuriMovieMaker.Commons; - -namespace ProxyForge.ViewModels; - -internal sealed class SettingsViewModel : Bindable -{ - private readonly ProxyCacheManager? _cacheManager; - private readonly VideoCacheDatabase? _videoCache; - private readonly IDialogService _dialogService; - - private string _cacheSummaryText = Translate.CacheSummaryLoading; - public string CacheSummaryText - { - get => _cacheSummaryText; - set => Set(ref _cacheSummaryText, value); - } - - private string _cacheUsageText = ""; - public string CacheUsageText - { - get => _cacheUsageText; - set => Set(ref _cacheUsageText, value); - } - - private bool _hasCacheEntries; - public bool HasCacheEntries - { - get => _hasCacheEntries; - set => Set(ref _hasCacheEntries, value); - } - - public ObservableCollection CacheEntries { get; } = []; - - private string _videoCacheSummaryText = ""; - public string VideoCacheSummaryText - { - get => _videoCacheSummaryText; - set => Set(ref _videoCacheSummaryText, value); - } - - private bool _hasVideoCacheEntries; - public bool HasVideoCacheEntries - { - get => _hasVideoCacheEntries; - set => Set(ref _hasVideoCacheEntries, value); - } - - public ObservableCollection VideoCacheEntries { get; } = []; - - public ICommand ClearCacheCommand { get; } - public ICommand RefreshCacheInfoCommand { get; } - public ICommand RemoveCacheEntryCommand { get; } - public ICommand ClearVideoCacheCommand { get; } - public ICommand RemoveVideoCacheEntryCommand { get; } - - internal SettingsViewModel(ProxyCacheManager? cacheManager, VideoCacheDatabase? videoCache, IDialogService dialogService) - { - _cacheManager = cacheManager; - _videoCache = videoCache; - _dialogService = dialogService; - ClearCacheCommand = new ActionCommand(ExecuteClearCache); - RefreshCacheInfoCommand = new ActionCommand(ExecuteRefreshCacheInfo); - RemoveCacheEntryCommand = new ActionCommand(ExecuteRemoveEntry); - ClearVideoCacheCommand = new ActionCommand(ExecuteClearVideoCache); - RemoveVideoCacheEntryCommand = new ActionCommand(ExecuteRemoveVideoCacheEntry); - ExecuteRefreshCacheInfo(); - } - - private void ExecuteClearCache() - { - if (_cacheManager is null) - return; - - var (count, totalSize) = _cacheManager.ClearAll(); - if (count == 0) - { - _dialogService.ShowInformation(Translate.CacheNoEntriesToDelete, Translate.AppName); - } - else - { - _dialogService.ShowInformation( - string.Format(Translate.CacheDeleteSummaryFormat, count.ToString("N0"), ByteFormatter.Format(totalSize)), - Translate.AppName); - } - - ExecuteRefreshCacheInfo(); - } - - private void ExecuteRefreshCacheInfo() - { - if (_cacheManager is null) - { - CacheSummaryText = Translate.CacheSummaryPluginNotInitialized; - CacheUsageText = ""; - HasCacheEntries = false; - return; - } - - var (count, totalSize) = _cacheManager.GetCacheInfo(); - CacheSummaryText = string.Format(Translate.CacheSummaryCountFormat, count.ToString("N0")); - CacheUsageText = string.Format( - Translate.CacheUsageDiskFormat, - count.ToString("N0"), - ByteFormatter.Format(totalSize)); - - CacheEntries.Clear(); - var snapshots = _cacheManager.GetAllSnapshots(); - foreach (var snap in snapshots) - CacheEntries.Add(new CacheEntryViewModel(snap)); - - HasCacheEntries = CacheEntries.Count > 0; - - RefreshVideoCacheInfo(); - } - - private void ExecuteRemoveEntry(CacheEntryViewModel? entry) - { - if (entry is null || _cacheManager is null) - return; - - _cacheManager.RemoveProxy(entry.OriginalPath, entry.Scale); - ExecuteRefreshCacheInfo(); - } - - private void ExecuteClearVideoCache() - { - if (_videoCache is null) - return; - - var count = _videoCache.ClearAll(); - if (count == 0) - _dialogService.ShowInformation(Translate.VideoCacheListEmpty, Translate.AppName); - else - _dialogService.ShowInformation( - string.Format(Translate.CacheDeleteSummaryFormat, count.ToString("N0"), ""), - Translate.AppName); - - ExecuteRefreshCacheInfo(); - } - - private void ExecuteRemoveVideoCacheEntry(VideoCacheEntryViewModel? entry) - { - if (entry is null || _videoCache is null) - return; - - _videoCache.Remove(entry.Uuid); - ExecuteRefreshCacheInfo(); - } - - private void RefreshVideoCacheInfo() - { - VideoCacheEntries.Clear(); - - if (_videoCache is null) - { - VideoCacheSummaryText = ""; - HasVideoCacheEntries = false; - return; - } - - var entries = _videoCache.GetAll(); - long totalSize = 0; - foreach (var e in entries) - { - totalSize += e.FileSize; - VideoCacheEntries.Add(new VideoCacheEntryViewModel(e)); - } - - VideoCacheSummaryText = string.Format( - Translate.VideoCacheSummaryFormat, - entries.Length.ToString("N0"), - ByteFormatter.Format(totalSize)); - - HasVideoCacheEntries = entries.Length > 0; - } -} - -internal sealed class CacheEntryViewModel(CacheEntrySnapshot snapshot) : Bindable -{ - public string FileName { get; } = snapshot.FileName; - 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 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"); - public string LastAccessedText { get; } = snapshot.LastAccessedAt.ToLocalTime().ToString("HH:mm:ss"); - public string ScaleText { get; } = string.Create(null, stackalloc char[8], $"{snapshot.Scale * 100:F0}%"); -} - -internal sealed class VideoCacheEntryViewModel(VideoCacheLookupResult entry) : Bindable -{ - public Guid Uuid { get; } = entry.Uuid; - public string FileName { get; } = entry.FileName; - public string OriginalPath { get; } = entry.OriginalPath; - public float Scale { get; } = entry.Scale; - public string Resolution { get; } = entry.ProxyWidth > 0 - ? string.Create(null, stackalloc char[24], $"{entry.ProxyWidth}\u00d7{entry.ProxyHeight}") - : "—"; - public string StorageType { get; } = Translate.StoragePersistent; - public long DataSize { get; } = entry.FileSize; - public string DataSizeText { get; } = ByteFormatter.Format(entry.FileSize); - public string CreatedAtText { get; } = entry.CreatedAt.ToLocalTime().ToString("yyyy/MM/dd HH:mm"); - public string LastAccessedText { get; } = entry.LastAccessedAt.ToLocalTime().ToString("yyyy/MM/dd HH:mm"); - public string ScaleText { get; } = entry.Scale > 0 - ? string.Create(null, stackalloc char[8], $"{entry.Scale * 100:F0}%") - : "—"; -} - -internal sealed class ActionCommand(Action execute) : ICommand -{ - public event EventHandler? CanExecuteChanged { add { } remove { } } - public bool CanExecute(object? parameter) => true; - public void Execute(object? parameter) => execute(); -} - -internal sealed class ActionCommand(Action execute) : ICommand where T : class -{ - public event EventHandler? CanExecuteChanged { add { } remove { } } - public bool CanExecute(object? parameter) => true; - public void Execute(object? parameter) => execute(parameter as T); -} \ No newline at end of file diff --git a/ProxyForge/Views/GenerationPopupView.xaml b/ProxyForge/Views/GenerationPopupView.xaml deleted file mode 100644 index bd41be3..0000000 --- a/ProxyForge/Views/GenerationPopupView.xaml +++ /dev/null @@ -1,71 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/ProxyForge/Views/GenerationPopupView.xaml.cs b/ProxyForge/Views/GenerationPopupView.xaml.cs deleted file mode 100644 index 89e05da..0000000 --- a/ProxyForge/Views/GenerationPopupView.xaml.cs +++ /dev/null @@ -1,71 +0,0 @@ -using ProxyForge.ViewModels; -using System.Collections.Specialized; -using System.Globalization; -using System.Windows; -using System.Windows.Data; -using System.Windows.Threading; - -namespace ProxyForge.Views; - -public partial class GenerationPopupView : Window -{ - private readonly GenerationPopupViewModel _viewModel; - private bool _allowClose; - - internal GenerationPopupView(GenerationPopupViewModel viewModel) - { - InitializeComponent(); - _viewModel = viewModel; - DataContext = _viewModel; - _viewModel.Items.CollectionChanged += OnItemsChanged; - Loaded += (_, _) => PositionBottomRight(); - } - - private void OnItemsChanged(object? sender, NotifyCollectionChangedEventArgs e) - { - if (_viewModel.Items.Count > 0) - Dispatcher.BeginInvoke(PositionBottomRight, DispatcherPriority.Loaded); - } - - private void PositionBottomRight() - { - var workArea = SystemParameters.WorkArea; - var windowWidth = double.IsNaN(ActualWidth) || ActualWidth <= 0 ? Width : ActualWidth; - var windowHeight = double.IsNaN(ActualHeight) || ActualHeight <= 0 ? Height : ActualHeight; - - if (double.IsNaN(windowWidth) || windowWidth <= 0) - windowWidth = MinWidth; - if (double.IsNaN(windowHeight) || windowHeight <= 0) - windowHeight = MinHeight; - - Left = workArea.Right - windowWidth - 12; - Top = workArea.Bottom - windowHeight - 12; - } - - internal void ForceClose() - { - _allowClose = true; - _viewModel.Items.CollectionChanged -= OnItemsChanged; - Close(); - } - - protected override void OnClosing(System.ComponentModel.CancelEventArgs e) - { - if (!_allowClose) - { - e.Cancel = true; - Hide(); - return; - } - base.OnClosing(e); - } -} - -internal sealed class InvertBoolToVisibilityConverter : IValueConverter -{ - public object Convert(object value, Type targetType, object parameter, CultureInfo culture) - => value is true ? Visibility.Collapsed : Visibility.Visible; - - public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) - => throw new NotSupportedException(); -} \ No newline at end of file diff --git a/ProxyForge/Views/ProxyForgeSettingsView.xaml b/ProxyForge/Views/ProxyForgeSettingsView.xaml deleted file mode 100644 index c4bfa08..0000000 --- a/ProxyForge/Views/ProxyForgeSettingsView.xaml +++ /dev/null @@ -1,361 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -