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
22 /// Class which handles the CLI
\r
24 public class Encode : IEncode
\r
26 #region Private Variables
\r
31 private StringBuilder logBuffer;
\r
34 /// The Log file writer
\r
36 private StreamWriter fileWriter;
\r
39 /// Gets The Process Handle
\r
41 private IntPtr processHandle;
\r
44 /// Gets the Process ID
\r
46 private int processID;
\r
49 /// Windows 7 API Pack wrapper
\r
51 private Win7 windowsSeven = new Win7();
\r
58 /// Initializes a new instance of the <see cref="Encode"/> class.
\r
62 this.EncodeStarted += Encode_EncodeStarted;
\r
65 #region Delegates and Event Handlers
\r
68 /// Encode Progess Status
\r
70 /// <param name="sender">
\r
73 /// <param name="e">
\r
74 /// The EncodeProgressEventArgs.
\r
76 public delegate void EncodeProgessStatus(object sender, EncodeProgressEventArgs e);
\r
78 /* Event Handlers */
\r
81 /// Fires when a new CLI Job starts
\r
83 public event EventHandler EncodeStarted;
\r
86 /// Fires when a CLI job finishes.
\r
88 public event EventHandler EncodeEnded;
\r
91 /// Encode process has progressed
\r
93 public event EncodeProgessStatus EncodeStatusChanged;
\r
99 /// Gets or sets The HB Process
\r
101 protected Process HbProcess { get; set; }
\r
104 /// Gets a value indicating whether IsEncoding.
\r
106 public bool IsEncoding { get; private set; }
\r
109 /// Gets ActivityLog.
\r
111 public string ActivityLog
\r
115 if (this.IsEncoding == false)
\r
117 ReadFile(); // Read the last log file back in if it exists
\r
120 return string.IsNullOrEmpty(this.logBuffer.ToString()) ? "No log data available..." : this.logBuffer.ToString();
\r
124 /* Public Methods */
\r
127 /// Create a preview sample video
\r
129 /// <param name="query">
\r
132 public void CreatePreviewSample(string query)
\r
134 this.Run(new Job { Query = query }, false);
\r
138 /// Execute a HandBrakeCLI process.
\r
140 /// <param name="encJob">
\r
143 /// <param name="enableLogging">
\r
144 /// Enable Logging. When Disabled we onlt parse Standard Ouput for progress info. Standard Error log data is ignored.
\r
146 protected void Run(Job encJob, bool enableLogging)
\r
153 SetupLogging(encJob);
\r
155 if (Init.PreventSleep)
\r
157 Win32.PreventSleep();
\r
160 string handbrakeCLIPath = Path.Combine(Application.StartupPath, "HandBrakeCLI.exe");
\r
161 ProcessStartInfo cliStart = new ProcessStartInfo(handbrakeCLIPath, encJob.Query)
\r
163 RedirectStandardOutput = true,
\r
164 RedirectStandardError = enableLogging ? true : false,
\r
165 UseShellExecute = false,
\r
166 CreateNoWindow = !Init.ShowCliForInGuiEncodeStatus ? true : false
\r
169 this.HbProcess = Process.Start(cliStart);
\r
173 this.HbProcess.ErrorDataReceived += HbProcErrorDataReceived;
\r
174 this.HbProcess.BeginErrorReadLine();
\r
177 this.processID = HbProcess.Id;
\r
178 this.processHandle = HbProcess.Handle;
\r
180 // Set the process Priority
\r
181 if (this.processID != -1)
\r
183 this.HbProcess.EnableRaisingEvents = true;
\r
184 this.HbProcess.Exited += HbProcess_Exited;
\r
187 // Set the Process Priority
\r
188 switch (Init.ProcessPriority)
\r
191 this.HbProcess.PriorityClass = ProcessPriorityClass.RealTime;
\r
194 this.HbProcess.PriorityClass = ProcessPriorityClass.High;
\r
196 case "Above Normal":
\r
197 this.HbProcess.PriorityClass = ProcessPriorityClass.AboveNormal;
\r
200 this.HbProcess.PriorityClass = ProcessPriorityClass.Normal;
\r
203 this.HbProcess.PriorityClass = ProcessPriorityClass.Idle;
\r
206 this.HbProcess.PriorityClass = ProcessPriorityClass.BelowNormal;
\r
210 // Fire the Encode Started Event
\r
211 if (this.EncodeStarted != null)
\r
212 this.EncodeStarted(this, new EventArgs());
\r
214 catch (Exception exc)
\r
216 Main.ShowExceptiowWindow("It would appear that HandBrakeCLI has not started correctly." +
\r
217 "You should take a look at the Activity log as it may indicate the reason why.\n\nDetailed Error Information: error occured in runCli()",
\r
223 /// Kill the CLI process
\r
229 if (this.HbProcess != null) this.HbProcess.Kill();
\r
231 catch (Exception exc)
\r
233 Main.ShowExceptiowWindow("Unable to stop HandBrakeCLI. It may not be running.", exc.ToString());
\r
236 if (this.EncodeEnded != null)
\r
237 this.EncodeEnded(this, new EventArgs());
\r
241 /// Attempt to Safely kill a DirectRun() CLI
\r
242 /// NOTE: This will not work with a MinGW CLI
\r
243 /// Note: http://www.cygwin.com/ml/cygwin/2006-03/msg00330.html
\r
245 public void SafelyClose()
\r
247 if ((int)this.processHandle == 0)
\r
250 // Allow the CLI to exit cleanly
\r
251 Win32.SetForegroundWindow((int)this.processHandle);
\r
252 SendKeys.Send("^C");
\r
255 //if (HbProcess != null)
\r
257 // HbProcess.StandardInput.AutoFlush = true;
\r
258 // HbProcess.StandardInput.WriteLine("^c^z");
\r
264 /// Save a copy of the log to the users desired location or a default location
\r
265 /// if this feature is enabled in options.
\r
267 /// <param name="destination">
\r
268 /// The Destination File Path
\r
270 protected void CopyLog(string destination)
\r
274 string logDir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) +
\r
275 "\\HandBrake\\logs";
\r
276 string tempLogFile = Path.Combine(logDir, string.Format("last_encode_log{0}.txt", Init.InstanceId));
\r
278 string encodeDestinationPath = Path.GetDirectoryName(destination);
\r
279 string destinationFile = Path.GetFileName(destination);
\r
280 string encodeLogFile = destinationFile + " " +
\r
281 DateTime.Now.ToString().Replace("/", "-").Replace(":", "-") + ".txt";
\r
283 // Make sure the log directory exists.
\r
284 if (!Directory.Exists(logDir))
\r
285 Directory.CreateDirectory(logDir);
\r
287 // Copy the Log to HandBrakes log folder in the users applciation data folder.
\r
288 File.Copy(tempLogFile, Path.Combine(logDir, encodeLogFile));
\r
290 // Save a copy of the log file in the same location as the enocde.
\r
291 if (Init.SaveLogWithVideo)
\r
292 File.Copy(tempLogFile, Path.Combine(encodeDestinationPath, encodeLogFile));
\r
294 // Save a copy of the log file to a user specified location
\r
295 if (Directory.Exists(Init.SaveLogPath))
\r
296 if (Init.SaveLogPath != String.Empty && Init.SaveLogToSpecifiedPath)
\r
297 File.Copy(tempLogFile, Path.Combine(Init.SaveLogPath, encodeLogFile));
\r
299 catch (Exception exc)
\r
301 Main.ShowExceptiowWindow("Unable to make a copy of the log file", exc.ToString());
\r
306 /// The HandBrakeCLI process has exited.
\r
308 /// <param name="sender">
\r
311 /// <param name="e">
\r
314 private void HbProcess_Exited(object sender, EventArgs e)
\r
316 IsEncoding = false;
\r
320 if (this.EncodeEnded != null)
\r
321 this.EncodeEnded(this, new EventArgs());
\r
323 if (windowsSeven.IsWindowsSeven)
\r
325 windowsSeven.SetTaskBarProgressToNoProgress();
\r
328 if (Init.PreventSleep)
\r
330 Win32.AllowSleep();
\r
335 if (fileWriter != null)
\r
336 fileWriter.Close();
\r
338 catch (Exception exc)
\r
340 Main.ShowExceptiowWindow("Unable to close the log file wrtier", exc.ToString());
\r
345 /// Read the log file
\r
347 /// <param name="n">
\r
350 private void ReadFile()
\r
352 logBuffer = new StringBuilder();
\r
355 // 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
356 // we'll need to make a copy of it.
\r
357 string logDir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\HandBrake\\logs";
\r
358 string logFile = Path.Combine(logDir, string.Format("last_encode_log{0}.txt", Init.InstanceId));
\r
359 string logFile2 = Path.Combine(logDir, string.Format("tmp_appReadable_log{0}.txt", Init.InstanceId));
\r
360 int logFilePosition = 0;
\r
364 // Make sure the application readable log file does not already exist. FileCopy fill fail if it does.
\r
365 if (File.Exists(logFile2))
\r
366 File.Delete(logFile2);
\r
368 // Copy the log file.
\r
369 if (File.Exists(logFile))
\r
370 File.Copy(logFile, logFile2, true);
\r
374 // Start the Reader
\r
375 // Only use text which continues on from the last read line
\r
376 StreamReader sr = new StreamReader(logFile2);
\r
379 while ((line = sr.ReadLine()) != null)
\r
381 if (i > logFilePosition)
\r
383 logBuffer.AppendLine(line);
\r
391 catch (Exception exc)
\r
393 Main.ShowExceptiowWindow("Unable to read log file", exc.ToString());
\r
399 /// Setup the logging.
\r
401 private void SetupLogging(Job encodeJob)
\r
403 string logDir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\HandBrake\\logs";
\r
404 string logFile = Path.Combine(logDir, string.Format("last_encode_log{0}.txt", Init.InstanceId));
\r
405 string logFile2 = Path.Combine(logDir, string.Format("tmp_appReadable_log{0}.txt", Init.InstanceId));
\r
409 logBuffer = new StringBuilder();
\r
411 // Clear the current Encode Logs
\r
412 if (File.Exists(logFile)) File.Delete(logFile);
\r
413 if (File.Exists(logFile2)) File.Delete(logFile2);
\r
415 fileWriter = new StreamWriter(logFile) { AutoFlush = true };
\r
417 fileWriter.WriteLine(Logging.CreateCliLogHeader(encodeJob));
\r
418 logBuffer.AppendLine(Logging.CreateCliLogHeader(encodeJob));
\r
420 catch (Exception exc)
\r
422 if (fileWriter != null)
\r
423 fileWriter.Close();
\r
424 Main.ShowExceptiowWindow("Error", exc.ToString());
\r
429 /// Recieve the Standard Error information and process it
\r
431 /// <param name="sender">
\r
432 /// The Sender Object
\r
434 /// <param name="e">
\r
435 /// DataReceived EventArgs
\r
437 private void HbProcErrorDataReceived(object sender, DataReceivedEventArgs e)
\r
439 if (!String.IsNullOrEmpty(e.Data))
\r
442 logBuffer.AppendLine(e.Data);
\r
446 if (fileWriter != null)
\r
447 fileWriter.WriteLine(e.Data);
\r
449 catch (Exception exc)
\r
451 Main.ShowExceptiowWindow("Unable to write log data...", exc.ToString());
\r
456 #region Encode Status from Standard Output
\r
461 /// <param name="sender">
\r
464 /// <param name="e">
\r
467 private void Encode_EncodeStarted(object sender, EventArgs e)
\r
469 Thread monitor = new Thread(EncodeMonitor);
\r
474 /// Monitor the Job
\r
476 private void EncodeMonitor()
\r
480 Parser encode = new Parser(HbProcess.StandardOutput.BaseStream);
\r
481 encode.OnEncodeProgress += EncodeOnEncodeProgress;
\r
482 while (!encode.EndOfStream)
\r
483 encode.ReadEncodeStatus();
\r
485 catch (Exception exc)
\r
487 Main.ShowExceptiowWindow("An Unknown Error has occured", exc.ToString());
\r
492 /// Displays the Encode status in the GUI
\r
494 /// <param name="sender">The sender</param>
\r
495 /// <param name="currentTask">The current task</param>
\r
496 /// <param name="taskCount">Number of tasks</param>
\r
497 /// <param name="percentComplete">Percent complete</param>
\r
498 /// <param name="currentFps">Current encode speed in fps</param>
\r
499 /// <param name="avg">Avg encode speed</param>
\r
500 /// <param name="timeRemaining">Time Left</param>
\r
501 private void EncodeOnEncodeProgress(object sender, int currentTask, int taskCount, float percentComplete, float currentFps, float avg, TimeSpan timeRemaining)
\r
503 EncodeProgressEventArgs eventArgs = new EncodeProgressEventArgs
\r
505 AverageFrameRate = avg,
\r
506 CurrentFrameRate = currentFps,
\r
507 EstimatedTimeLeft = timeRemaining,
\r
508 PercentComplete = percentComplete,
\r
509 Task = currentTask,
\r
510 TaskCount = taskCount
\r
513 if (this.EncodeStatusChanged != null)
\r
514 this.EncodeStatusChanged(this, eventArgs);
\r
516 if (windowsSeven.IsWindowsSeven)
\r
519 int.TryParse(Math.Round(percentComplete).ToString(), out percent);
\r
521 windowsSeven.SetTaskBarProgress(percent);
\r