Пример #1
0
        public static async Task ChunksToVideo(string tempFolder, string chunksFolder, string baseOutPath, bool isBackup = false)
        {
            if (IoUtils.GetAmountOfFiles(chunksFolder, true, "*" + FfmpegUtils.GetExt(I.current.outMode)) < 1)
            {
                I.Cancel("No video chunks found - An error must have occured during chunk encoding!", AiProcess.hasShownError);
                return;
            }

            NmkdStopwatch sw = new NmkdStopwatch();

            if (!isBackup)
            {
                Program.mainForm.SetStatus("Merging video chunks...");
            }

            try
            {
                DirectoryInfo chunksDir = new DirectoryInfo(chunksFolder);
                foreach (DirectoryInfo dir in chunksDir.GetDirectories())
                {
                    string suffix            = dir.Name.Replace("chunks", "");
                    string tempConcatFile    = Path.Combine(tempFolder, $"chunks-concat{suffix}.ini");
                    string concatFileContent = "";

                    foreach (string vid in IoUtils.GetFilesSorted(dir.FullName))
                    {
                        concatFileContent += $"file '{Paths.chunksDir}/{dir.Name}/{Path.GetFileName(vid)}'\n";
                    }

                    File.WriteAllText(tempConcatFile, concatFileContent);
                    Logger.Log($"CreateVideo: Running MergeChunks() for frames file '{Path.GetFileName(tempConcatFile)}'", true);
                    bool   fpsLimit = dir.Name.Contains(Paths.fpsLimitSuffix);
                    string outPath  = Path.Combine(baseOutPath, await IoUtils.GetCurrentExportFilename(fpsLimit, true));
                    await MergeChunks(tempConcatFile, outPath, isBackup);

                    if (!isBackup)
                    {
                        Task.Run(async() => { await IoUtils.TryDeleteIfExistsAsync(IoUtils.FilenameSuffix(outPath, Paths.backupSuffix)); });
                    }
                }
            }
            catch (Exception e)
            {
                Logger.Log("ChunksToVideo Error: " + e.Message, isBackup);

                if (!isBackup)
                {
                    MessageBox.Show("An error occured while trying to merge the video chunks.\nCheck the log for details.");
                }
            }

            Logger.Log($"Merged video chunks in {sw}", true);
        }
Пример #2
0
        public static async Task <string> GetCurrentExportFilename(bool fpsLimit, bool withExt)
        {
            InterpSettings curr   = Interpolate.current;
            string         max    = Config.Get(Config.Key.maxFps);
            Fraction       maxFps = max.Contains("/") ? new Fraction(max) : new Fraction(max.GetFloat());
            float          fps    = fpsLimit ? maxFps.GetFloat() : curr.outFps.GetFloat();

            if (curr.outMode == Interpolate.OutMode.VidGif && fps > 50f)
            {
                fps = 50f;
            }

            Size outRes = await InterpolateUtils.GetOutputResolution(curr.inPath, false, false);

            string pattern    = Config.Get(Config.Key.exportNamePattern);
            string inName     = Interpolate.current.inputIsFrames ? Path.GetFileName(curr.inPath) : Path.GetFileNameWithoutExtension(curr.inPath);
            bool   encodeBoth = Config.GetInt(Config.Key.maxFpsMode) == 0;
            bool   addSuffix  = fpsLimit && (!pattern.Contains("[FPS]") && !pattern.Contains("[ROUNDFPS]")) && encodeBoth;
            string filename   = pattern;

            filename = filename.Replace("[NAME]", inName);
            filename = filename.Replace("[FULLNAME]", Path.GetFileName(curr.inPath));
            filename = filename.Replace("[FACTOR]", curr.interpFactor.ToStringDot());
            filename = filename.Replace("[AI]", curr.ai.aiNameShort.ToUpper());
            filename = filename.Replace("[MODEL]", curr.model.name.Remove(" "));
            filename = filename.Replace("[FPS]", fps.ToStringDot());
            filename = filename.Replace("[ROUNDFPS]", fps.RoundToInt().ToString());
            filename = filename.Replace("[RES]", $"{outRes.Width}x{outRes.Height}");
            filename = filename.Replace("[H]", $"{outRes.Height}p");

            if (addSuffix)
            {
                filename += Paths.fpsLimitSuffix;
            }

            if (withExt)
            {
                filename += FfmpegUtils.GetExt(curr.outMode);
            }

            return(filename);
        }
