Beispiel #1
0
        static async Task DeleteOldFramesAsync(string interpFramesPath, List <int> frameLinesToEncode)
        {
            if (debug)
            {
                Logger.Log("[AE] Starting DeleteOldFramesAsync.", true, false, "ffmpeg");
            }

            Stopwatch sw = new Stopwatch();

            sw.Restart();

            foreach (int frame in frameLinesToEncode)
            {
                if (!FrameIsStillNeeded(interpFramesLines[frame], frame))    // Make sure frames are no longer needed (for dupes) before deleting!
                {
                    string framePath = Path.Combine(interpFramesPath, interpFramesLines[frame]);
                    //IOUtils.OverwriteFileWithText(framePath);    // Overwrite to save space without breaking progress counter
                    IoUtils.TryDeleteIfExists(framePath);
                    InterpolationProgress.deletedFramesCount++;
                }
            }

            if (debug)
            {
                Logger.Log("[AE] DeleteOldFramesAsync finished in " + FormatUtils.TimeSw(sw), true, false, "ffmpeg");
            }
        }
Beispiel #2
0
        private static void BuildIcon(string filePath, int width, int height, byte[] imageBytes, int imageWidth,
                                      int imageHeight, int imageX, int imageY)
        {
            IoUtils.ForceDelete(filePath);
            using (var fs = new FileStream(filePath, FileMode.Create))
            {
                var outputBitmap = new Bitmap(width, height);

                var tempImage = ImageUtils.ByteArrayToImage(imageBytes);
                tempImage = ImageUtils.ScaleImage(tempImage, imageWidth, imageHeight);

                using (var graphics = Graphics.FromImage(outputBitmap))
                {
                    graphics.CompositingMode    = CompositingMode.SourceCopy;
                    graphics.CompositingQuality = CompositingQuality.HighQuality;
                    graphics.InterpolationMode  = InterpolationMode.HighQualityBicubic;
                    graphics.SmoothingMode      = SmoothingMode.HighQuality;
                    graphics.PixelOffsetMode    = PixelOffsetMode.HighQuality;
                    graphics.DrawImage(tempImage,
                                       new PointF(imageX, imageY));
                }

                outputBitmap.Save(fs, ImageFormat.Png);
                outputBitmap.Dispose();
                tempImage.Dispose();
            }
        }
        public static async Task CopyLastFrame(int lastFrameNum)
        {
            if (I.canceled)
            {
                return;
            }

            try
            {
                lastFrameNum--;     // We have to do this as extracted frames start at 0, not 1
                bool   frameFolderInput = IoUtils.IsPathDirectory(I.current.inPath);
                string targetPath       = Path.Combine(I.current.framesFolder, lastFrameNum.ToString().PadLeft(Padding.inputFrames, '0') + I.current.framesExt);
                if (File.Exists(targetPath))
                {
                    return;
                }

                Size res = IoUtils.GetImage(IoUtils.GetFilesSorted(I.current.framesFolder, false).First()).Size;

                if (frameFolderInput)
                {
                    string lastFramePath = IoUtils.GetFilesSorted(I.current.inPath, false).Last();
                    await FfmpegExtract.ExtractLastFrame(lastFramePath, targetPath, res);
                }
                else
                {
                    await FfmpegExtract.ExtractLastFrame(I.current.inPath, targetPath, res);
                }
            }
            catch (Exception e)
            {
                Logger.Log("CopyLastFrame Error: " + e.Message);
            }
        }
Beispiel #4
0
        public static async Task ExtractFrames(string inPath, string outPath, bool alpha)
        {
            if (canceled)
            {
                return;
            }
            Program.mainForm.SetStatus("Extracting frames from video...");
            current.RefreshExtensions(InterpSettings.FrameType.Import);
            bool mpdecimate = Config.GetInt(Config.Key.dedupMode) == 2;
            Size res        = await Utils.GetOutputResolution(inPath, true, true);

            await FfmpegExtract.VideoToFrames(inPath, outPath, alpha, current.inFpsDetected, mpdecimate, false, res, current.framesExt);

            if (mpdecimate)
            {
                int    framesLeft     = IoUtils.GetAmountOfFiles(outPath, false, "*" + current.framesExt);
                int    framesDeleted  = currentInputFrameCount - framesLeft;
                float  percentDeleted = ((float)framesDeleted / currentInputFrameCount) * 100f;
                string keptPercent    = $"{(100f - percentDeleted).ToString("0.0")}%";

                if (QuickSettingsTab.trimEnabled)
                {
                    Logger.Log($"Deduplication: Kept {framesLeft} frames.");
                }
                else
                {
                    Logger.Log($"Deduplication: Kept {framesLeft} ({keptPercent}) frames, deleted {framesDeleted} frames.");
                }
            }

            if (!Config.GetBool("allowConsecutiveSceneChanges", true))
            {
                Utils.FixConsecutiveSceneFrames(Path.Combine(current.tempFolder, Paths.scenesDir), current.framesFolder);
            }
        }
