async/background TryDeleteIfExistsAsync & DeleteContentsOfDir

This commit is contained in:
N00MKRAD
2021-05-09 18:31:39 +02:00
parent b3a32ff557
commit f9a631340d
7 changed files with 72 additions and 84 deletions

View File

@@ -118,19 +118,30 @@ namespace Flowframes.IO
} }
} }
public static void DeleteContentsOfDir(string path) /// <summary>
/// Async version of DeleteContentsOfDir, won't block main thread.
/// </summary>
public static async Task<bool> DeleteContentsOfDirAsync(string path)
{ {
DirectoryInfo directoryInfo = new DirectoryInfo(path); return await Task.Run(async () => { return DeleteContentsOfDir(path); }); // Delete in background thread
FileInfo[] files = directoryInfo.GetFiles(); }
foreach (FileInfo fileInfo in files)
{ /// <summary>
fileInfo.Delete(); /// Delete everything inside a directory except the dir itself.
} /// </summary>
DirectoryInfo[] directories = directoryInfo.GetDirectories(); public static bool DeleteContentsOfDir(string path)
foreach (DirectoryInfo directoryInfo2 in directories) {
{ try
directoryInfo2.Delete(recursive: true); {
DeleteIfExists(path);
Directory.CreateDirectory(path);
return true;
} }
catch(Exception e)
{
Logger.Log("DeleteContentsOfDir Error: " + e.Message, true);
return false;
}
} }
public static void ReplaceInFilenamesDir(string dir, string textToFind, string textToReplace, bool recursive = true, string wildcard = "*") public static void ReplaceInFilenamesDir(string dir, string textToFind, string textToReplace, bool recursive = true, string wildcard = "*")
@@ -245,36 +256,6 @@ namespace Flowframes.IO
} }
} }
public static async Task<Dictionary<string, string>> RenameCounterDirReversibleAsync(string path, string ext, int startAt, int padding = 0)
{
Stopwatch sw = new Stopwatch();
sw.Restart();
Dictionary<string, string> oldNewNamesMap = new Dictionary<string, string>();
int counter = startAt;
FileInfo[] files = new DirectoryInfo(path).GetFiles($"*.{ext}", SearchOption.TopDirectoryOnly);
var filesSorted = files.OrderBy(n => n);
foreach (FileInfo file in files)
{
string dir = new DirectoryInfo(file.FullName).Parent.FullName;
int filesDigits = (int)Math.Floor(Math.Log10((double)files.Length) + 1);
string newFilename = (padding > 0) ? counter.ToString().PadLeft(padding, '0') : counter.ToString();
string outpath = outpath = Path.Combine(dir, newFilename + Path.GetExtension(file.FullName));
File.Move(file.FullName, outpath);
oldNewNamesMap.Add(file.FullName, outpath);
counter++;
if(sw.ElapsedMilliseconds > 100)
{
await Task.Delay(1);
sw.Restart();
}
}
return oldNewNamesMap;
}
public static async Task ReverseRenaming(string basePath, Dictionary<string, string> oldNewMap) // Relative -> absolute paths public static async Task ReverseRenaming(string basePath, Dictionary<string, string> oldNewMap) // Relative -> absolute paths
{ {
Dictionary<string, string> absPaths = oldNewMap.ToDictionary(x => Path.Combine(basePath, x.Key), x => Path.Combine(basePath, x.Value)); Dictionary<string, string> absPaths = oldNewMap.ToDictionary(x => Path.Combine(basePath, x.Key), x => Path.Combine(basePath, x.Value));
@@ -347,17 +328,24 @@ namespace Flowframes.IO
public static async Task<Size> GetVideoOrFramesRes (string path) public static async Task<Size> GetVideoOrFramesRes (string path)
{ {
Size res; Size res = new Size();
if (!IsPathDirectory(path)) // If path is video try
{ {
res = GetVideoRes(path); if (!IsPathDirectory(path)) // If path is video
} {
else // Path is frame folder res = GetVideoRes(path);
{ }
Image thumb = await MainUiFunctions.GetThumbnail(path); else // Path is frame folder
res = new Size(thumb.Width, thumb.Height); {
Image thumb = await MainUiFunctions.GetThumbnail(path);
res = new Size(thumb.Width, thumb.Height);
}
} }
catch (Exception e)
{
Logger.Log("GetVideoOrFramesRes Error: " + e.Message);
}
return res; return res;
} }
@@ -379,12 +367,30 @@ namespace Flowframes.IO
return size; return size;
} }
/// <summary>
/// Async (background thread) version of TryDeleteIfExists. Safe to run without awaiting.
/// </summary>
public static async Task<bool> TryDeleteIfExistsAsync(string path)
{
string renamedPath = path;
while (Directory.Exists(renamedPath)) // Keep adding a "_" to the end if there is still an undeleted dir (unlikely)
renamedPath += "_";
Directory.Move(path, renamedPath); // Move/rename, so a new folder can be created without waiting this one's deletion
return await Task.Run(async () => { return TryDeleteIfExists(renamedPath); }); // Delete in background thread
}
/// <summary>
/// Delete a path if it exists. Works for files and directories. Returns success status.
/// </summary>
public static bool TryDeleteIfExists(string path) // Returns true if no exception occurs public static bool TryDeleteIfExists(string path) // Returns true if no exception occurs
{ {
try try
{ {
if (path == null) if (path == null)
return false; return false;
DeleteIfExists(path); DeleteIfExists(path);
return true; return true;
} }
@@ -397,16 +403,20 @@ namespace Flowframes.IO
public static bool DeleteIfExists (string path) // Returns true if the file/dir exists public static bool DeleteIfExists (string path) // Returns true if the file/dir exists
{ {
if (!IsPathDirectory(path) && File.Exists(path)) Logger.Log($"DeleteIfExists({path})", true);
if (!IsPathDirectory(path) && File.Exists(path))
{ {
File.Delete(path); File.Delete(path);
return true; return true;
} }
if (IsPathDirectory(path) && Directory.Exists(path)) if (IsPathDirectory(path) && Directory.Exists(path))
{ {
Directory.Delete(path, true); Directory.Delete(path, true);
return true; return true;
} }
return false; return false;
} }

View File

@@ -100,12 +100,12 @@ namespace Flowframes.Main
} }
if (!stepByStep) if (!stepByStep)
IOUtils.DeleteContentsOfDir(I.current.interpFolder); await IOUtils.DeleteContentsOfDirAsync(I.current.interpFolder);
} }
static async Task CopyOutputFrames(string framesPath, string framesFile, string outputFolderPath, bool dontMove) static async Task CopyOutputFrames(string framesPath, string framesFile, string outputFolderPath, bool dontMove)
{ {
IOUtils.TryDeleteIfExists(outputFolderPath); await IOUtils.TryDeleteIfExistsAsync(outputFolderPath);
IOUtils.CreateDir(outputFolderPath); IOUtils.CreateDir(outputFolderPath);
Stopwatch sw = new Stopwatch(); Stopwatch sw = new Stopwatch();
sw.Restart(); sw.Restart();

View File

@@ -242,11 +242,11 @@ namespace Flowframes
{ {
DialogResult dialogResult = MessageBox.Show($"Delete the temp folder (Yes) or keep it for resuming later (No)?", "Delete temporary files?", MessageBoxButtons.YesNo); DialogResult dialogResult = MessageBox.Show($"Delete the temp folder (Yes) or keep it for resuming later (No)?", "Delete temporary files?", MessageBoxButtons.YesNo);
if (dialogResult == DialogResult.Yes) if (dialogResult == DialogResult.Yes)
IOUtils.TryDeleteIfExists(current.tempFolder); Task.Run(async () => { await IOUtils.TryDeleteIfExistsAsync(current.tempFolder); });
} }
else else
{ {
IOUtils.TryDeleteIfExists(current.tempFolder); Task.Run(async () => { await IOUtils.TryDeleteIfExistsAsync(current.tempFolder); });
} }
} }
@@ -266,7 +266,7 @@ namespace Flowframes
Logger.Log("Deleting temporary files..."); Logger.Log("Deleting temporary files...");
try try
{ {
Directory.Delete(current.tempFolder, true); await Task.Run(async () => { Directory.Delete(current.tempFolder, true); });
} }
catch (Exception e) catch (Exception e)
{ {

View File

@@ -58,7 +58,7 @@ namespace Flowframes.Main
// if (Config.GetBool("scnDetect") && !current.inputIsFrames) // Input is video - extract frames first // if (Config.GetBool("scnDetect") && !current.inputIsFrames) // Input is video - extract frames first
// await ExtractSceneChanges(); // await ExtractSceneChanges();
if (!IOUtils.TryDeleteIfExists(current.framesFolder)) if (!(await IOUtils.TryDeleteIfExistsAsync(current.framesFolder)))
{ {
InterpolateUtils.ShowMessage("Failed to delete existing frames folder - Make sure no file is opened in another program!", "Error"); InterpolateUtils.ShowMessage("Failed to delete existing frames folder - Make sure no file is opened in another program!", "Error");
return; return;
@@ -81,7 +81,7 @@ namespace Flowframes.Main
InterpolateUtils.ShowMessage("There are no extracted frames that can be interpolated!\nDid you run the extraction step?", "Error"); InterpolateUtils.ShowMessage("There are no extracted frames that can be interpolated!\nDid you run the extraction step?", "Error");
return; return;
} }
if (!IOUtils.TryDeleteIfExists(current.interpFolder)) if (!(await IOUtils.TryDeleteIfExistsAsync(current.interpFolder)))
{ {
InterpolateUtils.ShowMessage("Failed to delete existing frames folder - Make sure no file is opened in another program!", "Error"); InterpolateUtils.ShowMessage("Failed to delete existing frames folder - Make sure no file is opened in another program!", "Error");
return; return;

View File

@@ -46,7 +46,7 @@ namespace Flowframes.Media
await RunFfmpeg(args, LogMode.Hidden); await RunFfmpeg(args, LogMode.Hidden);
if (deleteAlphaDir) if (deleteAlphaDir)
IOUtils.TryDeleteIfExists(alphaDir); await IOUtils.TryDeleteIfExistsAsync(alphaDir);
} }
} }
} }