Пример #3
0
        public static async Task MainLoop(string interpFramesPath)
        {
            if (!AutoEncodeResume.resumeNextRun)
            {
                AutoEncodeResume.Reset();
            }

            debug = Config.GetBool("autoEncDebug", false);

            try
            {
                UpdateChunkAndBufferSizes();

                bool imgSeq = Interpolate.current.outMode.ToString().ToLower().StartsWith("img");
                interpFramesFolder = interpFramesPath;
                videoChunksFolder  = Path.Combine(interpFramesPath.GetParentDir(), Paths.chunksDir);

                if (Interpolate.currentlyUsingAutoEnc)
                {
                    Directory.CreateDirectory(videoChunksFolder);
                }

                encodedFrameLines.Clear();
                unencodedFrameLines.Clear();

                Logger.Log($"[AE] Starting AutoEncode MainLoop - Chunk Size: {chunkSize} Frames - Safety Buffer: {safetyBufferFrames} Frames", true);
                int    chunkNo = AutoEncodeResume.encodedChunks + 1;
                string encFile = Path.Combine(interpFramesPath.GetParentDir(), Paths.GetFrameOrderFilename(Interpolate.current.interpFactor));
                interpFramesLines = IoUtils.ReadLines(encFile).Select(x => x.Split('/').Last().Remove("'").Split('#').First()).ToArray();     // Array with frame filenames

                while (!Interpolate.canceled && GetInterpFramesAmount() < 2)
                {
                    await Task.Delay(1000);
                }

                int lastEncodedFrameNum = 0;

                while (HasWorkToDo())    // Loop while proc is running and not all frames have been encoded
                {
                    if (Interpolate.canceled)
                    {
                        return;
                    }

                    if (paused)
                    {
                        await Task.Delay(200);

                        continue;
                    }

                    unencodedFrameLines.Clear();

                    bool aiRunning = !AiProcess.lastAiProcess.HasExited;

                    for (int frameLineNum = lastEncodedFrameNum; frameLineNum < interpFramesLines.Length; frameLineNum++)
                    {
                        if (aiRunning && interpFramesLines[frameLineNum].Contains(InterpolationProgress.lastFrame.ToString().PadLeft(Padding.interpFrames, '0')))
                        {
                            break;
                        }

                        unencodedFrameLines.Add(frameLineNum);
                    }

                    if (Config.GetBool(Config.Key.alwaysWaitForAutoEnc))
                    {
                        int  maxFrames   = chunkSize + (0.5f * chunkSize).RoundToInt() + safetyBufferFrames;
                        bool overwhelmed = unencodedFrameLines.Count > maxFrames;

                        if (overwhelmed && !AiProcessSuspend.aiProcFrozen && OsUtils.IsProcessHidden(AiProcess.lastAiProcess))
                        {
                            string dirSize = FormatUtils.Bytes(IoUtils.GetDirSize(Interpolate.current.interpFolder, true));
                            Logger.Log($"AutoEnc is overwhelmed! ({unencodedFrameLines.Count} unencoded frames > {maxFrames}) - Pausing.", true);
                            AiProcessSuspend.SuspendResumeAi(true);
                        }
                        else if (!overwhelmed && AiProcessSuspend.aiProcFrozen)
                        {
                            AiProcessSuspend.SuspendResumeAi(false);
                        }
                    }

                    if (unencodedFrameLines.Count > 0 && (unencodedFrameLines.Count >= (chunkSize + safetyBufferFrames) || !aiRunning))     // Encode every n frames, or after process has exited
                    {
                        try
                        {
                            List <int> frameLinesToEncode = aiRunning ? unencodedFrameLines.Take(chunkSize).ToList() : unencodedFrameLines;     // Take all remaining frames if process is done
                            string     lastOfChunk        = Path.Combine(interpFramesPath, interpFramesLines[frameLinesToEncode.Last()]);

                            if (!File.Exists(lastOfChunk))
                            {
                                if (debug)
                                {
                                    Logger.Log($"[AE] Last frame of chunk doesn't exist; skipping loop iteration ({lastOfChunk})", true);
                                }

                                await Task.Delay(500);

                                continue;
                            }

                            busy = true;
                            string outpath   = Path.Combine(videoChunksFolder, "chunks", $"{chunkNo.ToString().PadLeft(4, '0')}{FfmpegUtils.GetExt(Interpolate.current.outMode)}");
                            string firstFile = Path.GetFileName(interpFramesLines[frameLinesToEncode.First()].Trim());
                            string lastFile  = Path.GetFileName(interpFramesLines[frameLinesToEncode.Last()].Trim());
                            Logger.Log($"[AE] Encoding Chunk #{chunkNo} to using line {frameLinesToEncode.First()} ({firstFile}) through {frameLinesToEncode.Last()} ({lastFile}) - {unencodedFrameLines.Count} unencoded frames left in total", true, false, "ffmpeg");

                            await Export.EncodeChunk(outpath, Interpolate.current.interpFolder, chunkNo, Interpolate.current.outMode, frameLinesToEncode.First(), frameLinesToEncode.Count);

                            if (Interpolate.canceled)
                            {
                                return;
                            }

                            if (aiRunning && Config.GetInt(Config.Key.autoEncMode) == 2)
                            {
                                Task.Run(() => DeleteOldFramesAsync(interpFramesPath, frameLinesToEncode));
                            }

                            if (Interpolate.canceled)
                            {
                                return;
                            }

                            encodedFrameLines.AddRange(frameLinesToEncode);
                            Logger.Log("[AE] Done Encoding Chunk #" + chunkNo, true, false, "ffmpeg");
                            lastEncodedFrameNum = (frameLinesToEncode.Last() + 1);
                            chunkNo++;
                            AutoEncodeResume.Save();

                            if (!imgSeq && Config.GetInt(Config.Key.autoEncBackupMode) > 0)
                            {
                                if (aiRunning && (currentMuxTask == null || (currentMuxTask != null && currentMuxTask.IsCompleted)))
                                {
                                    currentMuxTask = Task.Run(() => Export.ChunksToVideo(Interpolate.current.tempFolder, videoChunksFolder, Interpolate.current.outPath, true));
                                }
                                else
                                {
                                    Logger.Log($"[AE] Skipping backup because {(!aiRunning ? "this is the final chunk" : "previous mux task has not finished yet")}!", true, false, "ffmpeg");
                                }
                            }

                            busy = false;
                        }
                        catch (Exception e)
                        {
                            Logger.Log($"AutoEnc Chunk Encoding Error: {e.Message}. Stack Trace:\n{e.StackTrace}");
                            Interpolate.Cancel("Auto-Encode encountered an error.");
                        }
                    }

                    await Task.Delay(50);
                }

                if (Interpolate.canceled)
                {
                    return;
                }

                while (currentMuxTask != null && !currentMuxTask.IsCompleted)
                {
                    await Task.Delay(100);
                }

                if (imgSeq)
                {
                    return;
                }

                await Export.ChunksToVideo(Interpolate.current.tempFolder, videoChunksFolder, Interpolate.current.outPath);
            }
            catch (Exception e)
            {
                Logger.Log($"AutoEnc Error: {e.Message}. Stack Trace:\n{e.StackTrace}");
                Interpolate.Cancel("Auto-Encode encountered an error.");
            }
        }