Beispiel #5
0
 internal static void getPngsToRoot(string currentPath, string root)
 {
     try {
         List <string> queue = new List <string>();
         string[]      dirs  = Directory.GetDirectories(currentPath);
         foreach (string dir in dirs)
         {
             CustomKnight.Instance.Log("Looking in" + dir);
             if (dirHasPng(dir, SearchOption.TopDirectoryOnly))
             {
                 IoUtils.DirectoryCopyAllFiles(dir, root);
             }
             else if (dirHasPng(dir, SearchOption.AllDirectories))
             {
                 queue.Add(dir);
             }
         }
         foreach (string dir in queue)
         {
             getPngsToRoot(dir, root);
         }
     } catch (Exception e) {
         CustomKnight.Instance.Log("The Skin could not be fixed : " + e.ToString());
     }
 }
        public void SetUp()
        {
            _testRoot = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
            Directory.CreateDirectory(_testRoot);

            _sut = new IoUtils();
        }
        public static void UpdateInterpProgress(int frames, int target, string latestFramePath = "")
        {
            if (I.canceled)
            {
                return;
            }
            interpolatedInputFramesCount = ((frames / I.current.interpFactor).RoundToInt() - 1);
            //ResumeUtils.Save();
            frames = frames.Clamp(0, target);
            int percent = (int)Math.Round(((float)frames / target) * 100f);

            Program.mainForm.SetProgress(percent);

            float  generousTime = ((AiProcess.processTime.ElapsedMilliseconds - AiProcess.lastStartupTimeMs) / 1000f);
            float  fps          = ((float)frames / generousTime).Clamp(0, 9999);
            string fpsIn        = (fps / currentFactor).ToString("0.00");
            string fpsOut       = fps.ToString("0.00");

            if (fps > peakFpsOut)
            {
                peakFpsOut = fps;
            }

            float  secondsPerFrame = generousTime / (float)frames;
            int    framesLeft      = target - frames;
            float  eta             = framesLeft * secondsPerFrame;
            string etaStr          = FormatUtils.Time(new TimeSpan(0, 0, eta.RoundToInt()), false);

            bool replaceLine = Regex.Split(Logger.textbox.Text, "\r\n|\r|\n").Last().Contains("Average Speed: ");

            string logStr = $"Interpolated {frames}/{target} Frames ({percent}%) - Average Speed: {fpsIn} FPS In / {fpsOut} FPS Out - ";

            logStr += $"Time: {FormatUtils.Time(AiProcess.processTime.Elapsed)} - ETA: {etaStr}";
            if (AutoEncode.busy)
            {
                logStr += " - Encoding...";
            }
            Logger.Log(logStr, false, replaceLine);

            try
            {
                if (!string.IsNullOrWhiteSpace(latestFramePath) && frames > currentFactor)
                {
                    if (bigPreviewForm == null && !preview.Visible /* ||Program.mainForm.WindowState != FormWindowState.Minimized */ /* || !Program.mainForm.IsInFocus()*/)
                    {
                        return;                                                                                                                                                             // Skip if the preview is not visible or the form is not in focus
                    }
                    if (timeSinceLastPreviewUpdate.IsRunning && timeSinceLastPreviewUpdate.ElapsedMilliseconds < previewUpdateRateMs)
                    {
                        return;
                    }
                    Image img = IoUtils.GetImage(latestFramePath, false, false);
                    SetPreviewImg(img);
                }
            }
            catch (Exception e)
            {
                //Logger.Log("Error updating preview: " + e.Message, true);
            }
        }
