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.Services.Interfaces;
\r
21 /// Class which handles the CLI
\r
23 public class Encode : IEncode
\r
25 #region Private Variables
\r
30 private StringBuilder logBuffer;
\r
33 /// The Log file writer
\r
35 private StreamWriter fileWriter;
\r
38 /// Gets The Process Handle
\r
40 private IntPtr processHandle;
\r
43 /// Gets the Process ID
\r
45 private int processID;
\r
48 /// Windows 7 API Pack wrapper
\r
50 private Win7 windowsSeven = new Win7();
\r
57 /// Initializes a new instance of the <see cref="Encode"/> class.
\r
61 this.EncodeStarted += Encode_EncodeStarted;
\r
64 #region Delegates and Event Handlers
\r
67 /// Encode Progess Status
\r
69 /// <param name="sender">
\r
72 /// <param name="e">
\r
73 /// The EncodeProgressEventArgs.
\r
75 public delegate void EncodeProgessStatus(object sender, EncodeProgressEventArgs e);
\r
77 /* Event Handlers */
\r
80 /// Fires when a new CLI Job starts
\r
82 public event EventHandler EncodeStarted;
\r
85 /// Fires when a CLI job finishes.
\r
87 public event EventHandler EncodeEnded;
\r
90 /// Encode process has progressed
\r
92 public event EncodeProgessStatus EncodeStatusChanged;
\r
98 /// Gets or sets The HB Process
\r
100 protected Process HbProcess { get; set; }
\r
103 /// Gets a value indicating whether IsEncoding.
\r
105 public bool IsEncoding { get; private set; }
\r
108 /// Gets ActivityLog.
\r
110 public string ActivityLog
\r
114 if (this.IsEncoding == false)
\r
116 ReadFile(); // Read the last log file back in if it exists
\r
119 return string.IsNullOrEmpty(this.logBuffer.ToString()) ? "No log data available..." : this.logBuffer.ToString();
\r
123 /* Public Methods */
\r
126 /// Create a preview sample video
\r
128 /// <param name="query">
\r
131 public void CreatePreviewSample(string query)
\r
133 this.Run(new Job { Query = query }, false);
\r
137 /// Execute a HandBrakeCLI process.
\r
139 /// <param name="encJob">
\r
142 /// <param name="enableLogging">
\r
143 /// Enable Logging. When Disabled we onlt parse Standard Ouput for progress info. Standard Error log data is ignored.
\r
145 protected void Run(Job encJob, bool enableLogging)
\r
152 SetupLogging(encJob);
\r
154 if (Init.PreventSleep)
\r
156 Win32.PreventSleep();
\r
159 string handbrakeCLIPath = Path.Combine(Application.StartupPath, "HandBrakeCLI.exe");
\r
160 ProcessStartInfo cliStart = new ProcessStartInfo(handbrakeCLIPath, encJob.Query)
\r
162 RedirectStandardOutput = true,
\r
163 RedirectStandardError = enableLogging ? true : false,
\r
164 UseShellExecute = false,
\r
165 CreateNoWindow = !Init.ShowCliForInGuiEncodeStatus ? true : false
\r
168 this.HbProcess = Process.Start(cliStart);
\r
172 this.HbProcess.ErrorDataReceived += HbProcErrorDataReceived;
\r
173 this.HbProcess.BeginErrorReadLine();
\r
176 this.processID = HbProcess.Id;
\r
177 this.processHandle = HbProcess.Handle;
\r
179 // Set the process Priority
\r
180 if (this.processID != -1)
\r
182 this.HbProcess.EnableRaisingEvents = true;
\r
183 this.HbProcess.Exited += HbProcess_Exited;
\r
186 // Set the Process Priority
\r
187 switch (Init.ProcessPriority)
\r
190 this.HbProcess.PriorityClass = ProcessPriorityClass.RealTime;
\r
193 this.HbProcess.PriorityClass = ProcessPriorityClass.High;
\r
195 case "Above Normal":
\r
196 this.HbProcess.PriorityClass = ProcessPriorityClass.AboveNormal;
\r
199 this.HbProcess.PriorityClass = ProcessPriorityClass.Normal;
\r
202 this.HbProcess.PriorityClass = ProcessPriorityClass.Idle;
\r
205 this.HbProcess.PriorityClass = ProcessPriorityClass.BelowNormal;
\r
209 // Fire the Encode Started Event
\r
210 if (this.EncodeStarted != null)
\r
211 this.EncodeStarted(this, new EventArgs());
\r
213 catch (Exception exc)
\r
215 Main.ShowExceptiowWindow("It would appear that HandBrakeCLI has not started correctly." +
\r
216 "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
222 /// Kill the CLI process
\r
228 if (this.HbProcess != null) this.HbProcess.Kill();
\r
230 catch (Exception exc)
\r
232 Main.ShowExceptiowWindow("Unable to stop HandBrakeCLI. It may not be running.", exc.ToString());
\r
235 if (this.EncodeEnded != null)
\r
236 this.EncodeEnded(this, new EventArgs());
\r
240 /// Attempt to Safely kill a DirectRun() CLI
\r
241 /// NOTE: This will not work with a MinGW CLI
\r
242 /// Note: http://www.cygwin.com/ml/cygwin/2006-03/msg00330.html
\r
244 public void SafelyClose()
\r
246 if ((int)this.processHandle == 0)
\r
249 // Allow the CLI to exit cleanly
\r
250 Win32.SetForegroundWindow((int)this.processHandle);
\r
251 SendKeys.Send("^C");
\r
254 /*//if (HbProcess != null)
\r
256 // HbProcess.StandardInput.AutoFlush = true;
\r
257 // 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
318 if (this.EncodeEnded != null)
\r
319 this.EncodeEnded(this, new EventArgs());
\r
321 if (windowsSeven.IsWindowsSeven)
\r
323 windowsSeven.SetTaskBarProgressToNoProgress();
\r
326 if (Init.PreventSleep)
\r
328 Win32.AllowSleep();
\r
333 if (fileWriter != null)
\r
334 fileWriter.Close();
\r
336 catch (Exception exc)
\r
338 Main.ShowExceptiowWindow("Unable to close the log file wrtier", exc.ToString());
\r
343 /// Read the log file
\r
345 private void ReadFile()
\r
347 logBuffer = new StringBuilder();
\r
350 // 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
351 // we'll need to make a copy of it.
\r
352 string logDir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\HandBrake\\logs";
\r
353 string logFile = Path.Combine(logDir, string.Format("last_encode_log{0}.txt", Init.InstanceId));
\r
354 string logFile2 = Path.Combine(logDir, string.Format("tmp_appReadable_log{0}.txt", Init.InstanceId));
\r
355 int logFilePosition = 0;
\r
359 // Make sure the application readable log file does not already exist. FileCopy fill fail if it does.
\r
360 if (File.Exists(logFile2))
\r
361 File.Delete(logFile2);
\r
363 // Copy the log file.
\r
364 if (File.Exists(logFile))
\r
365 File.Copy(logFile, logFile2, true);
\r
369 // Start the Reader
\r
370 // Only use text which continues on from the last read line
\r
371 StreamReader sr = new StreamReader(logFile2);
\r
374 while ((line = sr.ReadLine()) != null)
\r
376 if (i > logFilePosition)
\r
378 logBuffer.AppendLine(line);
\r
386 catch (Exception exc)
\r
388 Main.ShowExceptiowWindow("Unable to read log file", exc.ToString());
\r
394 /// Setup the logging.
\r
396 /// <param name="encodeJob">The Encode Job Object</param>
\r
397 private void SetupLogging(Job encodeJob)
\r
399 string logDir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\HandBrake\\logs";
\r
400 string logFile = Path.Combine(logDir, string.Format("last_encode_log{0}.txt", Init.InstanceId));
\r
401 string logFile2 = Path.Combine(logDir, string.Format("tmp_appReadable_log{0}.txt", Init.InstanceId));
\r
405 logBuffer = new StringBuilder();
\r
407 // Clear the current Encode Logs
\r
408 if (File.Exists(logFile)) File.Delete(logFile);
\r
409 if (File.Exists(logFile2)) File.Delete(logFile2);
\r
411 fileWriter = new StreamWriter(logFile) { AutoFlush = true };
\r
413 fileWriter.WriteLine(Logging.CreateCliLogHeader(encodeJob));
\r
414 logBuffer.AppendLine(Logging.CreateCliLogHeader(encodeJob));
\r
416 catch (Exception exc)
\r
418 if (fileWriter != null)
\r
419 fileWriter.Close();
\r
420 Main.ShowExceptiowWindow("Error", exc.ToString());
\r
425 /// Recieve the Standard Error information and process it
\r
427 /// <param name="sender">
\r
428 /// The Sender Object
\r
430 /// <param name="e">
\r
431 /// DataReceived EventArgs
\r
433 private void HbProcErrorDataReceived(object sender, DataReceivedEventArgs e)
\r
435 if (!String.IsNullOrEmpty(e.Data))
\r
438 logBuffer.AppendLine(e.Data);
\r
442 if (fileWriter != null)
\r
443 fileWriter.WriteLine(e.Data);
\r
445 catch (Exception exc)
\r
447 Main.ShowExceptiowWindow("Unable to write log data...", exc.ToString());
\r
452 #region Encode Status from Standard Output
\r
457 /// <param name="sender">
\r
460 /// <param name="e">
\r
463 private void Encode_EncodeStarted(object sender, EventArgs e)
\r
465 Thread monitor = new Thread(EncodeMonitor);
\r
470 /// Monitor the Job
\r
472 private void EncodeMonitor()
\r
476 Parser encode = new Parser(HbProcess.StandardOutput.BaseStream);
\r
477 encode.OnEncodeProgress += EncodeOnEncodeProgress;
\r
478 while (!encode.EndOfStream)
\r
479 encode.ReadEncodeStatus();
\r
481 catch (Exception exc)
\r
483 Main.ShowExceptiowWindow("An Unknown Error has occured", exc.ToString());
\r
488 /// Displays the Encode status in the GUI
\r
490 /// <param name="sender">The sender</param>
\r
491 /// <param name="currentTask">The current task</param>
\r
492 /// <param name="taskCount">Number of tasks</param>
\r
493 /// <param name="percentComplete">Percent complete</param>
\r
494 /// <param name="currentFps">Current encode speed in fps</param>
\r
495 /// <param name="avg">Avg encode speed</param>
\r
496 /// <param name="timeRemaining">Time Left</param>
\r
497 private void EncodeOnEncodeProgress(object sender, int currentTask, int taskCount, float percentComplete, float currentFps, float avg, TimeSpan timeRemaining)
\r
499 EncodeProgressEventArgs eventArgs = new EncodeProgressEventArgs
\r
501 AverageFrameRate = avg,
\r
502 CurrentFrameRate = currentFps,
\r
503 EstimatedTimeLeft = timeRemaining,
\r
504 PercentComplete = percentComplete,
\r
505 Task = currentTask,
\r
506 TaskCount = taskCount
\r
509 if (this.EncodeStatusChanged != null)
\r
510 this.EncodeStatusChanged(this, eventArgs);
\r
512 if (windowsSeven.IsWindowsSeven)
\r
515 int.TryParse(Math.Round(percentComplete).ToString(), out percent);
\r
517 windowsSeven.SetTaskBarProgress(percent);
\r