2 This file is part of the HandBrake source code.
\r
3 Homepage: <http://handbrake.fr/>.
\r
4 It may be used under the terms of the GNU General Public License. */
\r
6 namespace HandBrake.ApplicationServices.Services
\r
9 using System.Diagnostics;
\r
12 using System.Threading;
\r
13 using System.Windows.Forms;
\r
15 using HandBrake.ApplicationServices.Functions;
\r
16 using HandBrake.ApplicationServices.Model;
\r
17 using HandBrake.ApplicationServices.Parsing;
\r
18 using HandBrake.ApplicationServices.Properties;
\r
19 using HandBrake.ApplicationServices.Services.Interfaces;
\r
21 using Timer = System.Threading.Timer;
\r
24 /// Class which handles the CLI
\r
26 public class Encode : IEncode
\r
28 /* Private Variables */
\r
38 private StringBuilder logBuffer;
\r
41 /// The line number thats been read to in the log file
\r
43 private int logFilePosition;
\r
46 /// A Timer for this window
\r
48 private Timer windowTimer;
\r
51 /// Gets The Process Handle
\r
53 private IntPtr processHandle;
\r
56 /// Gets the Process ID
\r
58 private int processID;
\r
63 /// Initializes a new instance of the <see cref="Encode"/> class.
\r
67 this.EncodeStarted += Encode_EncodeStarted;
\r
73 /// Encode Progess Status
\r
75 /// <param name="sender">
\r
78 /// <param name="e">
\r
79 /// The EncodeProgressEventArgs.
\r
81 public delegate void EncodeProgessStatus(object sender, EncodeProgressEventArgs e);
\r
83 /* Event Handlers */
\r
86 /// Fires when a new CLI Job starts
\r
88 public event EventHandler EncodeStarted;
\r
91 /// Fires when a CLI job finishes.
\r
93 public event EventHandler EncodeEnded;
\r
96 /// Encode process has progressed
\r
98 public event EncodeProgessStatus EncodeStatusChanged;
\r
103 /// Gets or sets The HB Process
\r
105 protected Process HbProcess { get; set; }
\r
108 /// Gets a value indicating whether IsEncoding.
\r
110 public bool IsEncoding { get; private set; }
\r
112 /* Public Methods */
\r
115 /// Gets ActivityLog.
\r
117 public string ActivityLog
\r
121 if (logBuffer == null)
\r
127 return logBuffer != null ? logBuffer.ToString() : string.Empty;
\r
132 /// Create a preview sample video
\r
134 /// <param name="query">
\r
137 public void CreatePreviewSample(string query)
\r
139 this.Run(new Job { Query = query }, true);
\r
143 /// Kill the CLI process
\r
147 if (this.HbProcess != null)
\r
148 this.HbProcess.Kill();
\r
150 Process[] list = Process.GetProcessesByName("HandBrakeCLI");
\r
151 foreach (Process process in list)
\r
154 if (this.EncodeEnded != null)
\r
155 this.EncodeEnded(this, new EventArgs());
\r
159 /// Attempt to Safely kill a DirectRun() CLI
\r
160 /// NOTE: This will not work with a MinGW CLI
\r
161 /// Note: http://www.cygwin.com/ml/cygwin/2006-03/msg00330.html
\r
163 public void SafelyClose()
\r
165 if ((int)this.processHandle == 0)
\r
168 // Allow the CLI to exit cleanly
\r
169 Win32.SetForegroundWindow((int)this.processHandle);
\r
170 SendKeys.Send("^C");
\r
173 // HbProcess.StandardInput.AutoFlush = true;
\r
174 // HbProcess.StandardInput.WriteLine("^C");
\r
178 /// Execute a HandBrakeCLI process.
\r
180 /// <param name="encJob">
\r
183 /// <param name="requireStandardOuput">
\r
184 /// Set to True to show no window and force standard output redirect
\r
186 protected void Run(Job encJob, bool requireStandardOuput)
\r
194 string handbrakeCLIPath = Path.Combine(Application.StartupPath, "HandBrakeCLI.exe");
\r
195 string logPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\HandBrake\\logs", "last_encode_log.txt");
\r
196 string strCmdLine = String.Format(@" /C """"{0}"" {1} 2>""{2}"" """, handbrakeCLIPath, encJob.Query, logPath);
\r
197 var cliStart = new ProcessStartInfo("CMD.exe", strCmdLine);
\r
199 if (Settings.Default.enocdeStatusInGui || requireStandardOuput)
\r
201 cliStart.RedirectStandardOutput = true;
\r
202 cliStart.UseShellExecute = false;
\r
203 if (!Settings.Default.showCliForInGuiEncodeStatus || requireStandardOuput)
\r
204 cliStart.CreateNoWindow = true;
\r
206 if (Settings.Default.cli_minimized)
\r
207 cliStart.WindowStyle = ProcessWindowStyle.Minimized;
\r
209 Process[] before = Process.GetProcesses(); // Get a list of running processes before starting.
\r
210 HbProcess = Process.Start(cliStart);
\r
211 this.processID = Main.GetCliProcess(before);
\r
213 if (HbProcess != null)
\r
214 this.processHandle = HbProcess.MainWindowHandle; // Set the process Handle
\r
216 // Start the Log Monitor
\r
217 windowTimer = new Timer(new TimerCallback(ReadFile), null, 1000, 1000);
\r
219 // Set the process Priority
\r
220 Process hbCliProcess = null;
\r
221 if (this.processID != -1)
\r
223 hbCliProcess = Process.GetProcessById(this.processID);
\r
224 hbCliProcess.EnableRaisingEvents = true;
\r
225 hbCliProcess.Exited += new EventHandler(HbProcess_Exited);
\r
228 if (hbCliProcess != null)
\r
229 switch (Settings.Default.processPriority)
\r
232 hbCliProcess.PriorityClass = ProcessPriorityClass.RealTime;
\r
235 hbCliProcess.PriorityClass = ProcessPriorityClass.High;
\r
237 case "Above Normal":
\r
238 hbCliProcess.PriorityClass = ProcessPriorityClass.AboveNormal;
\r
241 hbCliProcess.PriorityClass = ProcessPriorityClass.Normal;
\r
244 hbCliProcess.PriorityClass = ProcessPriorityClass.Idle;
\r
247 hbCliProcess.PriorityClass = ProcessPriorityClass.BelowNormal;
\r
251 // Fire the Encode Started Event
\r
252 if (this.EncodeStarted != null)
\r
253 this.EncodeStarted(this, new EventArgs());
\r
255 catch (Exception exc)
\r
257 Main.ShowExceptiowWindow("It would appear that HandBrakeCLI has not started correctly. You should take a look at the Activity log as it may indicate the reason why.\n\nDetailed Error Information: error occured in runCli()", exc.ToString());
\r
262 /// The HandBrakeCLI process has exited.
\r
264 /// <param name="sender">
\r
267 /// <param name="e">
\r
270 private void HbProcess_Exited(object sender, EventArgs e)
\r
272 IsEncoding = false;
\r
274 windowTimer.Dispose();
\r
277 if (this.EncodeEnded != null)
\r
278 this.EncodeEnded(this, new EventArgs());
\r
282 /// Function to run the CLI directly rather than via CMD
\r
283 /// TODO: Code to handle the Log data has yet to be written.
\r
284 /// TODO: Code to handle the % / ETA info has to be written.
\r
286 /// <param name="query">
\r
289 protected void DirectRun(string query)
\r
293 if (this.EncodeStarted != null)
\r
294 this.EncodeStarted(this, new EventArgs());
\r
301 string handbrakeCLIPath = Path.Combine(Environment.CurrentDirectory, "HandBrakeCLI.exe");
\r
302 HbProcess = new Process
\r
306 FileName = handbrakeCLIPath,
\r
308 UseShellExecute = false,
\r
309 RedirectStandardOutput = true,
\r
310 RedirectStandardError = true,
\r
311 RedirectStandardInput = true,
\r
312 CreateNoWindow = false,
\r
313 WindowStyle = ProcessWindowStyle.Minimized
\r
317 // Setup event handlers for rediected data
\r
318 HbProcess.ErrorDataReceived += new DataReceivedEventHandler(HbProcErrorDataReceived);
\r
319 HbProcess.OutputDataReceived += new DataReceivedEventHandler(HbProcOutputDataReceived);
\r
321 // Start the process
\r
324 // Setup the asynchronous reading of stdin and stderr
\r
325 HbProcess.BeginErrorReadLine();
\r
326 HbProcess.BeginOutputReadLine();
\r
328 // Set the Process Priority);
\r
329 switch (Settings.Default.processPriority)
\r
332 HbProcess.PriorityClass = ProcessPriorityClass.RealTime;
\r
335 HbProcess.PriorityClass = ProcessPriorityClass.High;
\r
337 case "Above Normal":
\r
338 HbProcess.PriorityClass = ProcessPriorityClass.AboveNormal;
\r
341 HbProcess.PriorityClass = ProcessPriorityClass.Normal;
\r
344 HbProcess.PriorityClass = ProcessPriorityClass.Idle;
\r
347 HbProcess.PriorityClass = ProcessPriorityClass.BelowNormal;
\r
351 // Set the class items
\r
352 this.processID = HbProcess.Id;
\r
353 this.processHandle = HbProcess.Handle;
\r
355 catch (Exception exc)
\r
357 Console.WriteLine(exc);
\r
362 /// Add the CLI Query to the Log File.
\r
364 /// <param name="encJob">
\r
365 /// The Encode Job Object
\r
367 protected void AddCLIQueryToLog(Job encJob)
\r
371 string logDir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) +
\r
372 "\\HandBrake\\logs";
\r
373 string logPath = Path.Combine(logDir, "last_encode_log.txt");
\r
375 var reader = new StreamReader(File.Open(logPath, FileMode.Open, FileAccess.Read, FileShare.Read));
\r
376 string log = reader.ReadToEnd();
\r
379 var writer = new StreamWriter(File.Create(logPath));
\r
381 writer.WriteLine("### CLI Query: " + encJob.Query);
\r
382 writer.WriteLine("### User Query: " + encJob.CustomQuery);
\r
383 writer.WriteLine("#########################################");
\r
384 writer.WriteLine(log);
\r
395 /// Save a copy of the log to the users desired location or a default location
\r
396 /// if this feature is enabled in options.
\r
398 /// <param name="destination">
\r
399 /// The Destination File Path
\r
401 protected void CopyLog(string destination)
\r
405 string logDir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) +
\r
406 "\\HandBrake\\logs";
\r
407 string tempLogFile = Path.Combine(logDir, "last_encode_log.txt");
\r
409 string encodeDestinationPath = Path.GetDirectoryName(destination);
\r
410 string destinationFile = Path.GetFileName(destination);
\r
411 string encodeLogFile = destinationFile + " " +
\r
412 DateTime.Now.ToString().Replace("/", "-").Replace(":", "-") + ".txt";
\r
414 // Make sure the log directory exists.
\r
415 if (!Directory.Exists(logDir))
\r
416 Directory.CreateDirectory(logDir);
\r
418 // Copy the Log to HandBrakes log folder in the users applciation data folder.
\r
419 File.Copy(tempLogFile, Path.Combine(logDir, encodeLogFile));
\r
421 // Save a copy of the log file in the same location as the enocde.
\r
422 if (Settings.Default.saveLogWithVideo)
\r
423 File.Copy(tempLogFile, Path.Combine(encodeDestinationPath, encodeLogFile));
\r
425 // Save a copy of the log file to a user specified location
\r
426 if (Directory.Exists(Settings.Default.saveLogPath))
\r
427 if (Settings.Default.saveLogPath != String.Empty && Settings.Default.saveLogToSpecifiedPath)
\r
428 File.Copy(tempLogFile, Path.Combine(Settings.Default.saveLogPath, encodeLogFile));
\r
430 catch (Exception exc)
\r
432 Main.ShowExceptiowWindow("Unable to make a copy of the log file", exc.ToString());
\r
437 /// Read the log file
\r
439 /// <param name="n">
\r
442 private void ReadFile(object n)
\r
446 // last_encode_log.txt is the primary log file. Since .NET can't read this file whilst the CLI is outputing to it (Not even in read only mode),
\r
447 // we'll need to make a copy of it.
\r
448 string logDir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) +
\r
449 "\\HandBrake\\logs";
\r
450 string logFile = Path.Combine(logDir, "last_encode_log.txt");
\r
451 string logFile2 = Path.Combine(logDir, "tmp_appReadable_log.txt");
\r
455 // Make sure the application readable log file does not already exist. FileCopy fill fail if it does.
\r
456 if (File.Exists(logFile2))
\r
457 File.Delete(logFile2);
\r
459 // Copy the log file.
\r
460 if (File.Exists(logFile))
\r
461 File.Copy(logFile, logFile2, true);
\r
468 // Put the Query and User Generated Query Flag on the log.
\r
469 if (logFilePosition == 0 && job.Query != null)
\r
471 logBuffer.AppendLine("### CLI Query: " + job.Query);
\r
472 logBuffer.AppendLine("### User Query: " + job.CustomQuery);
\r
473 logBuffer.AppendLine("#########################################");
\r
476 // Start the Reader
\r
477 // Only use text which continues on from the last read line
\r
478 StreamReader sr = new StreamReader(logFile2);
\r
481 while ((line = sr.ReadLine()) != null)
\r
483 if (i > logFilePosition)
\r
485 logBuffer.AppendLine(line);
\r
501 /// Reset the Log Reader
\r
503 private void ResetLogReader()
\r
505 logFilePosition = 0;
\r
506 logBuffer = new StringBuilder();
\r
510 /// Recieve the Standard Error information and process it
\r
512 /// <param name="sender">
\r
513 /// The Sender Object
\r
515 /// <param name="e">
\r
516 /// DataReceived EventArgs
\r
518 private void HbProcErrorDataReceived(object sender, DataReceivedEventArgs e)
\r
520 if (!String.IsNullOrEmpty(e.Data))
\r
523 logBuffer.AppendLine(e.Data);
\r
528 /// Standard Input Data Recieved from the CLI
\r
530 /// <param name="sender">
\r
531 /// The Sender Object
\r
533 /// <param name="e">
\r
534 /// DataReceived EventArgs
\r
536 private void HbProcOutputDataReceived(object sender, DataReceivedEventArgs e)
\r
538 if (!String.IsNullOrEmpty(e.Data))
\r
541 logBuffer.AppendLine(e.Data);
\r
548 /// <param name="sender">
\r
551 /// <param name="e">
\r
554 private void Encode_EncodeStarted(object sender, EventArgs e)
\r
556 Thread monitor = new Thread(EncodeMonitor);
\r
561 /// Monitor the Job
\r
563 private void EncodeMonitor()
\r
567 Parser encode = new Parser(HbProcess.StandardOutput.BaseStream);
\r
568 encode.OnEncodeProgress += EncodeOnEncodeProgress;
\r
569 while (!encode.EndOfStream)
\r
570 encode.ReadEncodeStatus();
\r
572 // Main.ShowExceptiowWindow("Encode Monitor Stopped", "Stopped");
\r
574 catch (Exception exc)
\r
576 Main.ShowExceptiowWindow("An Unknown Error has occured", exc.ToString());
\r
581 /// Displays the Encode status in the GUI
\r
583 /// <param name="sender">The sender</param>
\r
584 /// <param name="currentTask">The current task</param>
\r
585 /// <param name="taskCount">Number of tasks</param>
\r
586 /// <param name="percentComplete">Percent complete</param>
\r
587 /// <param name="currentFps">Current encode speed in fps</param>
\r
588 /// <param name="avg">Avg encode speed</param>
\r
589 /// <param name="timeRemaining">Time Left</param>
\r
590 private void EncodeOnEncodeProgress(object sender, int currentTask, int taskCount, float percentComplete, float currentFps, float avg, TimeSpan timeRemaining)
\r
592 EncodeProgressEventArgs eventArgs = new EncodeProgressEventArgs
\r
594 AverageFrameRate = avg,
\r
595 CurrentFrameRate = currentFps,
\r
596 EstimatedTimeLeft = timeRemaining,
\r
597 PercentComplete = percentComplete,
\r
598 Task = currentTask,
\r
599 TaskCount = taskCount
\r
602 if (this.EncodeStatusChanged != null)
\r
603 this.EncodeStatusChanged(this, eventArgs);
\r