Beispiel #8
0
        static void CheckExistingFolder(string inpath, string outpath)
        {
            if (Interpolate.current == null || !Interpolate.current.stepByStep)
            {
                return;
            }
            string tmpFolder = InterpolateUtils.GetTempFolderLoc(inpath, outpath);

            if (Directory.Exists(tmpFolder))
            {
                int    scnFrmAmount    = IoUtils.GetAmountOfFiles(Path.Combine(tmpFolder, Paths.scenesDir), false, "*" + Interpolate.current.interpExt); // TODO: Make this work if the frames extension was changed
                string scnFrames       = scnFrmAmount > 0 ? $"{scnFrmAmount} scene frames" : "no scene frames";
                int    srcFrmAmount    = IoUtils.GetAmountOfFiles(Path.Combine(tmpFolder, Paths.framesDir), false, "*" + Interpolate.current.interpExt);
                string srcFrames       = srcFrmAmount > 1 ? $"{srcFrmAmount} source frames" : "no source frames";
                int    interpFrmAmount = IoUtils.GetAmountOfFiles(Path.Combine(tmpFolder, Paths.interpDir), false);
                string interpFrames    = interpFrmAmount > 2 ? $"{interpFrmAmount} interpolated frames" : "no interpolated frames";
                string msg             = $"A temporary folder for this video already exists. It contains {scnFrames}, {srcFrames}, {interpFrames}.";

                DialogResult dialogResult = MessageBox.Show($"{msg}\n\nClick \"Yes\" to use the existing files or \"No\" to delete them.", "Use files from existing temp folder?", MessageBoxButtons.YesNo);
                if (dialogResult == DialogResult.No)
                {
                    IoUtils.TryDeleteIfExists(tmpFolder);
                    Logger.Log("Deleted old temp folder.");
                }
            }
        }
Beispiel #9
0
        public static string[] importFilenames;   // index=renamed, value=original TODO: Store on disk instead for crashes?

        public static async Task Rename()
        {
            importFilenames = IoUtils.GetFilesSorted(Interpolate.current.framesFolder).Select(x => Path.GetFileName(x)).ToArray();
            await IoUtils.RenameCounterDir(Interpolate.current.framesFolder, 0, Padding.inputFramesRenamed);

            framesAreRenamed = true;
        }
Beispiel #10
0
        public static async Task ImportImages(string inPath, string outPath, bool alpha, Size size, bool showLog, string format)
        {
            if (showLog)
            {
                Logger.Log($"Importing images from {new DirectoryInfo(inPath).Name}...");
            }
            Logger.Log($"ImportImages() - Alpha: {alpha} - Size: {size} - Format: {format}", true, false, "ffmpeg");
            IoUtils.CreateDir(outPath);
            string concatFile = Path.Combine(Paths.GetDataPath(), "import-concat-temp.ini");

            FfmpegUtils.CreateConcatFile(inPath, concatFile, Filetypes.imagesInterpCompat);

            string inArg    = $"-f concat -safe 0 -i {concatFile.Wrap()}";
            string linksDir = Path.Combine(concatFile + Paths.symlinksSuffix);

            if (Config.GetBool(Config.Key.allowSymlinkEncoding, true) && Symlinks.SymlinksAllowed())
            {
                if (await Symlinks.MakeSymlinksForEncode(concatFile, linksDir, Padding.interpFrames))
                {
                    inArg = $"-i \"{linksDir}/%{Padding.interpFrames}d{FfmpegEncode.GetConcatFileExt(concatFile)}\"";
                }
            }

            string  sizeStr = (size.Width > 1 && size.Height > 1) ? $"-s {size.Width}x{size.Height}" : "";
            string  vf      = $"-vf {GetPadFilter()}";
            string  args    = $"-r 25 {inArg} {GetImgArgs(format, true, alpha)} {sizeStr} -vsync 0 -start_number 0 {vf} \"{outPath}/%{Padding.inputFrames}d{format}\"";
            LogMode logMode = IoUtils.GetAmountOfFiles(inPath, false) > 50 ? LogMode.OnlyLastLine : LogMode.Hidden;

            await RunFfmpeg(args, logMode, "panic");
        }
Beispiel #11
0
        public static async Task VideoToFrames(string inputFile, string framesDir, bool alpha, Fraction rate, bool deDupe, bool delSrc, Size size, string format)
        {
            Logger.Log("Extracting video frames from input video...");
            Logger.Log($"VideoToFrames() - Alpha: {alpha} - Rate: {rate} - Size: {size} - Format: {format}", true, false, "ffmpeg");
            string sizeStr = (size.Width > 1 && size.Height > 1) ? $"-s {size.Width}x{size.Height}" : "";

            IoUtils.CreateDir(framesDir);
            string  mpStr   = deDupe ? ((Config.GetInt(Config.Key.mpdecimateMode) == 0) ? mpDecDef : mpDecAggr) : "";
            string  filters = FormatUtils.ConcatStrings(new[] { GetPadFilter(), mpStr });
            string  vf      = filters.Length > 2 ? $"-vf {filters}" : "";
            string  rateArg = (rate.GetFloat() > 0) ? $" -r {rate}" : "";
            string  args    = $"{GetTrimArg(true)} -i {inputFile.Wrap()} {GetImgArgs(format, true, alpha)} -vsync 0 {rateArg} -frame_pts 1 {vf} {sizeStr} {GetTrimArg(false)} \"{framesDir}/%{Padding.inputFrames}d{format}\"";
            LogMode logMode = await Interpolate.GetCurrentInputFrameCount() > 50 ? LogMode.OnlyLastLine : LogMode.Hidden;

            await RunFfmpeg(args, logMode, true);

            int amount = IoUtils.GetAmountOfFiles(framesDir, false, "*" + format);

            Logger.Log($"Extracted {amount} {(amount == 1 ? "frame" : "frames")} from input.", false, true);
            await Task.Delay(1);

            if (delSrc)
            {
                DeleteSource(inputFile);
            }
        }
