Skip to content

Commit

Permalink
VFR option in GUI, logic fixes and sanity check improvs, disable dedu…
Browse files Browse the repository at this point in the history
…pe if <5% dupes
  • Loading branch information
n00mkrad committed Dec 2, 2024
1 parent 2769b7d commit 046cbad
Show file tree
Hide file tree
Showing 17 changed files with 127 additions and 62 deletions.
1 change: 1 addition & 0 deletions CodeLegacy/Data/Enums.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
{
public class Enums
{
public enum VfrMode { Auto, All, None }
public enum Round { Near, Up, Down }

public class Output
Expand Down
3 changes: 3 additions & 0 deletions CodeLegacy/Data/InterpSettings.cs
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,9 @@ public void InitArgs ()

private void SetPaths (string inputPath)
{
if (!File.Exists(inputPath) && !Directory.Exists(inputPath))
return;

inPath = inputPath;
outPath = (Config.GetInt("outFolderLoc") == 0) ? inputPath.GetParentDir() : Config.Get("custOutDir").Trim();
tempFolder = InterpolateUtils.GetTempFolderLoc(inPath, outPath);
Expand Down
7 changes: 7 additions & 0 deletions CodeLegacy/Data/Strings.cs
Original file line number Diff line number Diff line change
Expand Up @@ -92,5 +92,12 @@ public class Strings
{ Enums.Encoding.Quality.JpegWebm.ImgLow.ToString(), "Low" },
{ Enums.Encoding.Quality.JpegWebm.ImgLowest.ToString(), "Lowest" },
};

public static Dictionary<string, string> VfrMode = new Dictionary<string, string>
{
{ Enums.VfrMode.Auto.ToString(), "Automatic" },
{ Enums.VfrMode.All.ToString(), "Treat all videos as VFR" },
{ Enums.VfrMode.None.ToString(), "Treat no videos as VFR" },
};
}
}
5 changes: 0 additions & 5 deletions CodeLegacy/Extensions/ExtensionMethods.cs
Original file line number Diff line number Diff line change
Expand Up @@ -285,11 +285,6 @@ public static string GetConcStr(this string filePath, int rate = -1)
return filePath.IsConcatFile() ? $"{rateStr}-safe 0 -f concat " : "";
}

public static string GetFfmpegInputArg(this string filePath)
{
return $"{(filePath.IsConcatFile() ? filePath.GetConcStr() : "")} -i {filePath.Wrap()}";
}