View File

@@ -48,7 +48,7 @@ namespace Flowframes.Media
if (IOUtils.GetFilesize(outPath) < 512) if (IOUtils.GetFilesize(outPath) < 512)
{ {
Logger.Log($"Failed to extract audio stream #{track.streamIndex}, even with re-encoding. Will be missing from output."); Logger.Log($"Failed to extract audio stream #{track.streamIndex}, even with re-encoding. Will be missing from output.");
IOUtils.TryDeleteIfExists(outPath); await IOUtils.TryDeleteIfExistsAsync(outPath);
return; return;
} }
@@ -120,7 +120,7 @@ namespace Flowframes.Media
} }
else else
{ {
IOUtils.TryDeleteIfExists(outPath); // Delete if encode was not successful await IOUtils.TryDeleteIfExistsAsync(outPath); // Delete if encode was not successful
} }
} }
@@ -313,28 +313,6 @@ namespace Flowframes.Media
await RunFfmpeg(args, tempFolder, LogMode.Hidden); await RunFfmpeg(args, tempFolder, LogMode.Hidden);
// if (File.Exists(outPath) && IOUtils.GetFilesize(outPath) < 1024)
// {
// Logger.Log("Failed to merge audio losslessly! Trying to re-encode.", false, false, "ffmpeg");
//
// args = $" -i {inName} -stream_loop {looptimes} -i {audioName.Wrap()}" +
// $"{trackInputArgs} -map 0:v -map 1:a {trackMapArgs} -c:v copy {Utils.GetAudioFallbackArgs(Path.GetExtension(inputFile))} -c:s {subCodec} {trackMetaArgs} -shortest {outName}";
//
// await RunFfmpeg(args, tempFolder, LogMode.Hidden);
//
// if (File.Exists(outPath) && IOUtils.GetFilesize(outPath) < 1024)
// {
// Logger.Log("Failed to merge audio, even with re-encoding. Output will not have audio.", false, false, "ffmpeg");
// IOUtils.TryMove(tempPath, inputFile); // Move temp file back
// IOUtils.TryDeleteIfExists(tempPath);
// return;
// }
//
// string audioExt = Path.GetExtension(audioPath).Remove(".").ToUpper();
// Logger.Log($"Source audio ({audioExt}) has been re-encoded to fit into the target container ({containerExt.Remove(".").ToUpper()}). This may decrease the quality slightly.", false, true, "ffmpeg");
// }
if (File.Exists(outPath) && IOUtils.GetFilesize(outPath) > 512) if (File.Exists(outPath) && IOUtils.GetFilesize(outPath) > 512)
{ {
File.Delete(tempPath); File.Delete(tempPath);

View File

@@ -291,7 +291,7 @@ namespace Flowframes
string lastInterpPath = outPath + $"-run{iteration - 1}"; string lastInterpPath = outPath + $"-run{iteration - 1}";
Directory.Move(outPath, lastInterpPath); // Rename last interp folder Directory.Move(outPath, lastInterpPath); // Rename last interp folder
await RunRifeNcnnProcess(lastInterpPath, outPath, mdl); await RunRifeNcnnProcess(lastInterpPath, outPath, mdl);
IOUtils.TryDeleteIfExists(lastInterpPath); await IOUtils.TryDeleteIfExistsAsync(lastInterpPath);
} }
else else
{ {