Beispiel #12
0
        public static async Task ExtractSceneChanges(string inPath, string outDir, Fraction rate, bool inputIsFrames, string format)
        {
            Logger.Log("Extracting scene changes...");
            Directory.CreateDirectory(outDir);

            string inArg = $"-i {inPath.Wrap()}";

            if (inputIsFrames)
            {
                string concatFile = Path.Combine(Paths.GetDataPath(), "png-scndetect-concat-temp.ini");
                FfmpegUtils.CreateConcatFile(inPath, concatFile, Filetypes.imagesInterpCompat);
                inArg = $"-f concat -safe 0 -i {concatFile.Wrap()}";
            }

            string scnDetect = $"-vf \"select='gt(scene,{Config.GetFloatString(Config.Key.scnDetectValue)})'\"";
            string rateArg   = (rate.GetFloat() > 0) ? $"-r {rate}" : "";
            string args      = $"-vsync 0 {GetTrimArg(true)} {inArg} {GetImgArgs(format)} {rateArg} {scnDetect} -frame_pts 1 -s 256x144 {GetTrimArg(false)} \"{outDir}/%{Padding.inputFrames}d{format}\"";

            LogMode logMode = await Interpolate.GetCurrentInputFrameCount() > 50 ? LogMode.OnlyLastLine : LogMode.Hidden;

            await RunFfmpeg(args, logMode, inputIsFrames? "panic" : "warning", true);

            bool hiddenLog = await Interpolate.GetCurrentInputFrameCount() <= 50;

            int amount = IoUtils.GetAmountOfFiles(outDir, false);

            Logger.Log($"Detected {amount} scene {(amount == 1 ? "change" : "changes")}.".Replace(" 0 ", " no "), false, !hiddenLog);
        }
Beispiel #13
0
        public static async Task CopyImages(string inpath, string outpath, bool showLog)
        {
            if (showLog)
            {
                Logger.Log($"Loading images from {new DirectoryInfo(inpath).Name}...");
            }
            Directory.CreateDirectory(outpath);

            Dictionary <string, string> moveFromTo = new Dictionary <string, string>();
            int counter = 0;

            foreach (FileInfo file in IoUtils.GetFileInfosSorted(inpath))
            {
                string newFilename = counter.ToString().PadLeft(Padding.inputFrames, '0') + file.Extension;
                moveFromTo.Add(file.FullName, Path.Combine(outpath, newFilename));
                counter++;
            }

            if (Config.GetBool(Config.Key.allowSymlinkEncoding) && Config.GetBool(Config.Key.allowSymlinkImport, true))
            {
                Logger.Log($"Symlink Import enabled, creating symlinks for input frames...", true);
                Dictionary <string, string> moveFromToSwapped = moveFromTo.ToDictionary(x => x.Value, x => x.Key);   // From/To => To/From (Link/Target)
                await Symlinks.CreateSymlinksParallel(moveFromToSwapped);
            }
            else
            {
                Logger.Log($"Symlink Import disabled, copying input frames...", true);
                await Task.Run(async() => {
                    foreach (KeyValuePair <string, string> moveFromToPair in moveFromTo)
                    {
                        File.Copy(moveFromToPair.Key, moveFromToPair.Value);
                    }
                });
            }
        }
Beispiel #14
0
        static async Task CopyOutputFrames(string framesPath, string framesFile, string outputFolderPath, int startNo, bool dontMove, bool hideLog)
        {
            IoUtils.CreateDir(outputFolderPath);
            Stopwatch sw = new Stopwatch();

            sw.Restart();

            string[] framesLines = IoUtils.ReadLines(framesFile);

            for (int idx = 1; idx <= framesLines.Length; idx++)
            {
                string line        = framesLines[idx - 1];
                string inFilename  = line.RemoveComments().Split('/').Last().Remove("'").Trim();
                string framePath   = Path.Combine(framesPath, inFilename);
                string outFilename = Path.Combine(outputFolderPath, startNo.ToString().PadLeft(Padding.interpFrames, '0')) + Path.GetExtension(framePath);
                startNo++;

                if (dontMove || ((idx < framesLines.Length) && framesLines[idx].Contains(inFilename)))   // If file is re-used in the next line, copy instead of move
                {
                    File.Copy(framePath, outFilename);
                }
                else
                {
                    File.Move(framePath, outFilename);
                }

                if (sw.ElapsedMilliseconds >= 500 || idx == framesLines.Length)
                {
                    sw.Restart();
                    Logger.Log($"Moving output frames... {idx}/{framesLines.Length}", hideLog, true);
                    await Task.Delay(1);
                }
            }
        }