public static string Get(this Dictionary<string, string> dict, string key, bool returnKeyInsteadOfEmptyString = false, bool ignoreCase = false)
{
if (key == null)
Expand Down
29 changes: 29 additions & 0 deletions CodeLegacy/Forms/Main/Form1.Designer.cs

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

50 changes: 30 additions & 20 deletions CodeLegacy/Forms/Main/Form1.cs
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,8 @@ public enum EXECUTION_STATE : uint { ES_AWAYMODE_REQUIRED = 0x00000040, ES_CONTI

public bool ShowModelDownloader = false;

private Enums.VfrMode prevVfrMode = (Enums.VfrMode)(-1);

protected override CreateParams CreateParams
{
get
Expand Down Expand Up @@ -68,6 +70,7 @@ private void Form1_Load(object sender, EventArgs e)

private async void Form1_Shown(object sender, EventArgs e)
{
Program.mainForm = this;
Refresh();
await Task.Delay(1);

Expand All @@ -77,12 +80,12 @@ private async void Form1_Shown(object sender, EventArgs e)
// Main Tab
UiUtils.InitCombox(interpFactorCombox, 0);
UiUtils.InitCombox(outSpeedCombox, 0);
// Video Utils
UiUtils.InitCombox(trimCombox, 0);
// Quick Settings
UiUtils.InitCombox(trimCombox, 0);
mpdecimateMode.FillFromEnum<Enums.Interpolation.MpDecimateSens>(useKeyNames: true);
vfrHandling.FillFromEnum<Enums.VfrMode>(stringMap: Strings.VfrMode);
vfrHandling.SelectedIndexChanged += (s, ev) => VfrModeChange();

Program.mainForm = this;
Logger.textbox = logBox;
VulkanUtils.Init();
NvApi.Init();
Expand All @@ -101,19 +104,24 @@ private async void Form1_Shown(object sender, EventArgs e)
completionAction.SelectedIndex = 0;
}

private void InitOutputUi()
private void VfrModeChange()
{
comboxOutputFormat.FillFromEnum<Enums.Output.Format>(Strings.OutputFormat, 0);
UpdateOutputUi();
var oldMode = (Enums.VfrMode)Config.GetInt(Config.Key.vfrHandling);
var newMode = ParseUtils.GetEnum<Enums.VfrMode>(vfrHandling.Text, stringMap: Strings.VfrMode);

if (Debugger.IsAttached)
if (newMode != oldMode)
{
Logger.Log($"Formats: {string.Join(", ", Enum.GetValues(typeof(Enums.Output.Format)).Cast<Enums.Output.Format>().Select(e => Strings.OutputFormat.Get(e.ToString())))}", true);
Logger.Log($"Encoders: {string.Join(", ", Enum.GetValues(typeof(Enums.Encoding.Encoder)).Cast<Enums.Encoding.Encoder>().Select(e => Strings.Encoder.Get(e.ToString())))}", true);
Logger.Log($"Pixel Formats: {string.Join(", ", Enum.GetValues(typeof(Enums.Encoding.PixelFormat)).Cast<Enums.Encoding.PixelFormat>().Select(e => Strings.PixelFormat.Get(e.ToString())))}", true);
SaveQuickSettings();
HandleInputFiles(new[] { inputTbox.Text });
}
}

private void InitOutputUi()
{
comboxOutputFormat.FillFromEnum<Enums.Output.Format>(Strings.OutputFormat, 0);
UpdateOutputUi();
}

public async void ResetOutputUi()
{
comboxOutputEncoder.Items.Clear();
Expand Down Expand Up @@ -168,7 +176,7 @@ private void UpdateOutputEncodingUi()
labelOutput.Text = $"Set {string.Join(", ", infoStrings)}";
}

async Task Checks()
private async Task Checks()
{
try
{
Expand All @@ -187,14 +195,14 @@ async Task Checks()
}
}

void HandleArgs()
private void HandleArgs()
{
// Input & interpolation settings

if (Cli.ValidFiles.Any())
{
Logger.Log($"[CLI] Loading file(s): {string.Join(", ", Cli.ValidFiles)}", true);
DragDropHandler(Cli.ValidFiles.ToArray());
HandleInputFiles(Cli.ValidFiles.ToArray());
}

if (Cli.InterpAi != (Implementations.Ai)(-1))
Expand Down Expand Up @@ -403,7 +411,7 @@ public void ResetInputInfo()
UpdateInputInfo();
}

void InitAis()
private void InitAis()
{
bool pytorchAvailable = Python.IsPytorchReady();

Expand Down Expand Up @@ -457,15 +465,15 @@ private void browseInputBtn_Click(object sender, EventArgs e)
CommonOpenFileDialog dialog = new CommonOpenFileDialog { InitialDirectory = inputTbox.Text.Trim(), IsFolderPicker = true };

if (dialog.ShowDialog() == CommonFileDialogResult.Ok)
DragDropHandler(new string[] { dialog.FileName });
HandleInputFiles(new string[] { dialog.FileName });
}

private void browseInputFileBtn_Click(object sender, EventArgs e)
{
CommonOpenFileDialog dialog = new CommonOpenFileDialog { InitialDirectory = inputTbox.Text.Trim(), IsFolderPicker = false };

if (dialog.ShowDialog() == CommonFileDialogResult.Ok)
DragDropHandler(new string[] { dialog.FileName });
HandleInputFiles(new string[] { dialog.FileName });
}

private void browseOutBtn_Click(object sender, EventArgs e)
Expand Down Expand Up @@ -535,7 +543,7 @@ public void SetFormat(Enums.Output.Format format)

private void inputTbox_DragDrop(object sender, DragEventArgs e)
{
DragDropHandler((string[])e.Data.GetData(DataFormats.FileDrop));
HandleInputFiles((string[])e.Data.GetData(DataFormats.FileDrop));
}

void outputTbox_DragEnter(object sender, DragEventArgs e) { e.Effect = DragDropEffects.Copy; }
Expand Down Expand Up @@ -658,10 +666,10 @@ private async void Form1_DragDrop(object sender, DragEventArgs e)
{
var files = (string[])e.Data.GetData(DataFormats.FileDrop);
await Task.Delay(1); // Release drop
DragDropHandler(files);
HandleInputFiles(files);
}

public void DragDropHandler(string[] files, bool first = true)
public void HandleInputFiles(string[] files)
{
if (Program.busy) return;

Expand Down Expand Up @@ -798,7 +806,7 @@ private void trimBox_TextChanged(object sender, EventArgs e)

#region Quick Settings

public void SaveQuickSettings(object sender, EventArgs e)
public void SaveQuickSettings(object sender = null, EventArgs e = null)
{
if (!_quickSettingsInitialized) return;

Expand All @@ -813,6 +821,7 @@ public void SaveQuickSettings(object sender, EventArgs e)
ConfigParser.SaveGuiElement(scnDetect);
ConfigParser.SaveGuiElement(scnDetectValue);
ConfigParser.SaveGuiElement(maxFps);
ConfigParser.SaveComboxIndex(vfrHandling);
}

public void LoadQuickSettings(object sender = null, EventArgs e = null)
Expand All @@ -825,6 +834,7 @@ public void LoadQuickSettings(object sender = null, EventArgs e = null)
ConfigParser.LoadGuiElement(scnDetect);
ConfigParser.LoadGuiElement(scnDetectValue);
ConfigParser.LoadGuiElement(maxFps);
ConfigParser.LoadComboxIndex(vfrHandling);

_quickSettingsInitialized = true;
}
Expand Down
15 changes: 1 addition & 14 deletions CodeLegacy/IO/Config.cs
Original file line number Diff line number Diff line change
Expand Up @@ -111,20 +111,6 @@ private static void Reload()
}
}

// Get using fixed key
public static string Get(Key key, string defaultVal)
{
WriteIfDoesntExist(key.ToString(), defaultVal);
return Get(key);
}

// Get using string
public static string Get(string key, string defaultVal)
{
WriteIfDoesntExist(key, defaultVal);
return Get(key);
}

public static string Get(Key key, Type type = Type.String)
{
return Get(key.ToString(), type);
Expand Down Expand Up @@ -390,6 +376,7 @@ public enum Key
lastOutputSettings,
PerformedHwEncCheck,
SupportedHwEncoders,
vfrHandling,
}
}
}
4 changes: 2 additions & 2 deletions CodeLegacy/IO/ConfigParser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ public static void SaveGuiElement(NumericUpDown upDown, StringMode stringMode =

public static void SaveComboxIndex(ComboBox comboBox)
{
Config.Set(comboBox.Name, comboBox.SelectedIndex.ToString());
Config.Set(comboBox.Name, comboBox.SelectedIndex.Clamp(0, int.MaxValue).ToString());
}

public static void LoadGuiElement(ComboBox comboBox, string suffix = "")
Expand All @@ -70,7 +70,7 @@ public static void LoadGuiElement(NumericUpDown upDown)

public static void LoadComboxIndex(ComboBox comboBox)
{
comboBox.SelectedIndex = Config.GetInt(comboBox.Name);
comboBox.SelectedIndex = Config.GetInt(comboBox.Name).Clamp(0, int.MaxValue);
}
}
}
3 changes: 3 additions & 0 deletions CodeLegacy/IO/IoUtils.cs
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,9 @@ public static bool IsPathValid(string path)

