CancelErrorRead() public method

public CancelErrorRead ( ) : void
return void
Beispiel #1
1
        private void runTask(videoTask t, Process process)
        {
            this.rsForm.setPercent("0.0");
            this.rsForm.setTime("");
            this.rsForm.setFps("");
            this.rsForm.setEta("");

            string fp = t.getFP();

            process = new System.Diagnostics.Process();

            process.StartInfo.FileName = "cmd";

            // 必须禁用操作系统外壳程序
            process.StartInfo.UseShellExecute        = false;
            process.StartInfo.CreateNoWindow         = true;
            process.StartInfo.RedirectStandardError  = true;
            process.StartInfo.RedirectStandardOutput = true;
            process.StartInfo.RedirectStandardInput  = true;

            process.ErrorDataReceived  += new DataReceivedEventHandler(OutputHandler);
            process.OutputDataReceived += new DataReceivedEventHandler(OutputHandler);

            process.Start();

            this.PIDs[0]    = process.Id;
            this.rsForm.PID = process.Id;
            this.rsForm.setStopBtnState(true);

            // 找到预设存储的文件并提取到taskSetting中
            string      tsfp = System.Windows.Forms.Application.StartupPath + "\\taskSettings\\" + t.getSetting() + ".json";
            taskSetting ts   = JsonConvert.DeserializeObject <taskSetting>(File.ReadAllText(tsfp));

            // 将encoder信息传给信息显示界面
            this.rsForm.encodingProgram = ts.encoder;
            this.rsForm.HideVideoEncoderSetting();

            cmdCode c = new cmdCode(fp, ts, this.outputFolderPath);
            string  cmd;

            int type     = c.taskType();
            int checkNum = 0;

            int       beforeProcessCheckTime = 3500;
            int       processCheckInterval   = 1000;
            const int checkF = 20;

            // 定义一个内部(匿名)方法
            // 整个视频转换过程结束时
            InnerMethodDelagate afterSuccess = delegate()
            {
                this.finishedNum++;
                this.rsForm.setStatusBarFilesCountLabel(this.finishedNum, this.num);

                try
                {
                    process.CancelErrorRead();
                    process.CancelOutputRead();
                }
                catch (Exception e)
                {
                    //saveLog2File();
                }

                this.rsForm.setEta("");
                this.rsForm.setFps("");
                this.rsForm.setTime("");
                this.rsForm.setEstKbps("");
                this.rsForm.SetTaskStepsLabel(true);

                Process p = Process.GetProcessById(this.PIDs[0]);
                p.Kill();
                this.rsForm.setStopBtnState(false);
                this.rsForm.setPercent("-3");
                this.isfinished[0] = true;
                this.reportCount   = 0;
                this.log.Clear();

                miniLog += t.getFP() + Environment.NewLine + Environment.NewLine + Environment.NewLine;
                saveMiniLog2File();
            };

            // 运行失败时调用
            InnerMethodDelagate afterFailed = delegate()
            {
                this.isfailed = true;

                saveLog2File();

                this.rsForm.setPercent("-1");
                this.rsForm.setTime("发生错误");
                this.rsForm.setFps("日志保存在程序目录");

                int sleepTime = 5;  // 设置失败后继续下一个任务的时间
                this.rsForm.setEta(sleepTime.ToString() + "秒后继续运行");

                this.rsForm.setStatusBarLabelTextColorRED();
                this.finishedNum++;
                this.rsForm.setStatusBarFilesCountLabel(this.finishedNum, this.num);
                this.rsForm.HideVideoEncoderSetting();

                try
                {
                    process.CancelErrorRead();
                    process.CancelOutputRead();
                }
                catch (Exception e)
                {
                    //saveLog2File();
                }

                Thread.Sleep(sleepTime * 1000);

                Process p = Process.GetProcessById(this.PIDs[0]);
                p.Kill();
                this.rsForm.setStopBtnState(false);
                this.rsForm.setPercent("-3");
                this.isfinished[0] = true;
                this.reportCount   = 0;
                this.log.Clear();
            };

            // 视频编码前更新UI(显示视频总帧数)
            InnerMethodDelagate DispVideoFrames = delegate()
            {
                // MediaInfo读取视频帧数
                MediaInfo MI = new MediaInfo();
                string    duration;
                string    frameRate;
                string    frames;
                MI.Open(t.getFP());
                duration = MI.Get(StreamKind.Video, 0, "Duration");
                try
                {
                    double totalTime = Double.Parse(duration) / 1000.0;
                    frameRate = MI.Get(StreamKind.Video, 0, "FrameRate");
                    frames    = ((int)(totalTime * Double.Parse(frameRate))).ToString();

                    if (!String.IsNullOrWhiteSpace(frames))
                    {
                        this.rsForm.setTime("0/" + frames);
                    }
                }
                catch (Exception e)
                {
                    //saveLog2File();
                }
            };

            InnerMethodDelagate VideoEncode = delegate()
            {
                // 视频编码
                this.encoding = true;
                this.rsForm.setPercent("0.0");

                string ext = this.getFileExtName(t.getFP());
                if (String.Equals(ext, "avs", StringComparison.CurrentCultureIgnoreCase))
                {
                    this.videoType = AVS;
                }
                else
                {
                    this.videoType = NORMAL;
                    DispVideoFrames();
                }

                cmd = c.cmdCodeGenerate(VIDEOENCODE, this.videoType);
                process.StandardInput.WriteLine(cmd);

                try
                {
                    process.BeginErrorReadLine();
                    process.BeginOutputReadLine();
                }
                catch (Exception e)
                {
                    //saveLog2File();
                }

                checkNum         = 0;
                this.reportCount = 0;
                int cpx2 = this.checkPattern + this.checkPattern;
                for (int i = 0; i < cpx2; i++)
                {
                    checkFrame[i] = 0;
                }
                for (int i = 0; i < cpx2; i++)
                {
                    this.fps[i] = 0;
                }

                Thread.Sleep(beforeProcessCheckTime);

                Process p;
                switch (videoType)
                {
                case NORMAL:
                    p = GetSubTaskProcess(ts.encoder);
                    if (p != null)
                    {
                        this.subTaskPID = p.Id;
                    }
                    else
                    {
                        this.subTaskPID = -1;
                    }
                    break;

                case AVS:
                    Process avsP  = GetSubTaskProcess("avs4x265.exe");
                    int     avsId = avsP.Id;
                    if (avsP != null)
                    {
                        bool hasFound = false;

                        // 等待视频编码进程启动,最长等待1小时
                        for (int i = 0; i < 7200; i++)
                        {
                            // 确认avs进程仍在运行
                            try
                            {
                                Process.GetProcessById(avsId);
                            }
                            catch (Exception e)
                            {
                                if (this.encoding == true || ConfirmFailed())
                                {
                                    afterFailed();
                                }
                                return;
                            }

                            // 每隔500ms寻找视频编码进程
                            p = GetSubTaskProcess(ts.encoder, avsId);
                            if (p != null)
                            {
                                this.subTaskPID = p.Id;
                                hasFound        = true;
                                break;
                            }
                            else
                            {
                                Thread.Sleep(500);
                            }
                        }

                        if (!hasFound)
                        {
                            this.subTaskPID = -1;
                        }
                    }
                    else
                    {
                        this.subTaskPID = -1;
                    }
                    break;

                default:
                    break;
                }

                this.rsForm.ShowVideoEncoderSetting();

                while (this.encoding == true || this.postProcessing == true)
                {
                    try
                    {
                        Process.GetProcessById(this.subTaskPID);
                    }
                    catch (Exception e)
                    {
                        if (this.encoding == true || ConfirmFailed())
                        {
                            afterFailed();
                        }
                        return;
                    }

                    Thread.Sleep(processCheckInterval);
                }
                try
                {
                    process.CancelErrorRead();
                    process.CancelOutputRead();
                }
                catch (Exception e)
                {
                    //saveLog2File();
                }

                this.rsForm.HideVideoEncoderSetting();
            };

            InnerMethodDelagate Mux = delegate()
            {
                // muxer
                this.muxing = true;
                int stepIdx = type == ONLYVIDEO ? 2 : 3;
                this.rsForm.SetTaskStepsLabel(false, stepIdx, stepIdx, MUXER);

                cmd = c.cmdCodeGenerate(MUXER);
                process.StandardInput.WriteLine(cmd);

                try
                {
                    process.BeginErrorReadLine();
                    process.BeginOutputReadLine();
                }
                catch (Exception e)
                {
                    //saveLog2File();
                }

                checkNum = 0;

                Thread.Sleep(beforeProcessCheckTime);  // 有些超短的视频(1-2M),如果不加这句就会直接判定为任务已失败,疑似原因:没等判断完进程就已经结束

                string muxerProcessName = "";
                if (String.Equals("mp4", ts.outputFormat))
                {
                    muxerProcessName = "mp4Box";
                }
                else if (String.Equals("mkv", ts.outputFormat))
                {
                    muxerProcessName = "mkvmerge";
                }

                Process p = GetSubTaskProcess(muxerProcessName);
                if (p != null)
                {
                    this.subTaskPID = p.Id;
                }
                else
                {
                    this.subTaskPID = -1;
                }

                while (this.muxing == true)
                {
                    try
                    {
                        Process.GetProcessById(this.subTaskPID);
                    }
                    catch (Exception e)
                    {
                        Thread.Sleep(1000);
                        if (this.muxing == true)
                        {
                            afterFailed();
                        }
                        return;
                    }

                    Thread.Sleep(processCheckInterval);
                    //checkNum = checkCmdRunning(checkNum, checkF);
                    //if (checkNum == -1)
                    //{
                    //    return;
                    //}
                }

                afterSuccess();

                string tempVideoFp = c.cmdCodeGenerate(DELETEVIDEOTEMP);
                string tempAudioFp = c.cmdCodeGenerate(DELETEAUDIOTEMP);
                try
                {
                    File.Delete(tempVideoFp);
                    File.Delete(tempAudioFp);
                }
                catch (System.IO.IOException ex)
                {
                    this.log.AppendLine("出现异常:" + ex);
                    saveLog2File();
                }
            };

            // 音频编码或复制开始前更新UI(显示音频总时长)
            InnerMethodDelagate DispAudioDuration = delegate()
            {
                // MediaInfo读取音频时长
                MediaInfo MI = new MediaInfo();
                string    duration;
                MI.Open(c.getAudioSource());
                duration = MI.Get(StreamKind.Audio, 0, 69);

                if (!String.IsNullOrWhiteSpace(duration))
                {
                    this.rsForm.setTime("0/" + duration);
                }

                this.rsForm.setPercent("0.0", AUDIOENCODE);
            };

            InnerMethodDelagate ClearUIAfterAudioProcessing = delegate()
            {
                this.rsForm.setPercent("0.0");
                this.rsForm.setTime("");
                this.rsForm.setFps("");
            };

            switch (type)
            {
            case ONLYVIDEO:

                this.rsForm.SetTaskStepsLabel(false, 1, 2, VIDEOENCODE);

                VideoEncode();

                // 一个子任务失败了意味着这个文件的编码任务失败,所以在所有子任务开始时都要检查checkNum是否为-1
                if (isfailed)
                {
                    return;
                }
                //afterSuccess();

                Mux();

                break;

            case COPYAUDIO:
                // 复制音频
                cmd = c.cmdCodeGenerate(AUDIOCOPY);
                process.StandardInput.WriteLine(cmd);
                process.BeginErrorReadLine();
                process.BeginOutputReadLine();
                this.audioProcessing = true;
                this.rsForm.SetTaskStepsLabel(false, 1, 3, AUDIOCOPY);
                DispAudioDuration();

                checkNum = 0;

                Thread.Sleep(beforeProcessCheckTime);

                Process p = GetSubTaskProcess("ffmpeg");
                if (p != null)
                {
                    this.subTaskPID = p.Id;
                }
                else
                {
                    this.subTaskPID = -1;
                }

                while (this.audioProcessing == true)
                {
                    try
                    {
                        Process.GetProcessById(this.subTaskPID);
                    }
                    catch (Exception e)
                    {
                        Thread.Sleep(1000);
                        if (this.audioProcessing == true)
                        {
                            afterFailed();
                        }
                        return;
                    }

                    Thread.Sleep(processCheckInterval);
                    //checkNum = checkCmdRunning(checkNum, checkF);
                    //if (checkNum == -1)
                    //{
                    //    return;
                    //}
                }
                ClearUIAfterAudioProcessing();

                process.CancelErrorRead();
                process.CancelOutputRead();

                this.rsForm.SetTaskStepsLabel(false, 2, 3, VIDEOENCODE);

                // 一个子任务失败了意味着这个文件的编码任务失败,所以在所有子任务开始时都要检查checkNum是否为-1
                if (isfailed)
                {
                    return;
                }
                VideoEncode();

                // 一个子任务失败了意味着这个文件的编码任务失败,所以在所有子任务开始时都要检查checkNum是否为-1
                if (isfailed)
                {
                    return;
                }
                Mux();

                break;

            case SUPPRESSAUDIO:
                // 音频编码
                cmd = c.cmdCodeGenerate(AUDIOENCODE);
                process.StandardInput.WriteLine(cmd);
                process.BeginErrorReadLine();
                process.BeginOutputReadLine();
                this.audioProcessing = true;
                this.rsForm.SetTaskStepsLabel(false, 1, 3, AUDIOENCODE);
                DispAudioDuration();

                checkNum = 0;

                Thread.Sleep(beforeProcessCheckTime);

                Process p2 = GetSubTaskProcess(ts.audioEncoder);
                if (p2 != null)
                {
                    this.subTaskPID = p2.Id;
                }
                else
                {
                    this.subTaskPID = -1;
                }

                while (this.audioProcessing == true)
                {
                    try
                    {
                        Process.GetProcessById(this.subTaskPID);
                    }
                    catch (Exception e)
                    {
                        Thread.Sleep(1000);
                        if (this.audioProcessing == true)
                        {
                            afterFailed();
                        }
                        return;
                    }

                    Thread.Sleep(processCheckInterval);
                    //checkNum = checkCmdRunning(checkNum, checkF);
                    //if (checkNum == -1)
                    //{
                    //    return;
                    //}
                }
                ClearUIAfterAudioProcessing();

                process.CancelErrorRead();
                process.CancelOutputRead();

                this.rsForm.SetTaskStepsLabel(false, 2, 3, VIDEOENCODE);

                // 一个子任务失败了意味着这个文件的编码任务失败,所以在所有子任务开始时都要检查checkNum是否为-1
                if (isfailed)
                {
                    return;
                }
                VideoEncode();

                // 一个子任务失败了意味着这个文件的编码任务失败,所以在所有子任务开始时都要检查checkNum是否为-1
                if (isfailed)
                {
                    return;
                }
                Mux();

                break;

            default:
                cmd = "";
                break;
            }

            //MessageBox.Show(cmd);
        }
        public void DoAddTasks(bool abStartup)
        {
            // Do this at most once per minute to avoid running the same task twice in rapid succession.
            if ( !abStartup && (!moProfile.ContainsKey("-AddTasks") || DateTime.Now < mdtPreviousAddTasksStarted.AddMinutes(1)) )
                return;

            mdtPreviousAddTasksStarted = DateTime.Now;

            try
            {
                if ( null == moAddTasksProfile )
                {
                    moAddTasksProfile = moProfile.oProfile("-AddTasks").oOneKeyProfile("-Task");
                    moAddTasksProcessArray = new Process[moAddTasksProfile.Count];
                }
                
                for (int i=0; i < moAddTasksProfile.Count; ++i)
                {
                    // Convert the current task from a command-line string to a profile oject.
                    tvProfile loAddTask = new tvProfile(moAddTasksProfile[i].ToString());

                    bool lbDoTask = false;

                    if ( abStartup )
                    {
                        lbDoTask = loAddTask.bValue("-OnStartup", false);

                        // Reset pause timer to allow other tasks to run without delay after startup.
                        mdtPreviousAddTasksStarted = DateTime.Now.AddMinutes(-1);
                    }
                    else
                    {
                        DateTime    ldtTaskStartTime = loAddTask.dtValue("-StartTime", DateTime.MinValue);
                        string      lsTaskDaysOfWeek = loAddTask.sValue("-StartDays", "");

                        // If -StartTime is within the current minute, start the task.
                        // If -StartDays is specified, run the task on those days only.
                        lbDoTask = DateTime.MinValue != ldtTaskStartTime && (int)mdtPreviousAddTasksStarted.TimeOfDay.TotalMinutes == (int)ldtTaskStartTime.TimeOfDay.TotalMinutes
                                && ("" == lsTaskDaysOfWeek || this.bListIncludesDay(lsTaskDaysOfWeek, mdtPreviousAddTasksStarted));
                    }

                    if ( lbDoTask )
                    {
                        string  lsCommandEXE = loAddTask.sValue("-CommandEXE", "add task -CommandEXE missing");

                        Process loProcess = new Process();
                                loProcess.ErrorDataReceived += new DataReceivedEventHandler(this.BackupProcessOutputHandler);
                                loProcess.OutputDataReceived += new DataReceivedEventHandler(this.BackupProcessOutputHandler);
                                loProcess.StartInfo.FileName = lsCommandEXE;
                                loProcess.StartInfo.Arguments = loAddTask.sValue("-CommandArgs", "");
                                loAddTask.bValue("-UnloadOnExit", false);

                                // The following subset of parameters are overridden when -TimeoutMinutes is set. This is
                                // necessary to guarantee IO redirection is handled properly (ie. output goes to the log).
                        bool    lbWaitForExitOverride = (loAddTask.iValue("-TimeoutMinutes", 0) > 0);
                                loProcess.StartInfo.CreateNoWindow          =  lbWaitForExitOverride | loAddTask.bValue("-CreateNoWindow", false);
                                loProcess.StartInfo.UseShellExecute         = !lbWaitForExitOverride & loAddTask.bValue("-UseShellExecute", true);
                                loProcess.StartInfo.RedirectStandardInput   =  lbWaitForExitOverride | loAddTask.bValue("-RedirectStandardInput", false);
                                loProcess.StartInfo.RedirectStandardError   =  lbWaitForExitOverride | loAddTask.bValue("-RedirectStandardError", false);
                                loProcess.StartInfo.RedirectStandardOutput  =  lbWaitForExitOverride | loAddTask.bValue("-RedirectStandardOutput", false);

                                moAddTasksProcessArray[i] = loProcess;

                        try
                        {
                            if ( !loAddTask.bValue("-OnStartup", false) )
                            {
                                this.LogIt(String.Format("Starting Task: {0}", loAddTask.sCommandLine()));

                                loProcess.Start();

                                // Start output to console also.
                                if ( loProcess.StartInfo.RedirectStandardError )
                                    loProcess.BeginErrorReadLine();
                                if ( loProcess.StartInfo.RedirectStandardOutput )
                                    loProcess.BeginOutputReadLine();

                                if ( lbWaitForExitOverride )
                                {
                                    // Wait the timeout period, then call "WaitForExit()" to flush the output steams.
                                    if ( loProcess.WaitForExit(60000 * loAddTask.iValue("-TimeoutMinutes", 0)) )
                                        loProcess.WaitForExit();

                                    // Stop output to console.
                                    if ( loProcess.StartInfo.RedirectStandardError )
                                        loProcess.CancelErrorRead();
                                    if ( loProcess.StartInfo.RedirectStandardOutput )
                                        loProcess.CancelOutputRead();

                                    loProcess.Close();
                                }
                            }
                            else
                            {
                                bool        lbFound = false;
                                string      lsWindowTitle = loAddTask.sValue("-CommandWindowTitle", "");
                                Process[]   loProcessesArray = Process.GetProcessesByName(Path.GetFileNameWithoutExtension(loProcess.StartInfo.FileName));
                                            // If there's exactly one matching process and no given window title to compare, we're done.
                                            lbFound = (1 == loProcessesArray.Length && "" == lsWindowTitle );

                                            // If no window title has been given to compare, there's nothing else to do.
                                            if ( !lbFound && "" != lsWindowTitle )
                                            {
                                                // If no matching processes have been found so far, get them all to compare.
                                                if ( 0 == loProcessesArray.Length )
                                                    loProcessesArray = Process.GetProcesses();

                                                // Since a window title has been provided, it must be compared to the process(es) found.
                                                // Wildcards are permitted, but only at the end of titles. We stop at the first match.
                                                foreach (Process loProcessEntry in loProcessesArray)
                                                    if ( loProcessEntry.MainWindowTitle.StartsWith(lsWindowTitle.Replace("*", "")) )
                                                    {
                                                        lbFound = true;
                                                        break;
                                                    }
                                            }

                                // Don't start -OnStartup processes that have already been started.
                                if ( lbFound )
                                {
                                    // The process has "already started" if there is only one with the
                                    // same EXE or multiple EXEs with one having the same window title.
                                    this.LogIt(String.Format("Already running, task not started: {0}", loAddTask.sCommandLine()));
                                }
                                else
                                {
                                    this.LogIt(String.Format("Starting Task: {0}", loAddTask.sCommandLine()));

                                    loProcess.Start();

                                    // Start output to console also.
                                    if ( loProcess.StartInfo.RedirectStandardError )
                                        loProcess.BeginErrorReadLine();
                                    if ( loProcess.StartInfo.RedirectStandardOutput )
                                        loProcess.BeginOutputReadLine();

                                    if ( lbWaitForExitOverride )
                                    {
                                        // Wait the timeout period, then call "WaitForExit()" to flush the output steams.
                                        if ( loProcess.WaitForExit(60000 * loAddTask.iValue("-TimeoutMinutes", 0)) )
                                            loProcess.WaitForExit();

                                        // Stop output to console.
                                        if ( loProcess.StartInfo.RedirectStandardError )
                                            loProcess.CancelErrorRead();
                                        if ( loProcess.StartInfo.RedirectStandardOutput )
                                            loProcess.CancelOutputRead();

                                        loProcess.Close();
                                    }
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            this.ShowError(ex.Message, String.Format("Failed starting task: {0}", lsCommandEXE));
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                this.ShowError(ex.Message, "Add Tasks Failed");
            }
        }
Beispiel #3
0
        private static Task GetDbDumpTask(Config config)
        {
            return Task.Factory.StartNew(() =>
            {
                var process = new Process
                {
                    StartInfo = new ProcessStartInfo(config.MongoDumpPath, config.MongoDumpArgs)
                    {
                        CreateNoWindow = true,
                        UseShellExecute = false,
                        RedirectStandardOutput = true,
                        RedirectStandardError = true
                    }
                };
                process.OutputDataReceived += (a, e) => Trace.TraceInformation(e.Data);
                process.ErrorDataReceived += (a, e) => Trace.TraceEvent(TraceEventType.Error, 0, e.Data);

                process.Start();
                process.BeginErrorReadLine();
                process.BeginOutputReadLine();
                process.WaitForExit();
                process.CancelErrorRead();
                process.CancelOutputRead();
                process.Close();

                Trace.TraceInformation("Dump completed!");
            });
        }
Beispiel #4
0
        public static int RunProcessAndRedirectToLogger(string command, string parameters, string workingDirectory, LoggerResult logger)
        {
            var process = new Process
            {
                StartInfo = new ProcessStartInfo(command)
                {
                    UseShellExecute = false,
                    CreateNoWindow = true,
                    RedirectStandardError = true,
                    RedirectStandardOutput = true,
                    WorkingDirectory = workingDirectory,
                    Arguments = parameters,
                }
            };

            process.Start();

            DataReceivedEventHandler outputDataReceived = (_, args) => LockProcessAndAddDataToLogger(process, logger, false, args);
            DataReceivedEventHandler errorDataReceived = (_, args) => LockProcessAndAddDataToLogger(process, logger, true, args);

            process.OutputDataReceived += outputDataReceived;
            process.ErrorDataReceived += errorDataReceived;
            process.BeginOutputReadLine();
            process.BeginErrorReadLine();
            process.WaitForExit();
            process.CancelOutputRead();
            process.CancelErrorRead();

            process.OutputDataReceived -= outputDataReceived;
            process.ErrorDataReceived -= errorDataReceived;

            return process.ExitCode;
        }
Beispiel #5
0
        public int Run(string srcpath)
        {
            Process p;

            p = new Process();
            p.StartInfo.FileName = ILASMpath;
            p.StartInfo.Arguments = srcpath;
            p.StartInfo.CreateNoWindow = true;
            p.StartInfo.UseShellExecute = false;

            p.OutputDataReceived += new DataReceivedEventHandler(OnOutputDataReceived);
            p.ErrorDataReceived += new DataReceivedEventHandler(OnErrorDataReceived);

            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.RedirectStandardError = true;

            p.Start();
            p.BeginOutputReadLine();
            p.BeginErrorReadLine();
            p.WaitForExit();
            p.CancelErrorRead();
            p.CancelOutputRead();

            return p.ExitCode;
        }
Beispiel #6
0
        public CSharpCompilerResult Compile(CSharpCompilerArgs args)
        {
            if (args == null)
                throw new ArgumentNullException("args");

            var exitCode = 0;
            var outputText = string.Empty;
            var invocationError = null as Exception;
            var warnings = new List<string>();
            var errors = new List<string>();

            var framework = new FrameworkVersion40Info();

            var compilerArgs = this.GetCompilerArgString(args);

            var psi = new ProcessStartInfo(framework.CSharpCompilerBinFilepath, compilerArgs);

            psi.RedirectStandardOutput = true;
            psi.RedirectStandardError = true;
            psi.WorkingDirectory = args.WorkDir;
            psi.CreateNoWindow = true;
            psi.WindowStyle = ProcessWindowStyle.Hidden;
            psi.UseShellExecute = false;

            var process = new Process();
            process.StartInfo = psi;

            process.ErrorDataReceived += (s, e) =>
            {
                Console.WriteLine(e.Data);
            };

            process.OutputDataReceived += (s, e) =>
            {
                Console.WriteLine(e.Data);
            };

            process.Start();
            process.BeginOutputReadLine();
            process.BeginErrorReadLine();

            process.WaitForExit();

            process.CancelErrorRead();
            process.CancelOutputRead();

            exitCode = process.ExitCode;

            process.Dispose();
            process = null;

            return new CSharpCompilerResult(exitCode,
                invocationError,
                outputText,
                args.OutputFilepath,
                warnings,
                errors);
        }
        internal static ProcessOutput StartAndWaitForReady(System.Diagnostics.Process process, int timeoutInSeconds, string processReadyIdentifier, string windowTitle)
        {
            if (timeoutInSeconds < 1 ||
                timeoutInSeconds > 10)
            {
                throw new ArgumentOutOfRangeException("timeoutInSeconds", "The amount in seconds should have a value between 1 and 10.");
            }

            List <string> errorOutput    = new List <string>();
            List <string> standardOutput = new List <string>();
            bool          processReady   = false;


            process.ErrorDataReceived  += (sender, args) => errorOutput.Add(args.Data);
            process.OutputDataReceived += (sender, args) =>
            {
                standardOutput.Add(args.Data);

                if (
                    !string.IsNullOrEmpty(args.Data)
                    &&
                    args.Data.Contains(processReadyIdentifier)
                    )
                {
                    processReady = true;
                }
            };

            process.Start();

            process.BeginErrorReadLine();
            process.BeginOutputReadLine();

            int lastResortCounter = 0;
            int timeOut           = timeoutInSeconds * 10;

            while (!processReady)
            {
                System.Threading.Tasks.Task
                .Delay(100)
                .Wait();

                if (++lastResortCounter > timeOut)
                {
                    // we waited X seconds.
                    // for any reason the detection did not worked, eg. the identifier changed
                    // lets assume everything is still ok
                    break;
                }
            }

            process.CancelErrorRead();
            process.CancelOutputRead();

            return(new ProcessOutput(errorOutput, standardOutput, process.ExitCode));
        }
Beispiel #8
0
        public void Run()
        {
            if(File.Exists(config.OutputPath)) {
            options.Log("Deleting old output file.", true);
            var info = new FileInfo(config.OutputPath);
            using(info.Create()) {
              //effectively deletes the contents of the file
              //calling delete seamed to break the following optimizer code, not sure why
            }
              }

              if(!File.Exists(config.OptimizerPath)) {
            using(var stream = IO.ReadFromResource("r.js"))
            using(var file = File.OpenWrite(config.OptimizerPath)) {
              stream.CopyTo(file);
            }
              }

              if(options.Loader == Options.LoaderOptions.Almond) {
            if(!File.Exists(config.AlmondPath)) {
              using(var stream = IO.ReadFromResource("almond-custom.js"))
              using(var file = File.OpenWrite(config.AlmondPath)) {
            stream.CopyTo(file);
              }
            }
              }

              var command = "/C node \"" +
                    config.OptimizerPath + "\" -o \"" +
                    config.BuildFilePath + "\"";

              var process = new Process {
            StartInfo = new ProcessStartInfo {
              FileName = "cmd.exe",
              Arguments = command,
              UseShellExecute = false,
              CreateNoWindow = true,
              RedirectStandardOutput = true,
              RedirectStandardError = true,
            },
            EnableRaisingEvents = true
              };

              process.OutputDataReceived += (s, e) => Console.WriteLine(e.Data);
              process.ErrorDataReceived += (s, e) => Console.Error.WriteLine(e.Data);

              process.Start();
              process.BeginOutputReadLine();
              process.BeginErrorReadLine();
              process.WaitForExit();
              process.CancelOutputRead();
              process.CancelErrorRead();
        }
Beispiel #9
0
        private static void WaitForExit(Process process)
        {
            process.ErrorDataReceived += (sender, args) => Trace.TraceError("NODEJS: {0}".E(args.Data));
            process.OutputDataReceived += (sender, args) => Trace.TraceInformation("NODEJS: {0}".I(args.Data));

            process.Start();

            process.BeginErrorReadLine();
            process.BeginOutputReadLine();

            process.WaitForExit();

            process.CancelErrorRead();
            process.CancelOutputRead();
        }
Beispiel #10
0
 public void Dispose()
 {
     if (disposed)
     {
         return;
     }
     disposed = true;
     try
     {
         if (internalProcess != null)
         {
             internalProcess.OutputDataReceived -= InternalProcessOnOutputDataReceived;
             internalProcess.ErrorDataReceived  -= InternalProcessOnErrorDataReceived;
             internalProcess.Exited             -= InternalProcessOnExited;
             internalProcess.EnableRaisingEvents = false;
             if (errorReadStarted)
             {
                 internalProcess.CancelErrorRead();
             }
             if (outputReadStarted)
             {
                 internalProcess.CancelOutputRead();
             }
             if (killOnDispose && !internalProcess.HasExited)
             {
                 internalProcess.StandardInput.WriteLine();
                 KillProcessAndChildren(internalProcess.Id);
             }
             internalProcess.Dispose();
         }
     }
     catch (Exception e)
     {
         string additionalInformation = string.Empty;
         try
         {
             if (internalProcess != null)
             {
                 additionalInformation = $"{internalProcess.MainWindowTitle} - {internalProcess.Id} : {internalProcess.HasExited} - {internalProcess.ExitTime}";
             }
         }
         catch (Exception)
         {
             //do nothing only for information gathering
         }
         executionContext.WriteVerbose($"Error while closing process {e}{Environment.NewLine}{additionalInformation}");
     }
 }
Beispiel #11
0
        public static string Run(string path, string args, out string error, bool readOutputByLines = false)
        {
            try
            {
                using (Process process = new Process())
                {
                    Console.WriteLine("Run: " + path);
                    Console.WriteLine("Args: " + args);
                    process.StartInfo.FileName = path;
                    process.StartInfo.Arguments = args;
                    process.StartInfo.UseShellExecute = false;
                    process.StartInfo.RedirectStandardOutput = true;
                    process.StartInfo.RedirectStandardError = true;

                    var reterror = "";
                    var retout = "";
                    process.OutputDataReceived += (sender, outargs) =>
                    {
                        if (retout != "" && outargs.Data != "") retout += "\r\n";
                        retout += outargs.Data;
                        Console.WriteLine("stdout: {0}", retout);
                    };
                    process.ErrorDataReceived += (sender, errargs) =>
                    {
                        if (reterror != "" && errargs.Data != "") reterror += "\r\n";
                        reterror += errargs.Data;
                        Console.WriteLine("stderr: {0}", reterror);
                    };

                    process.Start();
                    process.BeginOutputReadLine();
                    process.BeginErrorReadLine();
                    process.WaitForExit();
                    process.CancelOutputRead();
                    process.CancelErrorRead();

                    error = reterror;
                    if (process.ExitCode != 0)
                        throw new Exception("Exit Code is not 0");
                    return readOutputByLines ? string.Empty : retout.Trim().Replace(@"\\", @"\");
                }
            }
            catch (Exception exception)
            {
                error = string.Format("Calling {0} caused an exception: {1}.", path, exception.Message);
                return string.Empty;
            }
        }
        private bool WaitProcessExit(System.Diagnostics.Process proc, int milliseconds)
        {
            bool success = proc.WaitForExit(milliseconds);

            if (success)
            {
                proc.WaitForExit(); // process stdout and stderr
            }
            else
            {
                proc.CancelOutputRead();
                proc.CancelErrorRead();
            }
            proc.Close();
            return(success);
        }
        public static void ExecuteCommandSync(object parameters)
        {
            ExecuteParameters param = (ExecuteParameters)parameters;

            try
            {
                System.Diagnostics.ProcessStartInfo procStartInfo =
                    new System.Diagnostics.ProcessStartInfo("cmd", "/c " + param.Command);
                procStartInfo.RedirectStandardOutput = true;
                procStartInfo.RedirectStandardError  = true;
                procStartInfo.UseShellExecute        = false;
                procStartInfo.CreateNoWindow         = true;
                procStartInfo.ErrorDialog            = false;

                foreach (EnvVar var in param.Env)
                {
                    if (var.Name == "path")
                    {
                        procStartInfo.EnvironmentVariables["path"] = procStartInfo.EnvironmentVariables["path"] + var.Value;
                    }
                    else
                    {
                        procStartInfo.EnvironmentVariables.Add(var.Name, var.Value);
                    }
                    Logger.GetInstance().Debug(param.Prefix + " EvnVar:" + var.Name + " = " + procStartInfo.EnvironmentVariables[var.Name]);
                }

                System.Diagnostics.Process proc = new System.Diagnostics.Process();
                proc.StartInfo = procStartInfo;
                Logger.GetInstance().Debug(param.Prefix + " starting process: \"" + param.Command + "\"");
                proc.OutputDataReceived += (sender, args) => SuppressUnnecessaryDebug(param.Prefix, args.Data);
                proc.ErrorDataReceived  += (sender, args) => SuppressUnnecessaryError(param.Prefix, args.Data);
                proc.EnableRaisingEvents = true;
                proc.Start();
                proc.BeginOutputReadLine();
                proc.BeginErrorReadLine();
                proc.WaitForExit();
                proc.CancelErrorRead();
                proc.CancelOutputRead();
                Logger.GetInstance().Debug(param.Prefix + " process exited.");
            }
            catch (Exception e)
            {
                Logger.GetInstance().Error(param.Prefix + " " + e);
            }
        }
        static void Main(string[] args)
        {
            Console.WriteLine("Please enter your file path to search.");
            Console.Write("> ");
            string path = Console.ReadLine();
            string[] filenames = Directory.GetFiles(path, "*.mkv", SearchOption.AllDirectories);

            foreach (string s in filenames)
            {
                if (File.Exists(s))
                {
                    currentFile = s;
                    Process p = new Process();
                    p.StartInfo.Arguments = "-i " + "\"" + s + "\"";
                    p.StartInfo.FileName = "ffmpeg.exe";
                    p.StartInfo.RedirectStandardError = true;
                    p.StartInfo.RedirectStandardOutput = true;
                    p.StartInfo.UseShellExecute = false;
                    p.Start();
                    p.BeginOutputReadLine();
                    p.BeginErrorReadLine();
                    p.ErrorDataReceived += P_ErrorDataReceived;
                    p.OutputDataReceived += P_ErrorDataReceived;
                    p.WaitForExit();
                    if (p.HasExited)
                    {
                        p.CancelErrorRead();
                        p.CancelOutputRead();
                        p.Close();
                    }
                }
            }

            convertFiles = convertFiles.Distinct().ToList();

            Console.WriteLine("File to convert: " + convertFiles.Count);
            runThread1();
            runThread2();
            runThread3();
            runThread4();

            Console.Write("Press any key to exit.");
            Console.ReadKey();

        }
Beispiel #15
0
 private void NmapExec(object sender, DoWorkEventArgs e)
 {
     Process compiler = new Process();
     compiler.StartInfo.FileName = NmapLocation;
     compiler.StartInfo.UseShellExecute = false;
     compiler.StartInfo.RedirectStandardInput = false;
     compiler.StartInfo.RedirectStandardOutput = true;
     compiler.StartInfo.RedirectStandardError = true;
     compiler.StartInfo.CreateNoWindow = true;
     compiler.OutputDataReceived += OutputDataHandler;
     compiler.ErrorDataReceived += OutputDataHandler;
     compiler.StartInfo.Arguments = (string)e.Argument;
     compiler.Start();
     compiler.BeginOutputReadLine();
     compiler.BeginErrorReadLine();
     compiler.WaitForExit();
     compiler.CancelOutputRead();
     compiler.CancelErrorRead();
     compiler.Close();
 }
        public static ProcessOutput StartAndWaitForExit(Process process, string windowTitle)
        {
            List<string> errorOutput = new List<string>();
            List<string> standardOutput = new List<string>();

            process.ErrorDataReceived += (sender, args) => errorOutput.Add(args.Data);
            process.OutputDataReceived += (sender, args) => standardOutput.Add(args.Data);

            process.Start();

            process.BeginErrorReadLine();
            process.BeginOutputReadLine();

            process.WaitForExit();

            process.CancelErrorRead();
            process.CancelOutputRead();

            return new ProcessOutput(errorOutput, standardOutput);
        }
        internal static ProcessOutput StartAndWaitForExit(System.Diagnostics.Process process, string windowTitle)
        {
            List <string> errorOutput    = new List <string>();
            List <string> standardOutput = new List <string>();

            process.ErrorDataReceived  += (sender, args) => errorOutput.Add(args.Data);
            process.OutputDataReceived += (sender, args) => standardOutput.Add(args.Data);

            process.Start();

            process.BeginErrorReadLine();
            process.BeginOutputReadLine();

            process.WaitForExit();

            process.CancelErrorRead();
            process.CancelOutputRead();

            return(new ProcessOutput(errorOutput, standardOutput, process.ExitCode));
        }
Beispiel #18
0
        /// <summary>
        /// 启动程序
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="args"></param>
        /// <param name="isGetResults"> </param>
        private static String CallProcess(string fileName, string args, Boolean isGetResults)
        {
            var process = new Process();
            process.StartInfo.FileName = fileName;//设置运行的命令行文件
            process.StartInfo.Arguments = args;//设置命令参数
            process.StartInfo.CreateNoWindow = true;//不显示dos命令行窗口
            process.StartInfo.UseShellExecute = false;//是否指定操作系统外壳进程启动程序
            process.StartInfo.RedirectStandardOutput = isGetResults;
            process.StartInfo.RedirectStandardError = isGetResults;

            // 启动
            process.Start();

            var result = new StringBuilder();

            if (isGetResults)
            {
                process.OutputDataReceived += (s, e) => result.AppendLine(e.Data);
                process.ErrorDataReceived += (s, e) => result.AppendLine(e.Data);

                process.BeginErrorReadLine();
                process.BeginOutputReadLine();
            }

            // 等待完成
            process.WaitForExit();

            if (isGetResults)
            {
                process.CancelOutputRead();
                process.CancelErrorRead();

                return result.ToString();
            }
            else
            {
                return "";
            }
        }
Beispiel #19
0
    public static bool Build()
    {
        FixChartJsBlazorMap();
        int exitCode;

        using (System.Diagnostics.Process pProcess = new System.Diagnostics.Process())
        {
            pProcess.StartInfo.WorkingDirectory       = "../sc2dsstats.app";
            pProcess.StartInfo.FileName               = "electronize";
            pProcess.StartInfo.Arguments              = "build /target win /package-json ./package.json /electron-params --publish=always /p:PublishSingleFile=false";
            pProcess.StartInfo.UseShellExecute        = false;
            pProcess.StartInfo.RedirectStandardOutput = true;
            pProcess.StartInfo.RedirectStandardError  = true;
            pProcess.StartInfo.WindowStyle            = System.Diagnostics.ProcessWindowStyle.Hidden;
            pProcess.StartInfo.CreateNoWindow         = true;
            pProcess.OutputDataReceived              += (sender, args) => { Program.logger?.LogInformation(args.Data); };
            pProcess.ErrorDataReceived += (sender, args) => { Program.logger?.LogError(args.Data); };
            pProcess.Start();
            pProcess.BeginOutputReadLine();
            pProcess.BeginErrorReadLine();
            // string output = pProcess.StandardOutput.ReadToEnd();
            pProcess.WaitForExit();
            pProcess.CancelOutputRead();
            pProcess.CancelErrorRead();
            exitCode = pProcess.ExitCode;
        }
        if (exitCode == 0)
        {
            Program.logger?.LogInformation($"Electronize finished with ExitCode {exitCode}");
            return(true);
        }
        else
        {
            Program.logger?.LogError($"Electronize failed with ExitCode {exitCode}");
            return(false);
        }
    }
        /// <summary>
        /// Reads from Output stream to determine if process is ready
        /// </summary>
        public static ProcessOutput StartAndWaitForReady(Process process, int timeoutInSeconds, string processReadyIdentifier, string windowTitle)
        {
            if (timeoutInSeconds < 1 ||
                timeoutInSeconds > 10)
            {
                throw new ArgumentOutOfRangeException("timeoutInSeconds", "The amount in seconds should have a value between 1 and 10.");
            }

            List<string> errorOutput = new List<string>();
            List<string> standardOutput = new List<string>();
            bool processReady = false;

            process.ErrorDataReceived += (sender, args) => errorOutput.Add(args.Data);
            process.OutputDataReceived += (sender, args) =>
                {
                    standardOutput.Add(args.Data);

                    if (!string.IsNullOrEmpty(args.Data) &&
                        args.Data.Contains(processReadyIdentifier))
                    {
                        processReady = true;
                    }
                };

            process.Start();

            process.BeginErrorReadLine();
            process.BeginOutputReadLine();

            int lastResortCounter = 0;
            int timeOut = timeoutInSeconds * 10;
            while (!processReady)
            {
                Thread.Sleep(100);
                if (++lastResortCounter > timeOut)
                {
                    // we waited X seconds.
                    // for any reason the detection did not worked, eg. the identifier changed
                    // lets assume everything is still ok
                    break;
                }
            }

            process.CancelErrorRead();
            process.CancelOutputRead();

            return new ProcessOutput(errorOutput, standardOutput);
        }
        public void StartProcessAsync(string application, string arguments)
        {
            lock (SyncRoot)
            {
                if (_process != null && !_process.HasExited)
                {
                    throw new Exception(
                        string.Format("Process can't be started, because recently started process[{0}] is currently running",
                        _process.ProcessName));
                }

                var processStartInfo = new ProcessStartInfo
                {
                    CreateNoWindow = true,
                    RedirectStandardOutput = true,
                    RedirectStandardError = true,
                    RedirectStandardInput = true,
                    ErrorDialog = false,
                    UseShellExecute = false,
                    Arguments = arguments,
                    FileName = application
                };

                _process = new Process
                {
                    StartInfo = processStartInfo,
                    // Enable raising events because Process does not raise events by default
                    EnableRaisingEvents = true
                };

                // Attach the event handler for OutputDataReceived before starting the process
                _process.OutputDataReceived += PublishProcessWriteToStdOut;

                // Attach the event handler for ErrorDataReceived before starting the process
                _process.ErrorDataReceived += PublishProcessWriteToStdErr;

                // Attach the event handler for Exited before starting the process
                _process.Exited += (sender, e) =>
                {
                    _process.OutputDataReceived -= PublishProcessWriteToStdOut;
                    _process.ErrorDataReceived -= PublishProcessWriteToStdErr;

                    _process.CancelOutputRead();
                    _process.CancelErrorRead();
                    PublishProcessExitCode(_process.ExitCode);
                };

                // Start the process
                // then begin asynchronously reading the output
                // then wait for the process to exit
                // then cancel asynchronously reading the output
                Log.Debug("Starting Application[" + application + "] with Arguments[" + arguments + "]");
                _process.Start();

                _process.BeginOutputReadLine();
                _process.BeginErrorReadLine();
            }
        }
Beispiel #22
0
        /// <summary>
        /// crop detection function, called by BackgroundWorker thread
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void GetCrop(object sender, DoWorkEventArgs e)
        {
            _bw = (BackgroundWorker)sender;

            _bw.ReportProgress(-10, _cropDetectStatus);
            _bw.ReportProgress(0);

            string inputFile = AviSynthGenerator.GenerateCropDetect(_jobInfo.VideoStream.TempFile,
                                                                    _jobInfo.VideoStream.FPS,
                                                                    _jobInfo.VideoStream.Length, out _cropDetectFrames);

            string localExecutable = Path.Combine(AppSettings.ToolsPath, Executable);

            using (Process encoder = new Process())
            {
                ProcessStartInfo encoderParameter = new ProcessStartInfo(localExecutable)
                    {
                        WorkingDirectory = AppSettings.DemuxLocation,
                        Arguments = string.Format(AppSettings.CInfo,
                                                  " -threads {0:g} -i \"{1:s}\" -vf cropdetect -vcodec rawvideo -an -sn -f matroska -y NUL",
                                                  Environment.ProcessorCount + 1,
                                                  inputFile),
                        CreateNoWindow = true,
                        UseShellExecute = false,
                        RedirectStandardError = true
                    };
                encoder.StartInfo = encoderParameter;
                encoder.ErrorDataReceived += CropDetectOnErrorDataReceived;

                Log.InfoFormat("ffmpeg {0:s}", encoderParameter.Arguments);

                bool encstarted;
                try
                {
                    encstarted = encoder.Start();
                }
                catch (Exception ex)
                {
                    encstarted = false;
                    Log.ErrorFormat("ffmpeg exception: {0}", ex);
                    _jobInfo.ExitCode = -1;
                }

                if (encstarted)
                {
                    encoder.PriorityClass = AppSettings.GetProcessPriority();
                    encoder.BeginErrorReadLine();

                    _bw.ReportProgress(-1, _cropDetectStatus);

                    _jobInfo.VideoStream.CropRect = new Rectangle();

                    while (!encoder.HasExited)
                    {
                        if (_bw.CancellationPending)
                            encoder.Kill();
                        Thread.Sleep(200);
                    }
                    encoder.WaitForExit(10000);
                    encoder.CancelErrorRead();

                    _jobInfo.ExitCode = encoder.ExitCode;
                    Log.InfoFormat("Exit Code: {0:g}", _jobInfo.ExitCode);
                }
            }

            int mod16Temp;
            int mod16Width = Math.DivRem(_jobInfo.VideoStream.Width, 16, out mod16Temp);
            mod16Width *= 16;

            int mod16Height = Math.DivRem(_jobInfo.VideoStream.Height, 16, out mod16Temp);
            mod16Height *= 16;

            if (_jobInfo.VideoStream.CropRect.Width == mod16Width)
            {
                _jobInfo.VideoStream.CropRect.Width = _jobInfo.VideoStream.Width;
                Point lPoint = _jobInfo.VideoStream.CropRect.Location;
                lPoint.X = 0;
                _jobInfo.VideoStream.CropRect.Location = lPoint;
            }

            if (_jobInfo.VideoStream.CropRect.Height == mod16Height)
            {
                _jobInfo.VideoStream.CropRect.Height = _jobInfo.VideoStream.Height;
                Point lPoint = _jobInfo.VideoStream.CropRect.Location;
                lPoint.Y = 0;
                _jobInfo.VideoStream.CropRect.Location = lPoint;
            }

            _bw.ReportProgress(100);
            _jobInfo.CompletedStep = _jobInfo.NextStep;
            _jobInfo.TempFiles.Add(inputFile);
            e.Result = _jobInfo;
        }
Beispiel #23
0
        /// <summary>
        /// AC3 encode processing function, called by BackgroundWorker thread
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void DoEncodeAc3(object sender, DoWorkEventArgs e)
        {
            _bw = (BackgroundWorker)sender;

            bool use64BitEncoder = AppSettings.Use64BitEncoders &&
                                   AppSettings.Ffmpeg64Installed &&
                                   Environment.Is64BitOperatingSystem;

            int[] sampleRateArr = new[] {0, 8000, 11025, 22050, 44100, 48000};
            int[] channelArr = new[] {0, 2, 3, 4, 1};

            string status = Processing.GetResourceString("ffmpeg_encoding_audio_status");

            _bw.ReportProgress(-10, status);
            _bw.ReportProgress(0, status);

            AudioInfo item = _jobInfo.AudioStreams[_jobInfo.StreamId];

            int outChannels = -1;
            int outSampleRate = -1;

            switch (_jobInfo.AudioProfile.Type)
            {
                case ProfileType.AC3:
                    outChannels = ((AC3Profile) _jobInfo.AudioProfile).OutputChannels;
                    outChannels = channelArr[outChannels];
                    if (item.ChannelCount > 6)
                        outChannels = 6;

                    outSampleRate = ((AC3Profile) _jobInfo.AudioProfile).SampleRate;
                    outSampleRate = sampleRateArr[outSampleRate];
                    break;
                case ProfileType.Copy:
                    outChannels = item.ChannelCount > 6 ? 6 : item.ChannelCount;
                    outSampleRate = item.SampleRate;
                    if (_jobInfo.EncodingProfile.OutFormat == OutputType.OutputDvd && outSampleRate != 48000)
                        outSampleRate = 48000;
                    break;
            }
            string inputFile = AviSynthGenerator.GenerateAudioScript(item.TempFile, item.Format, item.FormatProfile,
                                                                     item.ChannelCount, outChannels, item.SampleRate,
                                                                     outSampleRate);
            string outFile = Processing.CreateTempFile(item.TempFile, "encoded.ac3");

            string localExecutable = Path.Combine(AppSettings.ToolsPath, use64BitEncoder ? Executable64 : Executable);

            DateTime startTime = DateTime.Now;

            using (Process encoder = new Process(),
                           decoder = BePipe.GenerateProcess(inputFile))
            {
                ProcessStartInfo encoderParameter = new ProcessStartInfo(localExecutable)
                    {
                        WorkingDirectory = AppSettings.DemuxLocation,
                        Arguments =
                            FfmpegCommandLineGenerator.GenerateAC3EncodeLine(
                                _jobInfo,
                                "-",
                                outFile),
                        CreateNoWindow = true,
                        UseShellExecute = false,
                        RedirectStandardError = true,
                        RedirectStandardInput = true
                    };
                encoder.StartInfo = encoderParameter;

                _localItem = item;
                _encodingStart = startTime;
                encoder.ErrorDataReceived += Ac3EncodeOnErrorDataReceived;

                Log.InfoFormat("ffmpeg {0:s}", encoderParameter.Arguments);

                bool encStarted;
                bool decStarted;
                try
                {
                    encStarted = encoder.Start();
                }
                catch (Exception ex)
                {
                    encStarted = false;
                    Log.ErrorFormat("ffmpeg exception: {0}", ex);
                    _jobInfo.ExitCode = -1;
                }

                try
                {
                    decStarted = decoder.Start();
                }
                catch (Exception ex)
                {
                    decStarted = false;
                    Log.ErrorFormat("bepipe exception: {0}", ex);
                    _jobInfo.ExitCode = -1;
                }

                if (encStarted && decStarted)
                {
                    encoder.PriorityClass = AppSettings.GetProcessPriority();
                    encoder.BeginErrorReadLine();
                    decoder.PriorityClass = AppSettings.GetProcessPriority();

                    Processing.CopyStreamToStream(decoder.StandardOutput.BaseStream, encoder.StandardInput.BaseStream,
                                                  32768,
                                                  (src, dst, exc) =>
                                                      {
                                                          src.Close();
                                                          dst.Close();

                                                          if (exc == null) return;

                                                          Log.Debug(exc.Message);
                                                          Log.Debug(exc.StackTrace);
                                                      });

                    while (!encoder.HasExited)
                    {
                        if (_bw.CancellationPending)
                        {
                            encoder.Kill();
                            decoder.Kill();
                        }
                        Thread.Sleep(200);
                    }

                    encoder.WaitForExit(10000);
                    encoder.CancelErrorRead();
                    decoder.WaitForExit(10000);

                    _jobInfo.ExitCode = encoder.ExitCode;
                    Log.InfoFormat("Exit Code: {0:g}", _jobInfo.ExitCode);

                    if (_jobInfo.ExitCode == 0)
                    {
                        _jobInfo.TempFiles.Add(inputFile);
                        _jobInfo.TempFiles.Add(item.TempFile);
                        _jobInfo.TempFiles.Add(item.TempFile + ".d2a");
                        _jobInfo.TempFiles.Add(item.TempFile + ".ffindex");
                        item.TempFile = outFile;
                        AudioHelper.GetStreamInfo(item);
                    }
                }
            }

            _bw.ReportProgress(100);
            _jobInfo.CompletedStep = _jobInfo.NextStep;
            e.Result = _jobInfo;
        }
Beispiel #24
0
        /// <summary>
        /// Demux processing function, called by BackgroundWorker thread
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void DoDemux(object sender, DoWorkEventArgs e)
        {
            _bw = (BackgroundWorker)sender;

            string status = Processing.GetResourceString("ffmpeg_demuxing_status");

            _bw.ReportProgress(-10, status);
            _bw.ReportProgress(0, status);

            string inputFile = string.IsNullOrEmpty(_jobInfo.TempInput) ? _jobInfo.InputFile : _jobInfo.TempInput;
            _jobInfo.VideoStream.TempFile = inputFile;
            try
            {
                _jobInfo.MediaInfo = Processing.GetMediaInfo(inputFile);
            }
            catch (TimeoutException ex)
            {
                Log.Error(ex);
            }

            StringBuilder sb = new StringBuilder();
            sb.AppendFormat("-i \"{0}\" ", inputFile);

            bool hasStreams = false;

            for (int i = 0; i < _jobInfo.AudioStreams.Count; i++)
            {
                AudioInfo item = _jobInfo.AudioStreams[i];

                string ext = StreamFormat.GetFormatExtension(item.Format, item.FormatProfile, false);

                string acodec;

                switch (ext)
                {
                    case "flac":
                        acodec = "flac";
                        break;
                    case "wav":
                        acodec = "pcm_s16le";
                        break;
                    default:
                        acodec = "copy";
                        break;
                }

                string formattedExt = string.Format("demuxed.{0:g}.{1}.{2}", item.StreamId, item.LangCode, ext);

                item.TempFile =
                    Processing.CreateTempFile(
                        string.IsNullOrEmpty(_jobInfo.TempInput) ? _jobInfo.JobName : _jobInfo.TempInput, formattedExt);

                sb.AppendFormat("-map 0:a:{0:0} -vn -c:a {1} -y \"{2}\" ", item.StreamKindId, acodec, item.TempFile);

                hasStreams = true;
                _jobInfo.AudioStreams[i] = item;
            }

            string localExecutable = Path.Combine(AppSettings.ToolsPath, Executable);
            if (hasStreams)
            {
                using (Process encoder = new Process())
                {
                    ProcessStartInfo parameter = new ProcessStartInfo(localExecutable)
                        {
                            WorkingDirectory = AppSettings.DemuxLocation,
                            Arguments = sb.ToString(),
                            CreateNoWindow = true,
                            UseShellExecute = false,
                            RedirectStandardError = true
                        };
                    encoder.StartInfo = parameter;
                    encoder.ErrorDataReceived += DemuxOnErrorDataReceived;

                    Log.InfoFormat("ffmpeg {0:s}", parameter.Arguments);

                    bool started;
                    try
                    {
                        started = encoder.Start();
                    }
                    catch (Exception ex)
                    {
                        started = false;
                        Log.ErrorFormat("ffmpeg exception: {0}", ex);
                        _jobInfo.ExitCode = -1;
                    }

                    if (started)
                    {
                        encoder.PriorityClass = AppSettings.GetProcessPriority();
                        encoder.BeginErrorReadLine();

                        _bw.ReportProgress(-1, status);

                        while (!encoder.HasExited)
                        {
                            if (_bw.CancellationPending)
                                encoder.Kill();
                            Thread.Sleep(200);
                        }

                        encoder.WaitForExit(10000);
                        encoder.CancelErrorRead();

                        _jobInfo.ExitCode = encoder.ExitCode;

                        if (_jobInfo.ExitCode == 0)
                            _jobInfo.VideoStream.TempFile = inputFile;

                        Log.InfoFormat("Exit Code: {0:g}", _jobInfo.ExitCode);
                    }
                }
            }
            else
                _jobInfo.ExitCode = 0;

            _bw.ReportProgress(100);
            _jobInfo.CompletedStep = _jobInfo.NextStep;
            e.Result = _jobInfo;
        }
		void BuildSatelliteAssembly (string cultureName, List <string> files)
		{
			string assemblyPath = BuildAssemblyPath (cultureName);
			var info = new ProcessStartInfo ();
			var al = new Process ();

			string arguments = SetAlPath (info);
			var sb = new StringBuilder (arguments);

			sb.Append ("/c:\"" + cultureName + "\" ");
			sb.Append ("/t:lib ");
			sb.Append ("/out:\"" + assemblyPath + "\" ");
			if (mainAssembly != null)
				sb.Append ("/template:\"" + mainAssembly.Location + "\" ");
			
			string responseFilePath = assemblyPath + ".response";
			using (FileStream fs = File.OpenWrite (responseFilePath)) {
				using (StreamWriter sw = new StreamWriter (fs)) {
					foreach (string f in files) 
						sw.WriteLine ("/embed:\"" + f + "\" ");
				}
			}
			sb.Append ("@\"" + responseFilePath + "\"");
			
			info.Arguments = sb.ToString ();
			info.CreateNoWindow = true;
			info.UseShellExecute = false;
			info.RedirectStandardOutput = true;
			info.RedirectStandardError = true;
			
			al.StartInfo = info;

			var alOutput = new StringCollection ();
			var alMutex = new Mutex ();
			DataReceivedEventHandler outputHandler = (object sender, DataReceivedEventArgs args) => {
				if (args.Data != null) {
					alMutex.WaitOne ();
					alOutput.Add (args.Data);
					alMutex.ReleaseMutex ();
				}
			};
			
			al.ErrorDataReceived += outputHandler;
			al.OutputDataReceived += outputHandler;

			// TODO: consider using asynchronous processes
			try {
				al.Start ();
			} catch (Exception ex) {
				throw new HttpException (String.Format ("Error running {0}", al.StartInfo.FileName), ex);
			}

			Exception alException = null;
			int exitCode = 0;
			try {
				al.BeginOutputReadLine ();
				al.BeginErrorReadLine ();
				al.WaitForExit ();
				exitCode = al.ExitCode;
			} catch (Exception ex) {
				alException = ex;
			} finally {
				al.CancelErrorRead ();
				al.CancelOutputRead ();
				al.Close ();
			}

			if (exitCode != 0 || alException != null) {
				// TODO: consider adding a new type of compilation exception,
				// tailored for al
				CompilerErrorCollection errors = null;
				
				if (alOutput.Count != 0) {
					foreach (string line in alOutput) {
						if (!line.StartsWith ("ALINK: error ", StringComparison.Ordinal))
							continue;
						if (errors == null)
							errors = new CompilerErrorCollection ();

						int colon = line.IndexOf (':', 13);
						string errorNumber = colon != -1 ? line.Substring (13, colon - 13) : "Unknown";
						string errorText = colon != -1 ? line.Substring (colon + 1) : line.Substring (13);
						
						errors.Add (new CompilerError (Path.GetFileName (assemblyPath), 0, 0, errorNumber, errorText));
					}
				}
				
				throw new CompilationException (Path.GetFileName (assemblyPath), errors, null);
			}
		}
    /// <summary>
    /// Starts the comparison process.
    /// </summary>
    private void StartProcess()
    {
        if (comparexe != null && CurrentState == State.START)
            StopProcess();

        comparexe = new System.Diagnostics.Process();
        comparexe.StartInfo.CreateNoWindow = true;
        comparexe.StartInfo.UseShellExecute = false;
        comparexe.StartInfo.RedirectStandardOutput = true;
        comparexe.StartInfo.RedirectStandardError = true;
        comparexe.StartInfo.FileName = System.IO.Path.GetFullPath(_exe_filename);
        comparexe.StartInfo.Arguments =
            string.Format("{0} {1} {2} {3} {4}",
                  _ref_db_filename,
                  UseWeightsFile ? _wei_db_filename : "Null",
                  _rec_filename,
                  DrawPlots ? "-p" : "",
                  Properties.ActivityToString(ActionName));
        comparexe.EnableRaisingEvents = true;
        comparexe.OutputDataReceived += (sender, e) =>
        {
            lock (_buffer)
            {
                _buffer.Add(e.Data);
            }
        };
        comparexe.ErrorDataReceived += (sender, e) =>
        {
            if (e.Data != null)
                UnityEngine.Debug.LogError("Compare process says: " + e.Data);
        };
        comparexe.Exited += (sender, e) =>
        {
            comparexe.CancelOutputRead();
            comparexe.CancelErrorRead();
            UnityEngine.Debug.Log("Compare process exited!");
        };

        if(comparexe.Start())
        {
            comparexe.BeginOutputReadLine();
            comparexe.BeginErrorReadLine();
            StartCoroutine("StartConsole");
        }
    }
        void BuildImageTrackingAssets()
        {
            if (Directory.Exists(Application.streamingAssetsPath))
            {
                s_ShouldDeleteStreamingAssetsFolder = false;
            }
            else
            {
                // Delete the streaming assets folder at the end of the build pipeline
                // since it did not exist before we created it here.
                s_ShouldDeleteStreamingAssetsFolder = true;
                Directory.CreateDirectory(Application.streamingAssetsPath);
            }

            if (!Directory.Exists(ARCoreImageTrackingProvider.k_StreamingAssetsPath))
            {
                Directory.CreateDirectory(ARCoreImageTrackingProvider.k_StreamingAssetsPath);
            }

            try
            {
                string[] libGuids = AssetDatabase.FindAssets("t:xrReferenceImageLibrary");
                if (libGuids == null || libGuids.Length == 0)
                {
                    return;
                }

                // This is how much each library will contribute to the overall progress
                var          progressPerLibrary = 1f / libGuids.Length;
                const string progressBarText    = "Building ARCore Image Library";

                for (int libraryIndex = 0; libraryIndex < libGuids.Length; ++libraryIndex)
                {
                    var libGuid         = libGuids[libraryIndex];
                    var overallProgress = progressPerLibrary * libraryIndex;
                    var numSteps        = libGuids.Length + 1; // 1 per image plus arcoreimg
                    var libraryPath     = AssetDatabase.GUIDToAssetPath(libGuid);
                    var imageLib        = AssetDatabase.LoadAssetAtPath <XRReferenceImageLibrary>(libraryPath);

                    EditorUtility.DisplayProgressBar(progressBarText, imageLib.name, overallProgress);

                    var tempDirectory      = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N"));
                    var inputImageListPath = Path.Combine(tempDirectory, Guid.NewGuid().ToString("N") + ".txt");

                    // prepare text file for arcoreimg to read from
                    try
                    {
                        Directory.CreateDirectory(tempDirectory);
                        using (var writer = new StreamWriter(inputImageListPath, false))
                        {
                            for (int i = 0; i < imageLib.count; i++)
                            {
                                var referenceImage     = imageLib[i];
                                var textureGuid        = referenceImage.textureGuid.ToString("N");
                                var assetPath          = AssetDatabase.GUIDToAssetPath(textureGuid);
                                var referenceImageName = referenceImage.guid.ToString("N");

                                EditorUtility.DisplayProgressBar(
                                    progressBarText,
                                    imageLib.name + ": " + assetPath,
                                    overallProgress + progressPerLibrary * i / numSteps);

                                var texture = AssetDatabase.LoadAssetAtPath <Texture2D>(assetPath);
                                if (texture == null)
                                {
                                    throw new BuildFailedException(string.Format(
                                                                       "ARCore Image Library Generation: Reference library at '{0}' is missing a texture at index {1}.",
                                                                       libraryPath, i));
                                }

                                var extension = Path.GetExtension(assetPath);
                                var entry     = new StringBuilder();

                                if (string.Equals(extension, ".jpg", StringComparison.Ordinal) ||
                                    string.Equals(extension, ".jpeg", StringComparison.Ordinal) ||
                                    string.Equals(extension, ".png", StringComparison.Ordinal))
                                {
                                    // If lowercase jpg or png, use image as is
                                    entry.Append($"{referenceImageName}|{assetPath}");
                                }
                                else if (string.Equals(extension, ".jpg", StringComparison.OrdinalIgnoreCase) ||
                                         string.Equals(extension, ".jpeg", StringComparison.OrdinalIgnoreCase) ||
                                         string.Equals(extension, ".png", StringComparison.OrdinalIgnoreCase))
                                {
                                    // If jpg or png but NOT lowercase, then copy it to a temporary file that uses lowercase
                                    var pathWithLowercaseExtension = Path.Combine(tempDirectory, textureGuid + extension.ToLower());
                                    File.Copy(assetPath, pathWithLowercaseExtension);
                                    entry.Append($"{referenceImageName}|{pathWithLowercaseExtension}");
                                }
                                else
                                {
                                    var pngFilename = Path.Combine(tempDirectory, textureGuid + ".png");
                                    var bytes       = ImageConversion.EncodeToPNG(texture);
                                    if (bytes == null)
                                    {
                                        throw new BuildFailedException(string.Format(
                                                                           "ARCore Image Library Generation: Texture format for image '{0}' not supported. Inspect other error messages emitted during this build for more details.",
                                                                           texture.name));
                                    }

                                    File.WriteAllBytes(pngFilename, bytes);
                                    entry.Append($"{referenceImageName}|{pngFilename}");
                                }

                                if (referenceImage.specifySize)
                                {
                                    entry.Append($"|{referenceImage.width.ToString("G", CultureInfo.InvariantCulture)}");
                                }

                                writer.WriteLine(entry.ToString());
                            }
                        }
                    }
                    catch
                    {
                        Directory.Delete(tempDirectory, true);
                        throw;
                    }

                    // launch arcoreimg and wait for it to return so we can process the asset
                    try
                    {
                        EditorUtility.DisplayProgressBar(
                            progressBarText,
                            imageLib.name + ": Invoking arcoreimg",
                            overallProgress + progressPerLibrary * (numSteps - 1) / numSteps);

                        var packagePath = Path.GetFullPath("Packages/com.unity.xr.arcore");

                        string extension    = "";
                        string platformName = "Undefined";
    #if UNITY_EDITOR_WIN
                        platformName = "Windows";
                        extension    = ".exe";
    #elif UNITY_EDITOR_OSX
                        platformName = "MacOS";
                        extension    = "";
    #elif UNITY_EDITOR_LINUX
                        platformName = "Linux";
                        extension    = "";
    #endif
                        var arcoreimgPath = Path.Combine(packagePath, "Tools~", platformName, "arcoreimg" + extension);

    #if UNITY_EDITOR_OSX || UNITY_EDITOR_LINUX
                        SetExecutablePermission(arcoreimgPath);
    #endif

                        var startInfo = new Diag.ProcessStartInfo();
                        startInfo.WindowStyle = Diag.ProcessWindowStyle.Hidden;
                        startInfo.FileName    = arcoreimgPath;

                        // This file must have the .imgdb extension (the tool adds it otherwise)
                        var outputDbPath = ARCoreImageTrackingProvider.GetPathForLibrary(imageLib);

                        if (File.Exists(outputDbPath))
                        {
                            File.Delete(outputDbPath);
                        }

                        startInfo.Arguments = string.Format(
                            "build-db --input_image_list_path={0} --output_db_path={1}",
                            $"\"{inputImageListPath}\"",
                            $"\"{outputDbPath}\"");

                        startInfo.UseShellExecute        = false;
                        startInfo.RedirectStandardOutput = true;
                        startInfo.RedirectStandardError  = true;
                        startInfo.CreateNoWindow         = true;

                        var process = new Diag.Process();
                        process.StartInfo           = startInfo;
                        process.EnableRaisingEvents = true;
                        var stdout = new StringBuilder();
                        var stderr = new StringBuilder();
                        process.OutputDataReceived += (sender, args) => stdout.Append(args.Data.ToString());
                        process.ErrorDataReceived  += (sender, args) => stderr.Append(args.Data.ToString());
                        process.Start();
                        process.BeginOutputReadLine();
                        process.BeginErrorReadLine();
                        process.WaitForExit();
                        process.CancelOutputRead();
                        process.CancelErrorRead();

                        if (!File.Exists(outputDbPath))
                        {
                            throw new BuildFailedException(string.Format(
                                                               "Failed to generate image database. Output from arcoreimg:\n\nstdout:\n{0}\n====\n\nstderr:\n{1}\n====",
                                                               stdout.ToString(),
                                                               stderr.ToString()));
                        }
                    }
                    catch
                    {
                        Debug.LogErrorFormat("Failed to generated ARCore reference image library '{0}'", imageLib.name);
                        throw;
                    }
                    finally
                    {
                        Directory.Delete(tempDirectory, true);
                    }
                }
            }
            catch
            {
                RemoveGeneratedStreamingAssets();
                throw;
            }
        }
Beispiel #28
0
		public override void StartBuild(ProjectBuildOptions options, IBuildFeedbackSink feedbackSink)
		{
			string productDir = GetPathFromRegistry(@"SOFTWARE\Microsoft\VisualStudio\9.0\Setup\VC", "ProductDir");
			
			string batFile = "vcvars32.bat";
			if (options.Platform == "x64") {
				batFile = "vcvars64.bat";
			}
			
			string commonTools =
				GetFile(productDir != null ? Path.Combine(productDir, "bin\\" + batFile) : null)
				?? GetFile("%VS90COMNTOOLS%\\" + batFile)
				??  GetFile("%VS80COMNTOOLS%\\" + batFile);
			
			Process p = new Process();
			p.StartInfo.FileName = "cmd.exe";
			p.StartInfo.Arguments = "/C";
			if (!string.IsNullOrEmpty(commonTools)) {
				p.StartInfo.Arguments += " call \"" + commonTools + "\" &&";
			}
			p.StartInfo.Arguments += " vcbuild";
			if (options.Target == BuildTarget.Build) {
				// OK
			} else if (options.Target == BuildTarget.Clean) {
				p.StartInfo.Arguments += " /clean";
			} else if (options.Target == BuildTarget.Rebuild) {
				p.StartInfo.Arguments += " /rebuild";
			}
			p.StartInfo.Arguments += " /showenv";
			p.StartInfo.Arguments += " \"" + this.FileName + "\"";
			p.StartInfo.Arguments += " \"/error:Error: \"";
			p.StartInfo.Arguments += " \"/warning:Warning: \"";
			
			p.StartInfo.WorkingDirectory = this.Directory;
			p.StartInfo.RedirectStandardOutput = true;
			p.StartInfo.RedirectStandardError = true;
			p.StartInfo.CreateNoWindow = true;
			p.StartInfo.UseShellExecute = false;
			p.StartInfo.EnvironmentVariables["VCBUILD_DEFAULT_CFG"] = options.Configuration + "|" + options.Platform;
			p.StartInfo.EnvironmentVariables["SolutionPath"] = ParentSolution.FileName;
			
			p.EnableRaisingEvents = true;
			p.OutputDataReceived += delegate(object sender, DataReceivedEventArgs e) {
				if (!string.IsNullOrEmpty(e.Data)) {
					BuildError error = ParseError(e.Data);
					if (error != null)
						feedbackSink.ReportError(error);
					else
						feedbackSink.ReportMessage(e.Data);
				}
			};
			p.ErrorDataReceived += delegate(object sender, DataReceivedEventArgs e) {
				if (!string.IsNullOrEmpty(e.Data)) {
					BuildError error = ParseError(e.Data);
					if (error != null)
						feedbackSink.ReportError(error);
					else
						feedbackSink.ReportError(new BuildError(null, e.Data));
				}
			};
			p.Exited += delegate(object sender, EventArgs e) {
				p.CancelErrorRead();
				p.CancelOutputRead();
				feedbackSink.Done(p.ExitCode == 0);
				p.Dispose();
			};
			
			feedbackSink.ReportMessage("Building " + this.Name);
			feedbackSink.ReportMessage(p.StartInfo.FileName + " " + p.StartInfo.Arguments);
			p.Start();
			p.BeginOutputReadLine();
			p.BeginErrorReadLine();
		}
Beispiel #29
0
        /// <summary>
        /// Backup files of the given file specifications and run
        /// the backup scripts to copy the backup around as needed.
        /// </summary>
        public bool BackupFiles()
        {
            // Return if backup is disabled.
            if ( !moProfile.bValue("-BackupFiles", true) )
            {
                this.LogIt("Backup files is disabled.");
                return true;
            }
            // Return if cleanup is enabled and it was stopped.
            if (  moProfile.bValue("-CleanupFiles", true) && this.bMainLoopStopped )
                return true;
            else
                this.bMainLoopStopped = false;

            bool    lbBackupFiles = false;
            int     liBackupBeginScriptErrors = 0;          // The error count returned by the "backup begin" script.
            int     liBackupDoneScriptFileCopyFailures = 0; // The copy failures count returned by the "backup done" script.
            int     liCurrentBackupDevicesBitField = 0;     // The current backup devices returned by the "backup done" script.

            // Get the embedded zip compression tool from the EXE.
            tvFetchResource.ToDisk(Application.ResourceAssembly.GetName().Name, mcsZipToolExeFilename, null);
            tvFetchResource.ToDisk(Application.ResourceAssembly.GetName().Name, mcsZipToolDllFilename, null);

            // Get all backup sets.
            tvProfile loBackupSetsProfile = moProfile.oOneKeyProfile("-BackupSet");

            miBackupSets = loBackupSetsProfile.Count;
            miBackupSetsRun = 0;
            miBackupSetsGood = 0;

            // Release the lock on the profile file 
            // so that it can be backed up as well.
            moProfile.bEnableFileLock = false;

            try
            {
                lbBackupFiles = true;

                // Run the "backup begin" script and return any errors.
                if ( moProfile.bValue("-BackupBeginScriptEnabled", true) )
                    liBackupBeginScriptErrors = this.iBackupBeginScriptErrors();
                else
                    this.LogIt("The \"backup begin\" script is disabled.");

                string  lsZipToolFileListPathFile = moProfile.sRelativeToProfilePathFile(this.ZipToolFileListPathFile);
                string  lsBackupPathFiles1 = null;      // The first file specification in the set (for logging).
                int     liFileCount = 0;                // The number of file specifications in the current set.

                foreach (DictionaryEntry loEntry in loBackupSetsProfile)
                {
                    System.Windows.Forms.Application.DoEvents();
                    if ( this.bMainLoopStopped )
                        break;

                    string lsProcessPathFile = moProfile.sRelativeToProfilePathFile(moProfile.sValue("-ZipToolEXE", mcsZipToolExeFilename));

                    // Increment the backup set counter.
                    miBackupSetsRun++;

                    // Convert the current backup set from a command-line string to a profile oject.
                    moCurrentBackupSet = new tvProfile(loEntry.Value.ToString());

                    // Get the list of folders to backup within the current backup set.
                    tvProfile       loFolderToBackupProfile = moCurrentBackupSet.oOneKeyProfile(
                                            "-FolderToBackup");
                    StreamWriter    loBackupFileListStreamWriter = null;

                    liFileCount = 0;

                    try
                    {
                        // Create the backup file list file.
                        loBackupFileListStreamWriter = new StreamWriter(moProfile.sRelativeToProfilePathFile(
                                lsZipToolFileListPathFile), false);

                        // Write the list of files to compress.
                        foreach (DictionaryEntry loFolderToBackup in loFolderToBackupProfile)
                        {
                            System.Windows.Forms.Application.DoEvents();
                            if ( this.bMainLoopStopped )
                                break;

                            string  lsFolderToBackup = loFolderToBackup.Value.ToString().Trim();
                            string  lsBackupPathFiles = null;
                                    if ( Directory.Exists(lsFolderToBackup) )
                                        lsBackupPathFiles = Path.Combine(lsFolderToBackup, this.sBackupFileSpec());
                                    else
                                        lsBackupPathFiles = lsFolderToBackup;
                                        // If the given "lsFolderToBackup" is not actually a folder, assume it's a single file (or a file mask).

                            if ( 1 == ++liFileCount )
                            {
                                if ( moProfile.ContainsKey("-ActivateAlreadyRunningInstance") )
                                {
                                    // Backup just the backup profile file as well (to avoid file contention problems with the main instance).
                                    loBackupFileListStreamWriter.WriteLine(this.sExeRelativePath(lsProcessPathFile, moProfile.sLoadedPathFile));
                                }
                                else
                                {
                                    // Backup the backup as well.
                                    loBackupFileListStreamWriter.WriteLine(this.sExeRelativePath(lsProcessPathFile, Path.GetDirectoryName(moProfile.sLoadedPathFile)));

                                    // Also make an extra - easily accessible - backup of just the profile file.
                                    lsBackupPathFiles1 = moProfile.sBackupPathFile;     // Discard the pathfile name.
                                }

                                // Save the first pathfile specification (ie. folder) for later reference.
                                lsBackupPathFiles1 = lsBackupPathFiles;
                            }

                            loBackupFileListStreamWriter.WriteLine(this.sExeRelativePath(lsProcessPathFile, lsBackupPathFiles));
                        }
                    }
                    catch (Exception ex)
                    {
                        lbBackupFiles = false;
                        if ( null != this.oUI )
                        this.oUI.bBackupRunning = false;
                        this.ShowError(string.Format("File Write Failure: \"{0}\"\r\n"
                                , lsZipToolFileListPathFile) + ex.Message
                                , "Failed Writing File"
                                );
                    }
                    finally
                    {
                        if ( null != loBackupFileListStreamWriter )
                            loBackupFileListStreamWriter.Close();
                    }

                    // The backup output path file will be dated and unique.
                    msCurrentBackupOutputPathFile = this.sBackupOutputPathFile();

                    string  lsProcessArgs = moProfile.sValue("-ZipToolEXEargs"
                                    , "a -ssw \"{BackupOutputPathFile}\" @\"{BackupPathFiles}\" -w\"{BackupOutputPath}\" ")
                                    + " " + moProfile.sValue("-ZipToolEXEargsMore", "");
                            lsProcessArgs = lsProcessArgs.Replace("{BackupPathFiles}", lsZipToolFileListPathFile);
                            lsProcessArgs = lsProcessArgs.Replace("{BackupOutputPath}", Path.GetDirectoryName(msCurrentBackupOutputPathFile));
                            lsProcessArgs = lsProcessArgs.Replace("{BackupOutputPathFile}", msCurrentBackupOutputPathFile);
                    string  lsArchivePath = Path.GetDirectoryName(msCurrentBackupOutputPathFile);
                            if ( !Directory.Exists(lsArchivePath) )
                                try
                                {
                                    Directory.CreateDirectory(lsArchivePath);
                                }
                                catch (Exception ex)
                                {
                                    lbBackupFiles = false;
                                    if ( null != this.oUI )
                                    this.oUI.bBackupRunning = false;
                                    this.ShowError(
                                              string.Format("Folder: \"{0}\"\r\n", lsArchivePath) + ex.Message
                                            , "Error Creating Archive Folder"
                                            );
                                }

                    Process loProcess = new Process();
                            loProcess.ErrorDataReceived += new DataReceivedEventHandler(this.BackupProcessOutputHandler);
                            loProcess.OutputDataReceived += new DataReceivedEventHandler(this.BackupProcessOutputHandler);
                            loProcess.StartInfo.FileName = lsProcessPathFile;
                            loProcess.StartInfo.Arguments = lsProcessArgs;
                            loProcess.StartInfo.WorkingDirectory = "\\";
                            loProcess.StartInfo.UseShellExecute = false;
                            loProcess.StartInfo.RedirectStandardError = true;
                            loProcess.StartInfo.RedirectStandardInput = true;
                            loProcess.StartInfo.RedirectStandardOutput = true;
                            loProcess.StartInfo.CreateNoWindow = true;

                    string  lsLastRunCmd = lsProcessPathFile + " " + lsProcessArgs;
                    string  lsFileAsStream = string.Format(@"
cd\
@prompt $
{0}
@echo.
cd {1}
@pause
"                                           , lsLastRunCmd
                                            , Path.GetDirectoryName(moProfile.sExePathFile)
                                            );

                    moProfile.Remove("-PreviousBackupOk");
                    moProfile.Save();

                    // This lets the user see what was run (or rerun it).
                    string          lsLastRunFile = moProfile.sValue("-ZipToolLastRunCmdPathFile", "Run Last Backup.cmd");
                    StreamWriter    loLastRunFileStreamWriter = null;

                    try
                    {
                        loLastRunFileStreamWriter = new StreamWriter(moProfile.sRelativeToProfilePathFile(lsLastRunFile), false);
                        loLastRunFileStreamWriter.Write(lsFileAsStream);
                    }
                    catch (Exception ex)
                    {
                        lbBackupFiles = false;
                        if ( null != this.oUI )
                        this.oUI.bBackupRunning = false;
                        this.ShowError(string.Format("File Write Failure: \"{0}\"\r\n"
                                , lsLastRunFile) + ex.Message
                                , "Failed Writing File"
                                );
                    }
                    finally
                    {
                        if ( null != loLastRunFileStreamWriter )
                            loLastRunFileStreamWriter.Close();
                    }

                    string  lsFilesSuffix = liFileCount <= 1 ? ""
                            : string.Format(" + {0} other file specification" + (1 == (liFileCount - 1) ? "" : "s")
                                    , liFileCount - 1);
                                
                    this.LogIt("");
                    this.LogIt("Backup started ...");
                    this.LogIt("");
                    this.LogIt(string.Format("Backup: \"{0}\"{1}", lsBackupPathFiles1, lsFilesSuffix));
                    this.LogIt("");
                    this.LogIt("Backup command: " + lsLastRunCmd);

                    System.Windows.Forms.Application.DoEvents();

                    loProcess.Start();

                    // Start output to console also.
                    if ( loProcess.StartInfo.RedirectStandardError )
                        loProcess.BeginErrorReadLine();
                    if ( loProcess.StartInfo.RedirectStandardOutput )
                        loProcess.BeginOutputReadLine();

                    // Wait for the backup process to finish.
                    while ( !this.bMainLoopStopped && !loProcess.HasExited )
                    {
                        System.Windows.Forms.Application.DoEvents();
                        System.Threading.Thread.Sleep(moProfile.iValue("-MainLoopSleepMS", 100));
                    }

                    // Do final wait then call "WaitForExit()" to flush the output steams.
                    if ( !this.bMainLoopStopped && loProcess.WaitForExit(1000 * moProfile.iValue("-KillProcessOrderlyWaitSecs", 30)) )
                        loProcess.WaitForExit();

                    // Stop output to console.
                    if ( loProcess.StartInfo.RedirectStandardError )
                        loProcess.CancelErrorRead();
                    if ( loProcess.StartInfo.RedirectStandardOutput )
                        loProcess.CancelOutputRead();

                    // If a stop request came through, kill the backup process.
                    if ( this.bMainLoopStopped && !this.bKillProcess(loProcess) )
                        this.ShowError("The backup process could not be stopped."
                                , "Backup Failed");

                    // The backup process finished uninterrupted.
                    if ( !this.bMainLoopStopped )
                    {
                        if ( 0 != loProcess.ExitCode )
                        {
                            // The backup process failed.
                            this.LogIt(string.Format("The backup to \"{0}\" failed."
                                    , Path.GetFileName(msCurrentBackupOutputPathFile)));

                            // Run the "backup failed" script.
                            if ( moProfile.bValue("-BackupFailedScriptEnabled", true) )
                                this.BackupFailedScript();
                            else
                                this.LogIt("The \"backup failed\" script is disabled.");
                        }
                        else
                        {
                            // The backup process finished without error.
                            this.LogIt(string.Format("The backup to \"{0}\" was successful."
                                    , Path.GetFileName(msCurrentBackupOutputPathFile)));

                            double ldCompositeResult = 0;   // Composite result returned by the "backup done" script.

                            // Run the "backup done" script and return the failed file count with bit field.
                            // The exit code is defined in the script as a combination of two integers:
                            // a bit field of found backup devices and a count of copy failures (99 max).
                            if ( moProfile.bValue("-BackupDoneScriptEnabled", true) )
                                ldCompositeResult = this.iBackupDoneScriptCopyFailuresWithBitField() / 100.0;
                            else
                                this.LogIt("The \"backup done\" script is disabled.");

                            // The integer part of the composite number is the bit field.
                            // This will be used below after all backup sets are run. We
                            // assume that the bit field remains constant between sets.
                            liCurrentBackupDevicesBitField = (int)ldCompositeResult;

                            // The fractional part (x 100) is the actual number of copy failures.
                            int liCopyFailures = (int)Math.Round(100 * (ldCompositeResult - liCurrentBackupDevicesBitField));

                            // Add failed files from the current backup set to the total.
                            liBackupDoneScriptFileCopyFailures += liCopyFailures;

                            // Increment how many backup sets have succeeded so far.
                            if ( 0 == liCopyFailures )
                                miBackupSetsGood++;
                        }
                    }

                    loProcess.Close();
                }
            }
            catch (Exception ex)
            {
                lbBackupFiles = false;
                if ( null != this.oUI )
                this.oUI.bBackupRunning = false;
                this.ShowError(ex.Message, "Backup Failed");
            }

            if ( lbBackupFiles && !this.bMainLoopStopped )
            {
                this.LogIt("");

                // Don't bother with the system tray message 
                // if the background timer is not running.
                string  lsSysTrayMsg = null;
                        if ( moProfile.bValue("-AutoStart", true) )
                            lsSysTrayMsg = this.sSysTrayMsg;

                List<char> loMissingBackupDevices = new List<char>();

                // Compare the bit field of current backup devices to the bit field of
                // devices selected by the user to be used by the "backup done" script.
                if ( moProfile.bValue("-BackupDoneScriptEnabled", true) )
                    loMissingBackupDevices = this.oMissingBackupDevices(liCurrentBackupDevicesBitField);

                if (        miBackupSetsGood != miBackupSetsRun
                        ||  0 != liBackupBeginScriptErrors
                        ||  0 != liBackupDoneScriptFileCopyFailures
                        ||  0 != loMissingBackupDevices.Count
                        )
                {
                    if ( 0 != loMissingBackupDevices.Count )
                        moProfile["-PreviousBackupDevicesMissing"] = true;
                    else
                        moProfile["-PreviousBackupDevicesMissing"] = false;

                    this.SetBackupFailed();

                    lbBackupFiles = false;
                    if ( null != this.oUI )
                    this.oUI.bBackupRunning = false;

                    this.ShowError("The backup failed. Check the log for errors." + lsSysTrayMsg
                            , "Backup Failed");
                }
                else
                {
                    moProfile["-PreviousBackupDevicesMissing"] = false;
                    moProfile["-PreviousBackupOk"] = true;
                    moProfile["-PreviousBackupTime"] = DateTime.Now;
                    moProfile.Save();

                    this.Show("Backup finished successfully." + lsSysTrayMsg
                            , "Backup Finished"
                            , tvMessageBoxButtons.OK
                            , tvMessageBoxIcons.Done
                            , "-CurrentBackupFinished"
                            );
                }
            }

            if ( this.bMainLoopStopped )
            {
                this.LogIt("Backup process stopped.");
                this.bMainLoopStopped = false;
                lbBackupFiles = false;
            }

            // Turn on the lock that was turned off when we started.
            moProfile.bEnableFileLock = true;

            return lbBackupFiles;
        }
Beispiel #30
0
        public void DoEncode(object sender, DoWorkEventArgs e)
        {
            _bw = (BackgroundWorker)sender;

            string status = Processing.GetResourceString("oggenc_encoding_audio_status");
            string encProgressFmt = Processing.GetResourceString("oggenc_encoding_audio_progress");

            _bw.ReportProgress(-10, status);
            _bw.ReportProgress(0, status);

            AudioInfo item = _jobInfo.AudioStreams[_jobInfo.StreamId];

            int outChannels = ((AACProfile) _jobInfo.AudioProfile).OutputChannels;
            switch (outChannels)
            {
                case 1:
                    outChannels = 2;
                    break;
                case 2:
                    outChannels = 1;
                    break;
            }
            int outSampleRate = ((AACProfile)_jobInfo.AudioProfile).SampleRate;
            switch (outSampleRate)
            {
                case 1:
                    outSampleRate = 8000;
                    break;
                case 2:
                    outSampleRate = 11025;
                    break;
                case 3:
                    outSampleRate = 22050;
                    break;
                case 4:
                    outSampleRate = 44100;
                    break;
                case 5:
                    outSampleRate = 48000;
                    break;
                default:
                    outSampleRate = 0;
                    break;
            }

            int encMode = ((AACProfile)_jobInfo.AudioProfile).EncodingMode;
            int bitrate = ((AACProfile)_jobInfo.AudioProfile).Bitrate * 1000;
            float quality = ((AACProfile)_jobInfo.AudioProfile).Quality;

            string inputFile = AviSynthGenerator.GenerateAudioScript(item.TempFile, item.Format, item.FormatProfile,
                                                                     item.ChannelCount, outChannels, item.SampleRate,
                                                                     outSampleRate);
            string outFile = Processing.CreateTempFile(item.TempFile, "encoded.m4a");

            StringBuilder sb = new StringBuilder();
            switch (encMode)
            {
                case 0:
                    sb.AppendFormat(AppSettings.CInfo, "-br {0:0} ", bitrate);
                    break;
                case 1:
                    sb.AppendFormat(AppSettings.CInfo, "-cbr {0:0} ", bitrate);
                    break;
                case 2:
                    sb.AppendFormat(AppSettings.CInfo, "-q {0:0.00} ", quality);
                    break;
            }

            sb.Append("-ignorelength -if - ");
            sb.AppendFormat(AppSettings.CInfo, "-of \"{0}\" ", outFile);

            string localExecutable = Path.Combine(AppSettings.ToolsPath, Executable);

            Regex pipeObj = new Regex(@"^([\d\,\.]*?)%.*$", RegexOptions.Singleline | RegexOptions.Multiline);
            Regex encObj = new Regex(@"^.*Processed.*\d*?.*seconds...$", RegexOptions.Singleline | RegexOptions.Multiline);

            DateTime startTime = DateTime.Now;

            using (Process encoder = new Process(),
                           decoder = BePipe.GenerateProcess(inputFile))
            {
                ProcessStartInfo encoderParameter = new ProcessStartInfo(localExecutable)
                    {
                        WorkingDirectory = AppSettings.DemuxLocation,
                        Arguments =
                            sb.ToString(),
                        CreateNoWindow = true,
                        UseShellExecute = false,
                        RedirectStandardError = true,
                        RedirectStandardInput = true
                    };
                encoder.StartInfo = encoderParameter;

                decoder.StartInfo.RedirectStandardError = true;

                DateTime time = startTime;

                decoder.ErrorDataReceived += (o, args) =>
                    {
                        string line = args.Data;
                        if (string.IsNullOrEmpty(line)) return;

                        Match result = pipeObj.Match(line);
                        if (result.Success)
                        {
                            float temp;

                            string tempProgress = result.Groups[1].Value.Replace(",", ".");

                            Single.TryParse(tempProgress, NumberStyles.Number,
                                            AppSettings.CInfo, out temp);
                            int progress = (int) Math.Floor(temp);
                            float progressRemaining = 100 - temp;

                            TimeSpan eta = DateTime.Now.Subtract(time);
                            long secRemaining = 0;
                            if (eta.Seconds != 0)
                            {
                                double speed = Math.Round(temp/eta.TotalSeconds, 6);

                                if (speed > 0)
                                    secRemaining =
                                        (long) Math.Round(progressRemaining/speed, 0);
                                else
                                    secRemaining = 0;
                            }
                            if (secRemaining < 0)
                                secRemaining = 0;

                            TimeSpan remaining = new TimeSpan(0, 0, (int) secRemaining);
                            DateTime ticks1 = new DateTime(eta.Ticks);

                            string encProgress = string.Format(encProgressFmt, ticks1,
                                                               remaining);
                            _bw.ReportProgress(progress, encProgress);
                        }
                        else
                        {
                            Log.InfoFormat("bepipe: {0:s}", line);
                        }
                    };

                encoder.ErrorDataReceived += (outputSender, outputEvent) =>
                    {
                        string line = outputEvent.Data;

                        if (string.IsNullOrEmpty(line)) return;

                        Match result = encObj.Match(line);
                        if (!result.Success)
                        {
                            Log.InfoFormat("neroAacEnc: {0:s}", line);
                        }
                    };

                Log.InfoFormat("neroAacEnc {0:s}", encoderParameter.Arguments);

                bool encStarted;
                bool decStarted;
                try
                {
                    encStarted = encoder.Start();
                }
                catch (Exception ex)
                {
                    encStarted = false;
                    Log.ErrorFormat("neroAacEnc exception: {0}", ex);
                    _jobInfo.ExitCode = -1;
                }

                try
                {
                    decStarted = decoder.Start();
                }
                catch (Exception ex)
                {
                    decStarted = false;
                    Log.ErrorFormat("bepipe exception: {0}", ex);
                    _jobInfo.ExitCode = -1;
                }

                if (encStarted && decStarted)
                {
                    encoder.PriorityClass = AppSettings.GetProcessPriority();
                    encoder.BeginErrorReadLine();
                    decoder.PriorityClass = AppSettings.GetProcessPriority();
                    decoder.BeginErrorReadLine();

                    Processing.CopyStreamToStream(decoder.StandardOutput.BaseStream, encoder.StandardInput.BaseStream, 32768,
                                                  (src, dst, exc) =>
                                                      {
                                                          src.Close();
                                                          dst.Close();

                                                          if (exc == null) return;

                                                          Log.Debug(exc.Message);
                                                          Log.Debug(exc.StackTrace);
                                                      });

                    while (!encoder.HasExited)
                    {
                        if (_bw.CancellationPending)
                        {
                            encoder.Kill();
                            decoder.Kill();
                        }
                        Thread.Sleep(200);
                    }
                    encoder.WaitForExit(10000);
                    encoder.CancelErrorRead();
                    decoder.WaitForExit(10000);
                    decoder.CancelErrorRead();

                    _jobInfo.ExitCode = encoder.ExitCode;
                    Log.InfoFormat("Exit Code: {0:g}", _jobInfo.ExitCode);

                    if (_jobInfo.ExitCode == 0)
                    {
                        _jobInfo.TempFiles.Add(inputFile);
                        _jobInfo.TempFiles.Add(item.TempFile);
                        _jobInfo.TempFiles.Add(item.TempFile + ".d2a");
                        _jobInfo.TempFiles.Add(item.TempFile + ".ffindex");
                        item.TempFile = outFile;
                        AudioHelper.GetStreamInfo(item);
                    }
                }
            }

            _bw.ReportProgress(100);
            _jobInfo.CompletedStep = _jobInfo.NextStep;
            e.Result = _jobInfo;
        }
        private void wrkTaskManager_DoWork(object sender, DoWorkEventArgs e)
        {
            // Make a note of the synchronization context
            SynchronizationContext ct = (SynchronizationContext)e.Argument;

            // Loop continuously, looking for new tasks.  Sleep for a second
            do
            {
                Thread.Sleep(1000);

                // If there are no tasks, we don't need to do anything...
                while (this.Tasks.Count != 0)
                {
                    // Find the first completed, cancelled or task more than 5 minutes old and delete it
                    for (int i = 0; i < Tasks.Count; i++)
                        if ((Tasks[i].Status == TaskStatus.Complete || Tasks[i].Status == TaskStatus.TimedOut || Tasks[i].Status == TaskStatus.Cancelled) &&
                            DateTime.Now.Subtract(Tasks[i].TaskFinished).TotalSeconds > 300)
                        {
                            // Signal the main thread to remove the task
                            ct.Send(new SendOrPostCallback((o) => { RemoveTask(i); }), null);
                            //this.Tasks.Remove(Tasks[i]);
                            break;
                        }

                    // Get the first queued task
                    Task t = null;
                    int idx = -1;

                    for (int i = 0; i < Tasks.Count; i++)
                    {
                        if (this.Tasks[i].Status == TaskStatus.Running)
                            // Oops - we're already running one task - break before we start another one!
                            break;

                        if (this.Tasks[i].Status == TaskStatus.Queued)
                        {
                            // Found one - note it and break
                            t = this.Tasks[i];
                            idx = i;
                            break;
                        }
                    }

                    // Did we find a task?
                    if (t != null)
                    {
                        // Yes, build the task and run it
                        string param;

                        param = "\\\\" + t.IP.ToString() + " -e "; // Computer's IP address.  PSExec should not load account's profile (quicker startup)

                        // Add credentials only if we have some to add
                        if (t.Credentials != null)
                        {
                            if (t.Credentials.domain == null)
                                param += "-u " + t.Credentials.username;                                // Local user
                            else
                                param += "-u " + t.Credentials.domain + "\\" + t.Credentials.username;      // Domain user and password

                            param += " -p " + t.Credentials.password + " ";
                        }

                        string batchfile = null;

                        // How many commands do we have to run?
                        if (t.Commands.Count == 1)
                            // Only one command.  This can be run directly by PSExec
                            param += t.Commands[0];
                        else
                        {
                            // Multiple commands.  Build a batch file
                            batchfile = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".bat");

                            // Turn echo off in the batch file.  Output comes in an illocical order otherwise.
                            List<string> batch = new List<string>(t.Commands);
                            batch.Insert(0, "@echo off");

                            // Write batch file and add it to the
                            File.WriteAllLines(batchfile, batch);
                            param += "-c " + batchfile;
                        }

                        // Trigger an event so other code can take action it may want to
                        ct.Send(new SendOrPostCallback((o) => { UpdateStatus(idx, TaskStatus.Running); }), null);
                        ct.Send(new SendOrPostCallback((o) => { OnRunning(t, EventArgs.Empty); }), null);

                        // Run PSExec
                        var psexec = new Process
                        {
                            StartInfo = new ProcessStartInfo
                            {
                                FileName = cfg.PSExecPath,
                                Arguments = param,
                                UseShellExecute = false,
                                RedirectStandardOutput = true,
                                RedirectStandardError = true,
                                CreateNoWindow = true
                            }
                        };

                        psexec.OutputDataReceived += new DataReceivedEventHandler(OutputHandler);
                        psexec.ErrorDataReceived += new DataReceivedEventHandler(OutputHandler);

                        output = "";

                        psexec.Start();
                        psexec.BeginOutputReadLine();
                        psexec.BeginErrorReadLine();

                        // Read output until the timeout has expired the process has terminated
                        t.TaskStarted = DateTime.Now;

                        do
                        {
                            // Wait 200ms for more output
                            Thread.Sleep(200);

                            // Flush output and process events
                            psexec.CancelErrorRead();
                            psexec.CancelOutputRead();
                            psexec.BeginOutputReadLine();
                            psexec.BeginErrorReadLine();

                            Application.DoEvents();

                            // Is the publically available output any different to the building output?
                            if ((output != "" && t.Output == null) || (t.Output != null && output != t.Output))
                                // Yes, update the publically available output
                                ct.Send(new SendOrPostCallback((o) => { UpdateOutput(idx, output); }), null);

                        } while (DateTime.Now.Subtract(t.TaskStarted) < t.TimeoutInterval && !psexec.HasExited);

                        // If we created a batch file, delete it
                        if (batchfile != null)
                        {
                            try
                            {
                                File.Delete(batchfile);
                            }
                            catch (Exception ex)
                            {
                                // If we can't delete the file, we can't delete the file.  It'll be caught by the next disk cleanup.  We can at least write something to the debug log.
                                Debug.WriteLine("Unable to remove {0}: {1}", batchfile, ex.ToString());
                            }
                        }

                        // Did task complete
                        if (psexec.HasExited)
                        {
                            // Yes, mark it as complete and release any dependent tasks
                            ct.Send(new SendOrPostCallback((o) => { UpdateStatus(idx, TaskStatus.Complete); }), null);
                            ct.Send(new SendOrPostCallback((o) => { ProcessDependentTasks(t.TaskID, TaskStatus.Complete); }), null);
                        }
                        else
                        {
                            // No, kill it and cancel all dependent tasks
                            psexec.Kill();

                            ct.Send(delegate { this.UpdateStatus(idx, TaskStatus.TimedOut); }, null);
                            ct.Send(delegate { ProcessDependentTasks(t.TaskID, TaskStatus.TimedOut); }, null);
                        }

                        // Note the time the task finished
                        t.TaskFinished = DateTime.Now;
                    }
                }
            } while (true);
        }
Beispiel #32
0
        public void DoEncode(object sender, DoWorkEventArgs e)
        {
            _bw = (BackgroundWorker)sender;

            string passStr = Processing.GetResourceString("vp8_pass");
            string status = Processing.GetResourceString("vp8_encoding_status");
            string progressFormat = Processing.GetResourceString("vp8_encoding_progress");

            //progress vars
            DateTime startTime = DateTime.Now;
            TimeSpan remaining = new TimeSpan(0, 0, 0);
            // end progress

            VP8Profile encProfile = (VP8Profile)_jobInfo.VideoProfile;

            if (!_jobInfo.EncodingProfile.Deinterlace && _jobInfo.VideoStream.Interlaced)
                _jobInfo.VideoStream.Interlaced = false;

            Size resizeTo = VideoHelper.GetTargetSize(_jobInfo);

            if (string.IsNullOrEmpty(_jobInfo.AviSynthScript))
                GenerateAviSynthScript(resizeTo);

            string inputFile = _jobInfo.AviSynthScript;
            string outFile =
                Processing.CreateTempFile(
                    string.IsNullOrEmpty(_jobInfo.TempOutput) ? _jobInfo.JobName : _jobInfo.TempOutput, "encoded.webm");

            _frameCount = _jobInfo.VideoStream.FrameCount;

            int targetBitrate = 0;
            if (_jobInfo.EncodingProfile.TargetFileSize > 0)
                targetBitrate = Processing.CalculateVideoBitrate(_jobInfo);

            int encodeMode = encProfile.EncodingMode;
            string pass = string.Empty;
            if (encodeMode == 1)
                pass = string.Format(" {1} {0:0}; ", _jobInfo.StreamId, passStr);

            _bw.ReportProgress(-10, status + pass.Replace("; ", string.Empty));
            _bw.ReportProgress(0, status);

            string argument = VP8CommandLineGenerator.Generate(encProfile,
                                                                targetBitrate,
                                                                resizeTo.Width,
                                                                resizeTo.Height,
                                                                _jobInfo.StreamId,
                                                                _jobInfo.VideoStream.FrameRateEnumerator,
                                                                _jobInfo.VideoStream.FrameRateDenominator,
                                                                outFile);

            string localExecutable = Path.Combine(AppSettings.ToolsPath, Executable);

            Regex frameInformation = new Regex(@"^.*Pass\s\d\/\d frame \s*\d*\/(\d*).*$",
                                               RegexOptions.Singleline | RegexOptions.Multiline);

            using (Process encoder = new Process(),
                           decoder = FfMpeg.GenerateDecodeProcess(inputFile))
            {
                ProcessStartInfo parameter = new ProcessStartInfo(localExecutable)
                    {
                        WorkingDirectory = AppSettings.DemuxLocation,
                        Arguments = argument,
                        CreateNoWindow = true,
                        UseShellExecute = false,
                        RedirectStandardError = true,
                        RedirectStandardInput = true
                    };
                encoder.StartInfo = parameter;

                encoder.ErrorDataReceived += (outputSender, outputEvent) =>
                    {
                        string line = outputEvent.Data;

                        if (string.IsNullOrEmpty(line)) return;

                        Match result = frameInformation.Match(line);

                        // ReSharper disable AccessToModifiedClosure
                        TimeSpan eta = DateTime.Now.Subtract(startTime);
                        // ReSharper restore AccessToModifiedClosure
                        long secRemaining = 0;

                        if (result.Success)
                        {
                            long current;
                            Int64.TryParse(result.Groups[1].Value, NumberStyles.Number,
                                           AppSettings.CInfo, out current);
                            long framesRemaining = _frameCount - current;
                            float fps = 0f;
                            if (eta.Seconds != 0)
                            {
                                //Frames per Second
                                double codingFPS = Math.Round(current/eta.TotalSeconds, 2);

                                if (codingFPS > 1)
                                {
                                    secRemaining = framesRemaining/(int) codingFPS;
                                    fps = (float) codingFPS;
                                }
                                else
                                    secRemaining = 0;
                            }

                            if (secRemaining > 0)
                                remaining = new TimeSpan(0, 0, (int) secRemaining);

                            DateTime ticks = new DateTime(eta.Ticks);

                            string progress = string.Format(progressFormat,
                                                            current, _frameCount,
                                                            fps,
                                                            remaining, ticks, pass);
                            _bw.ReportProgress((int) (((float) current/_frameCount)*100),
                                               progress);
                        }
                        else
                        {
                            Log.InfoFormat("vpxenc: {0:s}", line);
                        }
                    };

                Log.InfoFormat("start parameter: vpxenc {0:s}", argument);

                bool started;
                bool decStarted;
                try
                {
                    started = encoder.Start();
                }
                catch (Exception ex)
                {
                    started = false;
                    Log.ErrorFormat("vpxenc exception: {0}", ex);
                    _jobInfo.ExitCode = -1;
                }

                NamedPipeServerStream decodePipe = new NamedPipeServerStream(AppSettings.DecodeNamedPipeName,
                                                                             PipeDirection.In, 1,
                                                                             PipeTransmissionMode.Byte, PipeOptions.None);

                try
                {
                    decStarted = decoder.Start();
                }
                catch (Exception ex)
                {
                    decStarted = false;
                    Log.ErrorFormat("avconv exception: {0}", ex);
                    _jobInfo.ExitCode = -1;
                }

                startTime = DateTime.Now;

                if (started && decStarted)
                {
                    encoder.PriorityClass = AppSettings.GetProcessPriority();
                    encoder.BeginErrorReadLine();
                    decoder.PriorityClass = AppSettings.GetProcessPriority();
                    decoder.BeginErrorReadLine();

                    Thread pipeReadThread = new Thread(() =>
                        {
                            try
                            {
                                ReadThreadStart(decodePipe, encoder);
                            }
                            catch (Exception ex)
                            {
                                Log.Error(ex);
                            }
                        });
                    pipeReadThread.Start();
                    pipeReadThread.Priority = ThreadPriority.BelowNormal;
                    encoder.Exited += (o, args) => pipeReadThread.Abort();

                    while (!encoder.HasExited)
                    {
                        if (_bw.CancellationPending)
                        {
                            encoder.Kill();
                            decoder.Kill();
                        }
                        Thread.Sleep(200);
                    }

                    encoder.WaitForExit(10000);
                    encoder.CancelErrorRead();

                    if (decodePipe.IsConnected)
                        try
                        {
                            decodePipe.Disconnect();
                        }
                        catch (Exception ex)
                        {
                            Log.Error(ex);
                        }

                    try
                    {
                        decodePipe.Close();
                        decodePipe.Dispose();
                    }
                    catch (Exception ex)
                    {
                        Log.Error(ex);
                    }

                    decoder.WaitForExit(10000);
                    decoder.CancelErrorRead();

                    _jobInfo.ExitCode = encoder.ExitCode;
                    Log.InfoFormat("Exit Code: {0:g}", _jobInfo.ExitCode);
                }
            }

            if (_jobInfo.ExitCode == 0)
            {
                if ((encProfile.EncodingMode == 1 && _jobInfo.StreamId == 2) ||
                    encProfile.EncodingMode == 0)
                {
                    _jobInfo.VideoStream.Encoded = true;
                    _jobInfo.VideoStream.IsRawStream = false;

                    _jobInfo.TempFiles.Add(_jobInfo.VideoStream.TempFile);
                    _jobInfo.VideoStream.TempFile = outFile;

                    try
                    {
                        _jobInfo.MediaInfo = Processing.GetMediaInfo(_jobInfo.VideoStream.TempFile);
                    }
                    catch (TimeoutException ex)
                    {
                        Log.Error(ex);
                    }
                    _jobInfo.VideoStream = VideoHelper.GetStreamInfo(_jobInfo.MediaInfo, _jobInfo.VideoStream, _jobInfo.EncodingProfile.OutFormat == OutputType.OutputBluRay);

                    string statsFile = Processing.CreateTempFile(outFile, "stats");
                    _jobInfo.TempFiles.Add(statsFile);
                    _jobInfo.TempFiles.Add(_jobInfo.AviSynthScript);
                    _jobInfo.TempFiles.Add(_jobInfo.FfIndexFile);
                    _jobInfo.TempFiles.Add(_jobInfo.AviSynthStereoConfig);
                }
            }

            _bw.ReportProgress(100);
            _jobInfo.CompletedStep = _jobInfo.NextStep;
            e.Result = _jobInfo;
        }
Beispiel #33
0
		private CompilerResults CompileFromFileBatch (CompilerParameters options, string[] fileNames)
		{
			if (null == options)
				throw new ArgumentNullException("options");
			if (null == fileNames)
				throw new ArgumentNullException("fileNames");

			CompilerResults results=new CompilerResults(options.TempFiles);
			Process mcs=new Process();

			// FIXME: these lines had better be platform independent.
			if (Path.DirectorySeparatorChar == '\\') {
				mcs.StartInfo.FileName = windowsMonoPath;
				mcs.StartInfo.Arguments = "\"" + windowsMcsPath + "\" " +
					BuildArgs (options, fileNames, ProviderOptions);
			} else {
				mcs.StartInfo.FileName="mcs";
				mcs.StartInfo.Arguments=BuildArgs(options, fileNames, ProviderOptions);
			}

			mcsOutput = new StringCollection ();
			mcsOutMutex = new Mutex ();
#if !NET_4_0
			/*
			 * !:. KLUDGE WARNING .:!
			 *
			 * When running the 2.0 test suite some assemblies will invoke mcs via
			 * CodeDOM and the new mcs process will find the MONO_PATH variable in its
			 * environment pointing to the net_2_0 library which will cause the runtime
			 * to attempt to load the 2.0 corlib into 4.0 process and thus mcs will
			 * fail. At the same time, we must not touch MONO_PATH when running outside
			 * the test suite, thus the kludge.
			 *
			 * !:. KLUDGE WARNING .:!
			 */
			if (Environment.GetEnvironmentVariable ("MONO_TESTS_IN_PROGRESS") != null) {
				string monoPath = Environment.GetEnvironmentVariable ("MONO_PATH");
				if (!String.IsNullOrEmpty (monoPath)) {
					const string basePath = "/class/lib/";
					const string profile = "net_2_0";
					var basePathIndex = monoPath.IndexOf (basePath, StringComparison.Ordinal);
					if (basePathIndex > 0 && basePathIndex + basePath.Length + profile.Length <= monoPath.Length) {
						var currentProfile = monoPath.Substring (basePathIndex + basePath.Length, profile.Length);
						if (currentProfile.Equals (profile, StringComparison.OrdinalIgnoreCase))
							monoPath = monoPath.Replace (basePath + currentProfile, basePath + "net_4_0");
					}
					mcs.StartInfo.EnvironmentVariables ["MONO_PATH"] = monoPath;
				}
			}
#endif
/*		       
			string monoPath = Environment.GetEnvironmentVariable ("MONO_PATH");
			if (monoPath != null)
				monoPath = String.Empty;

			string privateBinPath = AppDomain.CurrentDomain.SetupInformation.PrivateBinPath;
			if (privateBinPath != null && privateBinPath.Length > 0)
				monoPath = String.Format ("{0}:{1}", privateBinPath, monoPath);

			if (monoPath.Length > 0) {
				StringDictionary dict = mcs.StartInfo.EnvironmentVariables;
				if (dict.ContainsKey ("MONO_PATH"))
					dict ["MONO_PATH"] = monoPath;
				else
					dict.Add ("MONO_PATH", monoPath);
			}
*/
			/*
			 * reset MONO_GC_PARAMS - we are invoking compiler possibly with another GC that
			 * may not handle some of the options causing compilation failure
			 */
			mcs.StartInfo.EnvironmentVariables ["MONO_GC_PARAMS"] = String.Empty;

			mcs.StartInfo.CreateNoWindow=true;
			mcs.StartInfo.UseShellExecute=false;
			mcs.StartInfo.RedirectStandardOutput=true;
			mcs.StartInfo.RedirectStandardError=true;
			mcs.ErrorDataReceived += new DataReceivedEventHandler (McsStderrDataReceived);
			
			try {
				mcs.Start();
			} catch (Exception e) {
				Win32Exception exc = e as Win32Exception;
				if (exc != null) {
					throw new SystemException (String.Format ("Error running {0}: {1}", mcs.StartInfo.FileName,
									Win32Exception.W32ErrorMessage (exc.NativeErrorCode)));
				}
				throw;
			}

			try {
				mcs.BeginOutputReadLine ();
				mcs.BeginErrorReadLine ();
				mcs.WaitForExit();
				
				results.NativeCompilerReturnValue = mcs.ExitCode;
			} finally {
				mcs.CancelErrorRead ();
				mcs.CancelOutputRead ();
				mcs.Close();
			}

			StringCollection sc = mcsOutput;
		       
 			bool loadIt=true;
			foreach (string error_line in mcsOutput) {
				CompilerError error = CreateErrorFromString (error_line);
				if (error != null) {
					results.Errors.Add (error);
					if (!error.IsWarning)
						loadIt = false;
				}
			}
			
			if (sc.Count > 0) {
				sc.Insert (0, mcs.StartInfo.FileName + " " + mcs.StartInfo.Arguments + Environment.NewLine);
				results.Output = sc;
			}

			if (loadIt) {
				if (!File.Exists (options.OutputAssembly)) {
					StringBuilder sb = new StringBuilder ();
					foreach (string s in sc)
						sb.Append (s + Environment.NewLine);
					
					throw new Exception ("Compiler failed to produce the assembly. Output: '" + sb.ToString () + "'");
				}
				
				if (options.GenerateInMemory) {
					using (FileStream fs = File.OpenRead(options.OutputAssembly)) {
						byte[] buffer = new byte[fs.Length];
						fs.Read(buffer, 0, buffer.Length);
						results.CompiledAssembly = Assembly.Load(buffer, null);
						fs.Close();
					}
				} else {
					// Avoid setting CompiledAssembly right now since the output might be a netmodule
					results.PathToAssembly = options.OutputAssembly;
				}
			} else {
				results.CompiledAssembly = null;
			}
			
			return results;
		}
Beispiel #34
0
        private CompilerResults CompileFromFileBatch(CompilerParameters options, string[] fileNames)
        {
            if (null == options)
                throw new ArgumentNullException("options");
            if (null == fileNames)
                throw new ArgumentNullException("fileNames");

            CompilerResults results = new CompilerResults(options.TempFiles);
            Process mcs = new Process();

#if !NET_2_0
            string mcs_output;
            string mcs_stdout;
            string[] mcsOutput;
#endif

            // FIXME: these lines had better be platform independent.
            if (Path.DirectorySeparatorChar == '\\')
            {
                mcs.StartInfo.FileName = windowsMonoPath;
                mcs.StartInfo.Arguments = "\"" + windowsMcsPath + "\" " +
#if NET_2_0
					BuildArgs (options, fileNames, ProviderOptions);
#else
                    BuildArgs(options, fileNames);
#endif
            }
            else
            {
#if NET_2_0
				// FIXME: This is a temporary hack to make code genaration work in 2.0+
#if NET_4_0
				mcs.StartInfo.FileName="dmcs";
#else
				mcs.StartInfo.FileName="gmcs";
#endif
				mcs.StartInfo.Arguments=BuildArgs(options, fileNames, ProviderOptions);
#else
                mcs.StartInfo.FileName = "mcs";
                mcs.StartInfo.Arguments = BuildArgs(options, fileNames);
#endif
            }

#if NET_2_0
			mcsOutput = new StringCollection ();
			mcsOutMutex = new Mutex ();
#endif

            string monoPath = Environment.GetEnvironmentVariable("MONO_PATH");
            if (monoPath == null)
                monoPath = String.Empty;

            string privateBinPath = AppDomain.CurrentDomain.SetupInformation.PrivateBinPath;
            if (privateBinPath != null && privateBinPath.Length > 0)
                monoPath = String.Format("{0}:{1}", privateBinPath, monoPath);

            if (monoPath.Length > 0)
            {
                StringDictionary dict = mcs.StartInfo.EnvironmentVariables;
                if (dict.ContainsKey("MONO_PATH"))
                    dict["MONO_PATH"] = monoPath;
                else
                    dict.Add("MONO_PATH", monoPath);
            }

            mcs.StartInfo.CreateNoWindow = true;
            mcs.StartInfo.UseShellExecute = false;
            mcs.StartInfo.RedirectStandardOutput = true;
            mcs.StartInfo.RedirectStandardError = true;
#if NET_2_0
			mcs.ErrorDataReceived += new DataReceivedEventHandler (McsStderrDataReceived);
#endif

            try
            {
                mcs.Start();
            }
            catch (Exception e)
            {
                Win32Exception exc = e as Win32Exception;
                if (exc != null)
                {
                    /*throw new SystemException(String.Format("Error running {0}: {1}", mcs.StartInfo.FileName,
                                    Win32Exception.W32ErrorMessage(exc.NativeErrorCode)));*/
                }
                throw;
            }

            try
            {
#if NET_2_0
				mcs.BeginOutputReadLine ();
				mcs.BeginErrorReadLine ();
#else
                // If there are a few kB in stdout, we might lock
                mcs_output = mcs.StandardError.ReadToEnd();
                mcs_stdout = mcs.StandardOutput.ReadToEnd();
#endif
                mcs.WaitForExit();

                results.NativeCompilerReturnValue = mcs.ExitCode;
            }
            finally
            {
#if NET_2_0
				mcs.CancelErrorRead ();
				mcs.CancelOutputRead ();
#endif

                mcs.Close();
            }

#if NET_2_0
			StringCollection sc = mcsOutput;
#else
            mcsOutput = mcs_output.Split(System.Environment.NewLine.ToCharArray());
            StringCollection sc = new StringCollection();
#endif

            bool loadIt = true;
            foreach (string error_line in mcsOutput)
            {
#if !NET_2_0
                sc.Add(error_line);
#endif
                CompilerError error = CreateErrorFromString(error_line);
                if (error != null)
                {
                    results.Errors.Add(error);
                    if (!error.IsWarning)
                        loadIt = false;
                }
            }

            if (sc.Count > 0)
            {
                sc.Insert(0, mcs.StartInfo.FileName + " " + mcs.StartInfo.Arguments + Environment.NewLine);

                //results.Output = sc;
            }

            if (loadIt)
            {
                if (!File.Exists(options.OutputAssembly))
                {
                    StringBuilder sb = new StringBuilder();
                    foreach (string s in sc)
                        sb.Append(s + Environment.NewLine);

                    throw new Exception("Compiler failed to produce the assembly. Output: '" + sb.ToString() + "'");
                }

                if (options.GenerateInMemory)
                {
                    using (FileStream fs = File.OpenRead(options.OutputAssembly))
                    {
                        byte[] buffer = new byte[fs.Length];
                        fs.Read(buffer, 0, buffer.Length);
                        results.CompiledAssembly = Assembly.Load(buffer, null, options.Evidence);
                        fs.Close();
                    }
                }
                else
                {
                    // Avoid setting CompiledAssembly right now since the output might be a netmodule
                    results.PathToAssembly = options.OutputAssembly;
                }
            }
            else
            {
                results.CompiledAssembly = null;
            }

            return results;
        }
Beispiel #35
0
        public void BeginGetDirectoryListing(string path, DirListingCallback callback)
        {
            if (m_Session == null)
            {
                callback(RequestResult.SessionInvalid, null);
                return;
            }

            List<FileEntry> files = new List<FileEntry>();
            Stopwatch timeoutWatch = new Stopwatch();

            /*
             * Check that we have a username either stored from previous sessions, or loaded
             * from the registry. If PPK Authentication is being used that will override
             * any values entered in the login dialog
             */
            if (String.IsNullOrEmpty(m_Session.Username))
            {
                if (m_Login.ShowDialog(SuperPuTTY.MainForm) == System.Windows.Forms.DialogResult.OK)
                {
                    m_Session.Username = m_Login.Username;
                    m_Session.Password = m_Login.Password;

                    if (m_Login.Remember)
                    {
                        //Session.SaveToRegistry(); // passwords are *never* saved and stored permanently
                        SuperPuTTY.SaveSessions();
                    }
                }
                else
                {
                    Logger.Log("Cancel connection");
                    callback(RequestResult.CancelLogin, null);
                }
            }

            Thread threadListFiles = new Thread(delegate()
            {
                m_processDir = new Process();

                m_processDir.EnableRaisingEvents = true;
                m_processDir.StartInfo.UseShellExecute = false;
                m_processDir.StartInfo.RedirectStandardError = true;
                //m_processDir.StartInfo.RedirectStandardInput = true;
                m_processDir.StartInfo.RedirectStandardOutput = true;
                m_processDir.StartInfo.CreateNoWindow = true;
                m_processDir.StartInfo.FileName = SuperPuTTY.Settings.PscpExe;
                // process the various options from the session object and convert them into arguments pscp can understand
                string args = MakeArgs(m_Session, true, path);
                Logger.Log("Sending Command: '{0} {1}'", m_processDir.StartInfo.FileName, MakeArgs(m_Session, false, path));
                m_processDir.StartInfo.Arguments = args;
                /*
                 * Handle output from spawned pscp.exe process, handle any data received and parse
                 * any lines that look like a directory listing.
                 */
                m_processDir.OutputDataReceived += delegate(object sender, DataReceivedEventArgs e)
                {
                    if (!String.IsNullOrEmpty(e.Data))
                    {
                        if (e.Data.Equals(PUTTY_ARGUMENTS_HELP_HEADER))
                        {
                            m_processDir.CancelOutputRead();
                            m_processDir.Kill();
                            return;
                        }
                        else if (e.Data.StartsWith("Listing directory "))
                        {
                            // This just tells us the current directory, however since we're the ones that requested it
                            // we already have this information. But this traps it so its not sent through the directory
                            // entry parser.
                        }
                        else if (e.Data.Equals(PUTTY_INTERACTIVE_AUTH) || e.Data.Contains("password: "******"Username/Password invalid or not sent");
                            callback(RequestResult.RetryAuthentication, null);
                        }
                        else
                        {
                            timeoutWatch.Reset();
                            lock (files)
                            {
                                FileEntry file;
                                if (TryParseFileLine(e.Data, out file))
                                {
                                    files.Add(file);
                                }

                                if (files.Count > 0)
                                {
                                    callback(RequestResult.ListingFollows, files);
                                }
                            }
                        }
                    }
                };

                m_processDir.ErrorDataReceived += delegate(object sender, DataReceivedEventArgs e)
                {
                    if (!String.IsNullOrEmpty(e.Data))
                    {
                        if (e.Data.Contains(PUTTY_NO_KEY))
                        {
                            m_processDir.CancelErrorRead();
                            m_processDir.Kill();
                            System.Windows.Forms.MessageBox.Show("The key of the host you are attempting to connect to has changed or is not cached \n" +
                                "You must connect to this host with with a PuTTY ssh terminal to accept the key and store it in the cache", "Host Key not found or changed", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Stop);
                        }
                        else
                        {
                            Logger.Log("Error Data:\n\t'{0}'", e.Data.TrimEnd());
                            // 'ssh_init: Host does not exist'
                        }
                    }
                };

                m_processDir.Exited += delegate(object sender, EventArgs e)
                {
                    if (m_processDir.ExitCode != 0)
                    {
                        Logger.Log("Process Exited (Failure): {0}", m_processDir.ExitCode);
                        callback(RequestResult.UnknownError, null);
                        if (m_PuttyClosed != null)
                            m_PuttyClosed(true);
                    }
                    else
                    {
                        Logger.Log("Process Exited: {0}", m_processDir.ExitCode);
                        if (m_PuttyClosed != null)
                            m_PuttyClosed(false);
                    }
                    m_DirIsBusy = false;
                };

                try
                {
                    m_processDir.Start();
                }
                catch (Win32Exception e)
                {
                    if (e.NativeErrorCode == 2) // File Not Found
                    {
                        Logger.Log(e);
                    }
                    else if (e.NativeErrorCode == 4) // Acess Denied
                    {
                        Logger.Log(e);
                    }
                }

                m_processDir.BeginErrorReadLine();
                m_processDir.BeginOutputReadLine();
                m_processDir.WaitForExit();
            });

            /* Only allow one directory list request at a time */
            if (!m_DirIsBusy)
            {
                m_DirIsBusy = true;
                threadListFiles.Name = "List Remote Directory";
                threadListFiles.IsBackground = true;
                threadListFiles.Start();
            }
            else
            {
                return;
            }

            Thread timeoutThread = new Thread(delegate()
            {
                while (m_DirIsBusy)
                {
                    /*
                     * if no data received in 5 seconds we'll stop the process,
                     * This allows us to capture any interactive prompts/messages
                     * sent to us by putty.
                     */
                    if (timeoutWatch.Elapsed.Seconds >= 5)
                    {
                        Logger.Log("Timeout after {0} seconds", timeoutWatch.Elapsed.Seconds);

                        if (!m_processDir.HasExited)
                        {
                            m_processDir.Kill();
                        }
                        m_processDir.CancelErrorRead();
                        m_processDir.CancelOutputRead();
                        return;
                    }
                    Thread.Sleep(1000);
                }
            });
            timeoutThread.Name = "Timeout Watcher";
            timeoutThread.IsBackground = true;
            timeoutThread.Start();
            timeoutWatch.Start();
        }
        /// <summary>
        ///     Start the process in an async manner
        /// </summary>
        /// <param name="startInfo">
        ///     The <see cref="ProcessStartInfo" /> describing the process to launch
        /// </param>
        /// <param name="outputMessage">
        ///     Callback for each line of text emitted on the launched Process's Standard Output Stream
        /// </param>
        /// <param name="errorMessage">
        ///     Callback for each line of text emitted on the launched Process's Standard Error Stream
        /// </param>
        /// <param name="startedCallback">
        ///     Callback invoked with the started <see cref="Process" />
        /// </param>
        /// <param name="cancellationToken">
        ///     The cancellation token.
        /// </param>
        /// <returns>
        ///     The <see cref="Task" /> representing the executing process.  The completed result will be the exit code value.
        /// </returns>
        /// <exception cref="InvalidOperationException">
        ///     Thrown if the process cannot be started
        /// </exception>
        public static async Task <int> StartAsync(
            [NotNull] this ProcessStartInfo startInfo,
            Action <string> outputMessage,
            Action <string> errorMessage,
            Action <Process> startedCallback,
            CancellationToken cancellationToken)
        {
            startInfo.RedirectStandardOutput = true;
            startInfo.RedirectStandardError  = true;
            startInfo.UseShellExecute        = false;
            startInfo.CreateNoWindow         = true;

            var tcs = new TaskCompletionSource <int>();
            var ps  = new Process {
                StartInfo = startInfo, EnableRaisingEvents = true
            };

            ps.Exited += (sender, eventArgs) =>
            {
                ps.WaitForExit();
                var code = ps.ExitCode;
                ps.CancelErrorRead();
                ps.CancelOutputRead();
                ps.Dispose();
                tcs.TrySetResult(code);
            };
            using (cancellationToken.Register(
                       () =>
            {
                tcs.TrySetCanceled();
                try
                {
                    if (ps.HasExited)
                    {
                        return;
                    }

                    ps.Kill();
                    ps.WaitForExit(WaitForExitDelayInMilliseconds);
                    ps.WaitForExit();
                    ps.Dispose();
                }
                catch (InvalidOperationException)
                {
                    // Ignore
                }
            }))
            {
                cancellationToken.ThrowIfCancellationRequested();
                ps.OutputDataReceived += (s, e) =>
                {
                    if (e.Data != null)
                    {
                        PushLine(e.Data, outputMessage);
                    }
                };
                ps.ErrorDataReceived += (s, e) =>
                {
                    if (e.Data != null)
                    {
                        PushLine(e.Data, errorMessage ?? outputMessage);
                    }
                };
                ps.Start();

                ps.BeginErrorReadLine();
                ps.BeginOutputReadLine();

                startedCallback?.Invoke(ps);

                return(await tcs.Task.ConfigureAwait(false));
            }
        }
Beispiel #37
0
        /// <summary>
        /// Main processing function, called by BackgroundWorker thread
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void DoEncode(object sender, DoWorkEventArgs e)
        {
            _bw = (BackgroundWorker)sender;

            string status = Processing.GetResourceString("dvdauthor_muxing_status");
            _bw.ReportProgress(-10, status);
            _bw.ReportProgress(0, status);

            string localExecutable = Path.Combine(AppSettings.ToolsPath, Executable);

            XmlDocument outSubFile = new XmlDocument();
            XmlDeclaration decl = outSubFile.CreateXmlDeclaration("1.0", "UTF-8", "yes");
            XmlElement xn = outSubFile.CreateElement("dvdauthor");
            outSubFile.AppendChild(decl);
            outSubFile.AppendChild(xn);
            xn.AppendChild(outSubFile.CreateElement("vmgm"));

            XmlNode titleSet = outSubFile.CreateElement("titleset");
            xn.AppendChild(titleSet);

            XmlNode titles = outSubFile.CreateElement("titles");
            titleSet.AppendChild(titles);

            string chapterString = string.Empty;
            if (_jobInfo.Chapters.Count > 1)
            {
                DateTime dt;
                List<string> tempChapters = new List<string>();

                if (_jobInfo.Input != InputType.InputDvd)
                {
                    foreach (TimeSpan chapter in _jobInfo.Chapters)
                    {
                        dt = DateTime.MinValue.Add(chapter);
                        tempChapters.Add(dt.ToString("H:mm:ss.fff"));
                    }
                }
                else
                {
                    TimeSpan actualTime = new TimeSpan();

                    foreach (TimeSpan chapter in _jobInfo.Chapters)
                    {
                        actualTime = actualTime.Add(chapter);
                        dt = DateTime.MinValue.Add(actualTime);
                        tempChapters.Add(dt.ToString("H:mm:ss.fff"));
                    }
                }
                chapterString = string.Join(",", tempChapters.ToArray());
            }

            foreach (string itemlang in _jobInfo.AudioStreams.Select(item => item.ShortLang))
            {
                LanguageHelper language = LanguageHelper.GetLanguage(string.IsNullOrEmpty(itemlang) ? "xx" : itemlang);

                XmlNode audio = outSubFile.CreateElement("audio");
                XmlAttribute audioLang = outSubFile.CreateAttribute("lang");
                audioLang.Value = language.Iso1Lang;

                if (audio.Attributes != null)
                    audio.Attributes.Append(audioLang);

                titles.AppendChild(audio);
            }

            foreach (SubtitleInfo item in _jobInfo.SubtitleStreams)
            {
                string itemlang = item.LangCode;

                if (string.IsNullOrEmpty(itemlang))
                    itemlang = "xx";

                LanguageHelper language = LanguageHelper.GetLanguage(itemlang);

                if (item.Format != "PGS" && item.Format != "VobSub") continue;

                XmlNode sub = outSubFile.CreateElement("subpicture");
                XmlAttribute subLang = outSubFile.CreateAttribute("lang");
                subLang.Value = language.Iso1Lang;

                if (sub.Attributes != null)
                    sub.Attributes.Append(subLang);

                titles.AppendChild(sub);
            }

            XmlNode pgc = outSubFile.CreateElement("pgc");
            titles.AppendChild(pgc);

            XmlNode vob = outSubFile.CreateElement("vob");
            XmlAttribute vobFile = outSubFile.CreateAttribute("file");
            vobFile.Value = HttpUtility.HtmlEncode(_jobInfo.VideoStream.TempFile);
            if (vob.Attributes != null)
            {
                vob.Attributes.Append(vobFile);

                if (!string.IsNullOrEmpty(chapterString))
                {
                    XmlAttribute chapters = outSubFile.CreateAttribute("chapters");
                    chapters.Value = chapterString;
                    vob.Attributes.Append(chapters);
                }
            }

            pgc.AppendChild(vob);

            string xmlFile = Processing.CreateTempFile(".xml");

            outSubFile.Save(xmlFile);

            Log.InfoFormat("dvdauthor xml: \r\n{0:s}", outSubFile.OuterXml);

            using (Process encoder = new Process())
            {
                ProcessStartInfo parameter = new ProcessStartInfo(localExecutable)
                    {
                        CreateNoWindow = true,
                        UseShellExecute = false,
                        RedirectStandardError = true
                    };

                string outFile = !string.IsNullOrEmpty(_jobInfo.TempOutput) ? _jobInfo.TempOutput : _jobInfo.OutputFile;

                parameter.Arguments = string.Format("-o \"{0}\" -x \"{1}\"", outFile, xmlFile);
                encoder.StartInfo = parameter;

                encoder.ErrorDataReceived += EncoderOnErrorDataReceived;

                Log.InfoFormat("dvdauthor: {0:s}", parameter.Arguments);

                try
                {
                    Directory.Delete(outFile, true);
                }
                catch (Exception exception)
                {
                    Log.ErrorFormat("DVDAuthor exception: {0}", exception.Message);
                }

                bool started;
                try
                {
                    started = encoder.Start();
                }
                catch (Exception ex)
                {
                    started = false;
                    Log.ErrorFormat("dvdauthor exception: {0}", ex);
                    _jobInfo.ExitCode = -1;
                }

                if (started)
                {
                    encoder.PriorityClass = AppSettings.GetProcessPriority();
                    encoder.BeginErrorReadLine();

                    _bw.ReportProgress(-1, status);

                    while (!encoder.HasExited)
                    {
                        if (_bw.CancellationPending)
                            encoder.Kill();

                        Thread.Sleep(200);
                    }

                    encoder.WaitForExit(10000);
                    encoder.CancelErrorRead();

                    _jobInfo.ExitCode = encoder.ExitCode;
                    Log.InfoFormat("Exit Code: {0:g}", _jobInfo.ExitCode);

                    if (_jobInfo.ExitCode == 0)
                    {
                        _jobInfo.TempFiles.Add(xmlFile);
                        _jobInfo.TempFiles.Add(_jobInfo.VideoStream.TempFile);
                    }
                }
            }
            _bw.ReportProgress(100);
            _jobInfo.CompletedStep = _jobInfo.NextStep;

            e.Result = _jobInfo;
        }
Beispiel #38
0
		private CompilerResults CompileFromFileBatch (CompilerParameters options, string[] fileNames)
		{
			if (null == options)
				throw new ArgumentNullException("options");
			if (null == fileNames)
				throw new ArgumentNullException("fileNames");

			CompilerResults results=new CompilerResults(options.TempFiles);
			Process mcs=new Process();

			// FIXME: these lines had better be platform independent.
			if (Path.DirectorySeparatorChar == '\\') {
				mcs.StartInfo.FileName = MonoToolsLocator.Mono;
				mcs.StartInfo.Arguments = "\"" + MonoToolsLocator.CSharpCompiler + "\" ";
			} else {
				mcs.StartInfo.FileName = MonoToolsLocator.CSharpCompiler;
			}

			mcs.StartInfo.Arguments += BuildArgs (options, fileNames, ProviderOptions);

			mcsOutput = new StringCollection ();
			mcsOutMutex = new Mutex ();
/*		       
			string monoPath = Environment.GetEnvironmentVariable ("MONO_PATH");
			if (monoPath != null)
				monoPath = String.Empty;

			string privateBinPath = AppDomain.CurrentDomain.SetupInformation.PrivateBinPath;
			if (privateBinPath != null && privateBinPath.Length > 0)
				monoPath = String.Format ("{0}:{1}", privateBinPath, monoPath);

			if (monoPath.Length > 0) {
				StringDictionary dict = mcs.StartInfo.EnvironmentVariables;
				if (dict.ContainsKey ("MONO_PATH"))
					dict ["MONO_PATH"] = monoPath;
				else
					dict.Add ("MONO_PATH", monoPath);
			}
*/
			/*
			 * reset MONO_GC_PARAMS - we are invoking compiler possibly with another GC that
			 * may not handle some of the options causing compilation failure
			 */
			mcs.StartInfo.EnvironmentVariables ["MONO_GC_PARAMS"] = String.Empty;

			mcs.StartInfo.CreateNoWindow=true;
			mcs.StartInfo.UseShellExecute=false;
			mcs.StartInfo.RedirectStandardOutput=true;
			mcs.StartInfo.RedirectStandardError=true;
			mcs.OutputDataReceived += new DataReceivedEventHandler (McsStderrDataReceived);

			// Use same text decoder as mcs and not user set values in Console
			mcs.StartInfo.StandardOutputEncoding =
			mcs.StartInfo.StandardErrorEncoding = Encoding.UTF8;
			
			try {
				mcs.Start();
			} catch (Exception e) {
				Win32Exception exc = e as Win32Exception;
				if (exc != null) {
					throw new SystemException (String.Format ("Error running {0}: {1}", mcs.StartInfo.FileName,
									Win32Exception.GetErrorMessage (exc.NativeErrorCode)));
				}
				throw;
			}

			try {
				mcs.BeginOutputReadLine ();
				mcs.BeginErrorReadLine ();
				mcs.WaitForExit();
				
				results.NativeCompilerReturnValue = mcs.ExitCode;
			} finally {
				mcs.CancelErrorRead ();
				mcs.CancelOutputRead ();
				mcs.Close();
			}

			StringCollection sc = mcsOutput;
		       
 			bool loadIt=true;
			foreach (string error_line in mcsOutput) {
				CompilerError error = CreateErrorFromString (error_line);
				if (error != null) {
					results.Errors.Add (error);
					if (!error.IsWarning)
						loadIt = false;
				}
			}
			
			if (sc.Count > 0) {
				sc.Insert (0, mcs.StartInfo.FileName + " " + mcs.StartInfo.Arguments + Environment.NewLine);
				results.Output = sc;
			}

			if (loadIt) {
				if (!File.Exists (options.OutputAssembly)) {
					StringBuilder sb = new StringBuilder ();
					foreach (string s in sc)
						sb.Append (s + Environment.NewLine);
					
					throw new Exception ("Compiler failed to produce the assembly. Output: '" + sb.ToString () + "'");
				}
				
				if (options.GenerateInMemory) {
					using (FileStream fs = File.OpenRead(options.OutputAssembly)) {
						byte[] buffer = new byte[fs.Length];
						fs.Read(buffer, 0, buffer.Length);
						results.CompiledAssembly = Assembly.Load(buffer, null);
						fs.Close();
					}
				} else {
					// Avoid setting CompiledAssembly right now since the output might be a netmodule
					results.PathToAssembly = options.OutputAssembly;
				}
			} else {
				results.CompiledAssembly = null;
			}
			
			return results;
		}
    public static String GetApacheVersion(String apacheHome)
    {
      Process process = new Process();

      if (File.Exists(apacheHome + @"\bin\apache.exe"))
        process.StartInfo.FileName = apacheHome + @"\bin\apache.exe";
      else if (File.Exists(apacheHome + @"\bin\httpd.exe"))
        process.StartInfo.FileName = apacheHome + @"\bin\httpd.exe";
      else
        throw new ApplicationException(String.Format("Can not find apache.exe or httpd.exe in {0}\\bin", apacheHome));

      process.StartInfo.RedirectStandardError = true;
      process.StartInfo.RedirectStandardOutput = true;
      process.StartInfo.Arguments = "-v";
      process.StartInfo.UseShellExecute = false;

      StringBuilder error = new StringBuilder();
      String version = null;
      String versionString = null;

      process.ErrorDataReceived += delegate(object sender, DataReceivedEventArgs e)
      {
        if (e.Data != null)
          error.Append(e.Data).Append('\n');
      };
      process.OutputDataReceived += delegate(object sender, DataReceivedEventArgs e)
      {
        if (e.Data == null)
          return;

        String test = e.Data.ToLower();
        if (test.IndexOf("version") != -1) {
          versionString = e.Data;

          if (test.IndexOf("2.2") != -1)
            version = "2.2";
          else if (test.IndexOf("2.0") != -1)
            version = "2.0";
        }
      };

      process.Start();

      process.BeginOutputReadLine();
      process.BeginErrorReadLine();

      process.WaitForExit();

      process.CancelErrorRead();
      process.CancelOutputRead();

      process.Close();

      if (version != null)
        return version;

      if (error.Length > 0)
        throw new ApplicationException("Unable to determine version of Apache due to message: " + error.ToString());
      else if (version != null)
        throw new ApplicationException("Unsupported Apache Version: " + versionString);
      else
        throw new ApplicationException("Unable to determine version of Apache");
    }