Beispiel #15
0
        public virtual Uri Write(Stream source, Uri sink)
        {
            if (sink == null)
            {
                throw new ArgumentException("Uri must not be null");
            }

            if (IoMode.HasFlag(IO.IoMode.Write) && sink.IsFile)
            {
                var filename   = IoUtils.UriToFileName(sink);
                var file       = new FileStream(filename, FileMode.Create);
                var target     = new BufferedStream(file);
                var bufferSize = 1024 * 1024;
                var buffer     = new byte[bufferSize];
                var oldPos     = source.Position;
                int readByte   = 0;
                int position   = 0;

                long endpos = source.Length - 1;
                while (position < endpos)
                {
                    readByte = source.Read(buffer, 0, bufferSize);
                    target.Write(buffer, 0, readByte);
                    position += readByte;
                }

                target.Flush();
                target.Close();
                source.Position = oldPos;
            }
            return(sink);
        }
Beispiel #16
0
        public static async Task FramesToFrames(string framesFile, string outDir, int startNo, Fraction fps, Fraction resampleFps, string format = "png", int lossyQ = 1, LogMode logMode = LogMode.OnlyLastLine)
        {
            Directory.CreateDirectory(outDir);
            string inArg    = $"-f concat -i {Path.GetFileName(framesFile)}";
            string linksDir = Path.Combine(framesFile + Paths.symlinksSuffix);

            format = format.ToLower();

            if (Config.GetBool(Config.Key.allowSymlinkEncoding, true) && Symlinks.SymlinksAllowed())
            {
                if (await Symlinks.MakeSymlinksForEncode(framesFile, linksDir, Padding.interpFrames))
                {
                    inArg = $"-i {Path.GetFileName(framesFile) + Paths.symlinksSuffix}/%{Padding.interpFrames}d{GetConcatFileExt(framesFile)}";
                }
            }

            string sn          = $"-start_number {startNo}";
            string rate        = fps.ToString().Replace(",", ".");
            string vf          = (resampleFps.GetFloat() < 0.1f) ? "" : $"-vf fps=fps={resampleFps}";
            string compression = format == "png" ? pngCompr : $"-q:v {lossyQ}";
            string codec       = format == "webp" ? "-c:v libwebp" : ""; // Specify libwebp to avoid putting all frames into single animated WEBP
            string args        = $"-vsync 0 -r {rate} {inArg} {codec} {compression} {sn} {vf} \"{outDir}/%{Padding.interpFrames}d.{format}\"";

            await RunFfmpeg(args, framesFile.GetParentDir(), logMode, "error", true);

            IoUtils.TryDeleteIfExists(linksDir);
        }
Beispiel #17
0
        public static void CheckOs()
        {
            if (!File.Exists(Paths.GetVerPath()) && Paths.GetExeDir().ToLower().Contains("temp"))
            {
                MessageBox.Show("You seem to be running Flowframes out of an archive.\nPlease extract the whole archive first!", "Error");
                IoUtils.TryDeleteIfExists(Paths.GetDataPath());
                Application.Exit();
            }

            string[] osInfo  = OsUtils.TryGetOs().Split(" | ");
            string   version = osInfo[0].Remove("Microsoft").Trim();

            if (Is32Bit() && !Config.GetBool("allow32Bit", false))
            {
                MessageBox.Show("This application is not compatible with 32 bit operating systems!", "Error");
                Application.Exit();
            }

            if (string.IsNullOrWhiteSpace(version))
            {
                return;
            }

            if (!version.ToLower().Contains("windows 10") && !version.ToLower().Contains("windows 11") && !Config.GetBool("ignoreIncompatibleOs", false))
            {
                MessageBox.Show($"This application was made for Windows 10/11 and is not officially compatible with {version}.\n\n" +
                                $"Use it at your own risk and do NOT ask for support as long as your are on {version}.", "Warning");
            }
        }