public static bool IsPathOneDrive(string path)
{
if (path.IsEmpty())
return false;

return path.Lower().Replace("\\", "/").MatchesWildcard("*:/users/*/onedrive*");
}

Expand Down
19 changes: 16 additions & 3 deletions CodeLegacy/Magick/Dedupe.cs
Original file line number Diff line number Diff line change
Expand Up @@ -268,10 +268,11 @@ public static async Task CreateFramesFileVideo(string videoPath, bool loop)
Process ffmpeg = OsUtils.NewProcess(true);
string baseCmd = $"/C cd /D {Path.Combine(IO.Paths.GetPkgPath(), IO.Paths.audioVideoDir).Wrap()}";
string mpDec = FfmpegCommands.GetMpdecimate(wrap: false); // FfmpegCommands.GetMpdecimate((int)FfmpegCommands.MpDecSensitivity.Normal, false);
ffmpeg.StartInfo.Arguments = $"{baseCmd} & ffmpeg -loglevel debug -y -i {videoPath.Wrap()} -fps_mode vfr -vf {mpDec} -f null NUL 2>&1 | findstr keep_count:";
ffmpeg.StartInfo.Arguments = $"{baseCmd} & ffmpeg -loglevel debug -y {videoPath.GetConcStr()} -i {videoPath.Wrap()} -fps_mode vfr -vf {mpDec} -f null NUL 2>&1 | findstr keep_count:";
var ffmpegOutputLines = (await Task.Run(() => OsUtils.GetProcStdOut(ffmpeg, true))).SplitIntoLines();