Beispiel #18
0
        /// <summary>
        ///     Recursively resolve all schemas. All references to external schemas must have .json extension.
        ///     This is done by:
        ///         1. Scanning the schema for $ref attributes.
        ///         2. Attempting to construct a Uri object to represent the reference.
        ///         3. Passing it into a resolver to create a network of schemas.
        ///         4. Modifying the original schema's $ref attributes with the full, unique Uri.
        ///         5. Setting the id of the referenced schemas to its full, unique Uri.
        /// </summary>
        /// <param name="parent">Path to the parent file.</param>
        /// <param name="current">Path to the current file.</param>
        /// <returns>An extended wrapper for the JsonSchema.</returns>
        /// TODO check if parent is needed - right now it assumes parent for all children
        private JsonSchemaWrapper ResolveSchemaHelper(Uri parent, Uri current)
        {
            var uri  = IoUtils.GetAbsoluteUri(parent, current, true);
            var data = IoUtils.ReadFromPath(uri);

            return(ResolveSchemaHelper(uri, parent, data));
        }
Beispiel #19
0
        static async Task DeleteNcnnDupes(string dir, float factor)
        {
            int dupeCount = InterpolateUtils.GetRoundedInterpFramesPerInputFrame(factor);
            var files     = IoUtils.GetFileInfosSorted(dir, false).Reverse().Take(dupeCount).ToList();

            Logger.Log($"DeleteNcnnDupes: Calculated dupe count from factor; deleting last {dupeCount} interp frames of {IoUtils.GetAmountOfFiles(dir, false)} ({string.Join(", ", files.Select(x => x.Name))})", true);

            int attempts = 4;

            while (attempts > 0)
            {
                try
                {
                    files.ForEach(x => x.Delete());
                    break;
                }
                catch (Exception ex)
                {
                    attempts--;

                    if (attempts < 1)
                    {
                        Logger.Log($"DeleteNcnnDupes Error: {ex.Message}", true);
                        break;
                    }
                    else
                    {
                        await Task.Delay(500);
                    }
                }
            }
        }
Beispiel #20
0
        static async Task RunEntry(InterpSettings entry)
        {
            SetBusy(true);
            Program.mainForm.SetWorking(true);

            if (!EntryIsValid(entry))
            {
                Logger.Log("Queue: Skipping entry because it's invalid.");
                Program.batchQueue.Dequeue();
                return;
            }

            string fname = Path.GetFileName(entry.inPath);

            if (IoUtils.IsPathDirectory(entry.inPath))
            {
                fname = Path.GetDirectoryName(entry.inPath);
            }
            Logger.Log($"Queue: Processing {fname} ({entry.interpFactor}x {entry.ai.aiNameShort}).");

            Program.mainForm.LoadBatchEntry(entry);     // Load entry into GUI
            Interpolate.current = entry;
            Program.mainForm.runBtn_Click(null, null);

            while (Program.busy)
            {
                await Task.Delay(500);
            }

            Program.batchQueue.Dequeue();
            Program.mainForm.SetWorking(false);
            Logger.Log($"Queue: Done processing {fname} ({entry.interpFactor}x {entry.ai.aiNameShort}).");
        }
        public static async Task DeleteInterpolatedInputFrames()
        {
            interpolatedInputFramesCount = 0;
            string[] inputFrames = IoUtils.GetFilesSorted(I.current.framesFolder);

            for (int i = 0; i < inputFrames.Length; i++)
            {
                while (Program.busy && (i + 10) > interpolatedInputFramesCount)
                {
                    await Task.Delay(1000);
                }
                if (!Program.busy)
                {
                    break;
                }

                if (i != 0 && i != inputFrames.Length - 1)
                {
                    IoUtils.OverwriteFileWithText(inputFrames[i]);
                }

                if (i % 10 == 0)
                {
                    await Task.Delay(10);
                }
            }
        }
        /// <summary>
        ///     Generate C# code.
        /// </summary>
        private void Generate()
        {
            var generatedCode = GenerateHelper();

            // Create directory to generate files
            if (!_configuration.Verbose)
            {
                IoUtils.CreateDirectoryFromNamespace(_configuration.OutputDirectory, _configuration.Namespace);
            }

            foreach (var entry in generatedCode)
            {
                if (!_configuration.Verbose)
                {
                    string saveLoc = _configuration.OutputDirectory + @"\" + entry.Key.Namespace.Replace('.', '\\') + @"\" + entry.Key.Schema.Title +
                                     ".cs";
                    IoUtils.GenerateFile(entry.Value, saveLoc);
                    Console.WriteLine("Wrote " + saveLoc);
                }
                else
                {
                    Console.WriteLine(entry.Value);
                }
            }
        }
Beispiel #23
0
        public static void FillLogDropdown(ComboBox dd)
        {
            int oldIndex = dd.SelectedIndex;

            dd.Items.Clear();

            FileInfo[] logFiles = IoUtils.GetFileInfosSorted(Paths.GetLogPath(), false, "*.txt");

            foreach (FileInfo file in logFiles)
            {
                dd.Items.Add(file.Name);
            }

            if (oldIndex < 0)
            {
                if (dd.Items.Count > 0)
                {
                    dd.SelectedIndex = 0;
                }

                for (int i = 0; i < dd.Items.Count; i++)
                {
                    if (((string)dd.Items[i]).Split('.').FirstOrDefault() == Logger.defaultLogName)
                    {
                        dd.SelectedIndex = i;
                    }
                }
            }
            else
            {
                dd.SelectedIndex = oldIndex;
            }
        }
Beispiel #24
0
        public static async Task CreateOutputVid()
        {
            if (IoUtils.GetAmountOfFiles(current.interpFolder, false) < 2)
            {
                if (Config.GetBool(Config.Key.sbsRunPreviousStepIfNeeded))
                {
                    Logger.Log($"There are no interpolated frames to export - Running interpolation step first...");
                    await InterpolateStep();
                }

                if (IoUtils.GetAmountOfFiles(current.interpFolder, false) < 2)
                {
                    Cancel($"There are no interpolated frames to encode!\n\nDid you delete the folder?");
                    return;
                }
            }

            if (!(await InterpolateUtils.CheckEncoderValid()))
            {
                return;
            }

            string[] outFrames = IoUtils.GetFilesSorted(current.interpFolder, current.interpExt);

            if (outFrames.Length > 0 && !IoUtils.CheckImageValid(outFrames[0]))
            {
                UiUtils.ShowMessageBox("Invalid frame files detected!\n\nIf you used Auto-Encode, this is normal, and you don't need to run " +
                                       "this step as the video was already created in the \"Interpolate\" step.", UiUtils.MessageType.Error);
                return;
            }

            await Export.ExportFrames(current.interpFolder, current.outPath, current.outMode, true);
        }
Beispiel #25
0
        private void BuildFilesAndFolders()
        {
            var xNamespace = XNamespace.Get("http://www.w3.org/2001/XMLSchema-instance");

            var xDoc = new XDocument(
                new XElement("Application",
                             new XAttribute(XNamespace.Xmlns + "xsi", xNamespace),
                             new XAttribute("GeneratedByTileIconifier", true),
                             new XElement("VisualElements",
                                          new XAttribute("ShowNameOnSquare150x150Logo",
                                                         _shortcutItem.Properties.CurrentState.ShowNameOnSquare150X150Logo ? "on" : "off"),
                                          new XAttribute("Square150x150Logo", _shortcutItem.RelativeMediumIconPath),
                                          new XAttribute("Square70x70Logo", _shortcutItem.RelativeSmallIconPath),
                                          new XAttribute("ForegroundText", _shortcutItem.Properties.CurrentState.ForegroundText),
                                          new XAttribute("BackgroundColor", _shortcutItem.Properties.CurrentState.BackgroundColor)
                                          )));

            if (!Directory.Exists(_shortcutItem.VisualElementsPath))
            {
                Directory.CreateDirectory(_shortcutItem.VisualElementsPath);
            }

            IoUtils.FileActionRetainingAttributes(_shortcutItem.VisualElementManifestPath,
                                                  () => xDoc.Save(_shortcutItem.VisualElementManifestPath));
        }
Beispiel #26
0
        public static async Task Convert(string dir, MagickFormat format, int quality, string ext = "", bool print = true, bool setProgress = true)
        {
            var files = IoUtils.GetFilesSorted(dir);

            if (print)
            {
                Logger.Log($"Converting {files.Length} files in {dir}");
            }
            int counter = 0;

            foreach (string file in files)
            {
                if (print)
                {
                    Logger.Log("Converting " + Path.GetFileName(file) + " to " + format.ToString().StripNumbers().ToUpper(), false, true);
                }
                MagickImage img = new MagickImage(file);
                img.Format  = format;
                img.Quality = quality;
                string outpath = file;
                if (!string.IsNullOrWhiteSpace(ext))
                {
                    outpath = Path.ChangeExtension(outpath, ext);
                }
                img.Write(outpath);
                counter++;
                if (setProgress)
                {
                    Program.mainForm.SetProgress((int)Math.Round(((float)counter / files.Length) * 100f));
                }
                await Task.Delay(1);
            }
        }