var frames = new Dictionary<int, List<int>>();
int frameCount = 0;
int lastKeepFrameNum = 0;

for (int frameIdx = 0; frameIdx < ffmpegOutputLines.Length; frameIdx++)
Expand All @@ -286,24 +287,36 @@ public static async Task CreateFramesFileVideo(string videoPath, bool loop)
}

lastKeepFrameNum = frameIdx;
frameCount++;
}
else if (line.Contains(" drop pts:"))
{
frames[lastKeepFrameNum].Add(frameIdx);
frameCount++;
}
}

var inputFrames = new List<int>(frames.Keys);
float keepPercentage = (float)inputFrames.Count / frameCount * 100f;
Logger.Log($"Dedupe: Kept {inputFrames.Count}/{frameCount} frames ({keepPercentage.ToString("0.#")}%)");

Logger.Log($"Dedupe: Kept {inputFrames.Count}/{ffmpegOutputLines.Length} frames", true);
if (keepPercentage > 95f)
{
Logger.Log("Dedupe: Less than 5% duplicate frames detected, will not dedupe.");
Interpolate.currentSettings.dedupe = false;
}

if (loop)
{
inputFrames.Add(inputFrames.First());
}

File.WriteAllText(Path.Combine(Interpolate.currentSettings.tempFolder, "input.json"), inputFrames.ToJson(true));
File.WriteAllText(Path.Combine(Interpolate.currentSettings.tempFolder, "dupes.test.json"), frames.ToJson(true));

if (Interpolate.currentSettings.dedupe)
{
File.WriteAllText(Path.Combine(Interpolate.currentSettings.tempFolder, "dupes.test.json"), frames.ToJson(true));
}
}
}
}
6 changes: 4 additions & 2 deletions CodeLegacy/Main/Export.cs
Original file line number Diff line number Diff line change
Expand Up @@ -335,7 +335,9 @@ public static async Task EncodeChunk(string outPath, string interpDir, int chunk

static async Task Loop(string outPath, int looptimes)
{
if (looptimes < 1 || !Config.GetBool(Config.Key.enableLoop)) return;
if (looptimes < 1 || !Config.GetBool(Config.Key.enableLoop))
return;

Logger.Log($"Looping {looptimes} {(looptimes == 1 ? "time" : "times")} to reach target length of {Config.GetInt(Config.Key.minOutVidLength)}s...");
await FfmpegCommands.LoopVideo(outPath, looptimes, Config.GetInt(Config.Key.loopMode) == 0);
}
Expand All @@ -347,7 +349,7 @@ private static int GetLoopTimes()
int minFrameCount = (minLength * I.currentSettings.outFps.Float).RoundToInt();
int outFrames = (I.currentMediaFile.FrameCount * I.currentSettings.interpFactor).RoundToInt();
if (outFrames / I.currentSettings.outFps.Float < minLength)
times = (int)Math.Ceiling((double)minFrameCount / (double)outFrames);
times = (int)Math.Ceiling((double)minFrameCount / outFrames);
times--; // Not counting the 1st play (0 loops)
if (times <= 0) return -1; // Never try to loop 0 times, idk what would happen, probably nothing
return times;
Expand Down
Loading

0 comments on commit 046cbad

Please sign in to comment.