Beispiel #27
0
        public static bool CheckAiAvailable(AI ai, ModelCollection.ModelInfo model)
        {
            if (IoUtils.GetAmountOfFiles(Path.Combine(Paths.GetPkgPath(), ai.pkgDir), true) < 1)
            {
                UiUtils.ShowMessageBox("The selected AI is not installed!", UiUtils.MessageType.Error);
                I.Cancel("Selected AI not available.", true);
                return(false);
            }

            if (model == null || model.dir.Trim() == "")
            {
                UiUtils.ShowMessageBox("No valid AI model has been selected!", UiUtils.MessageType.Error);
                I.Cancel("No valid model selected.", true);
                return(false);
            }

            if (I.current.ai.aiName.ToUpper().Contains("CUDA") && NvApi.gpuList.Count < 1)
            {
                UiUtils.ShowMessageBox("Warning: No Nvidia GPU was detected. CUDA might fall back to CPU!\n\nTry an NCNN implementation instead if you don't have an Nvidia GPU.", UiUtils.MessageType.Error);

                if (!Config.GetBool("allowCudaWithoutDetectedGpu", true))
                {
                    I.Cancel("No CUDA-capable graphics card available.", true);
                    return(false);
                }
            }

            return(true);
        }
Beispiel #28
0
        public static async Task CreateDupesFile(string framesPath, int lastFrameNum, string ext)
        {
            bool   debug       = Config.GetBool("dupeScanDebug", false);
            string infoFile    = Path.Combine(framesPath.GetParentDir(), "dupes.ini");
            string fileContent = "";

            FileInfo[] frameFiles = IoUtils.GetFileInfosSorted(framesPath, false, "*" + ext);

            if (debug)
            {
                Logger.Log($"Running CreateDupesFile for '{framesPath}' ({frameFiles.Length} files), lastFrameNum = {lastFrameNum}, ext = {ext}.", true, false, "dupes");
            }

            for (int i = 0; i < frameFiles.Length; i++)
            {
                bool isLastItem = (i + 1) == frameFiles.Length;

                int frameNum1 = frameFiles[i].Name.GetInt();
                int frameNum2 = isLastItem ? lastFrameNum : frameFiles[i + 1].Name.GetInt();

                int diff  = frameNum2 - frameNum1;
                int dupes = diff - 1;

                if (debug)
                {
                    Logger.Log($"{(isLastItem ? "[isLastItem] " : "")}frameNum1 (frameFiles[{i}]) = {frameNum1}, frameNum2 (frameFiles[{i+1}]) = {frameNum2} => dupes = {dupes}", true, false, "dupes");
                }

                fileContent += $"{Path.GetFileNameWithoutExtension(frameFiles[i].Name)}:{dupes}\n";
            }

            File.WriteAllText(infoFile, fileContent);
        }
Beispiel #29
0
        public static string GetTempFolderLoc(string inPath, string outPath)
        {
            string basePath = inPath.GetParentDir();

            if (Config.GetInt(Config.Key.tempFolderLoc) == 1)
            {
                basePath = outPath.GetParentDir();
            }

            if (Config.GetInt(Config.Key.tempFolderLoc) == 2)
            {
                basePath = outPath;
            }

            if (Config.GetInt(Config.Key.tempFolderLoc) == 3)
            {
                basePath = Paths.GetExeDir();
            }

            if (Config.GetInt(Config.Key.tempFolderLoc) == 4)
            {
                string custPath = Config.Get(Config.Key.tempDirCustom);
                if (IoUtils.IsDirValid(custPath))
                {
                    basePath = custPath;
                }
            }

            return(Path.Combine(basePath, Path.GetFileNameWithoutExtension(inPath).StripBadChars().Remove(" ").Trunc(30, false) + "-temp"));
        }
Beispiel #30
0
        public void ReadThingGraphCursor(IGraphScene <IVisual, IVisualEdge> scene)
        {
            try {
                DefaultDialogValues(OpenFileDialog, ThingGraphCursorIoManager.ReadFilter);
                if (scene != null && scene.HasThingGraph())
                {
                    if (FileDialogShow(OpenFileDialog, true) == DialogResult.Ok)
                    {
                        var graphCursor = new GraphCursor <IThing, ILink>(scene.Graph.Source <IVisual, IVisualEdge, IThing, ILink>().Source);
                        var uri         = IoUtils.UriFromFileName(OpenFileDialog.FileName);
                        ThingGraphCursorIoManager.ConfigureSinkIo = s => ConfigureSink(s);

                        graphCursor = ThingGraphCursorIoManager.ReadSink(uri, graphCursor);
                        if (graphCursor != null)
                        {
                            Registry.Create <ISceneViz <IVisual, IThing, IVisualEdge, ILink> > ()
                            .SetDescription(scene, graphCursor.Cursor, OpenFileDialog.FileName);
                        }
                        OpenFileDialog.ResetFileName();
                    }
                }
            } catch (Exception ex) {
                Registry.Pooled <IExceptionHandler>().Catch(ex, MessageType.OK);
            }
        }