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
63 GrowlCommunicator.Register();
\r
66 #region Delegates and Event Handlers
\r
69 /// Encode Progess Status
\r
71 /// <param name="sender">
\r
74 /// <param name="e">
\r
75 /// The EncodeProgressEventArgs.
\r
77 public delegate void EncodeProgessStatus(object sender, EncodeProgressEventArgs e);
\r
79 /* Event Handlers */
\r
82 /// Fires when a new CLI Job starts
\r
84 public event EventHandler EncodeStarted;
\r
87 /// Fires when a CLI job finishes.
\r
89 public event EventHandler EncodeEnded;
\r
92 /// Encode process has progressed
\r
94 public event EncodeProgessStatus EncodeStatusChanged;
\r
100 /// Gets or sets The HB Process
\r
102 protected Process HbProcess { get; set; }
\r
105 /// Gets a value indicating whether IsEncoding.
\r
107 public bool IsEncoding { get; private set; }
\r
110 /// Gets ActivityLog.
\r
112 public string ActivityLog
\r
116 if (this.IsEncoding == false)
\r
118 ReadFile(); // Read the last log file back in if it exists
\r
121 return string.IsNullOrEmpty(this.logBuffer.ToString()) ? "No log data available..." : this.logBuffer.ToString();
\r
125 /* Public Methods */
\r
128 /// Create a preview sample video
\r
130 /// <param name="query">
\r
133 public void CreatePreviewSample(string query)
\r
135 this.Run(new Job { Query = query }, false);
\r
139 /// Execute a HandBrakeCLI process.
\r
141 /// <param name="encJob">
\r
144 /// <param name="enableLogging">
\r
145 /// Enable Logging. When Disabled we onlt parse Standard Ouput for progress info. Standard Error log data is ignored.
\r
147 protected void Run(Job encJob, bool enableLogging)
\r
154 SetupLogging(encJob);
\r
156 if (Init.PreventSleep)
\r
158 Win32.PreventSleep();
\r
161 string handbrakeCLIPath = Path.Combine(Application.StartupPath, "HandBrakeCLI.exe");
\r
162 ProcessStartInfo cliStart = new ProcessStartInfo(handbrakeCLIPath, encJob.Query)
\r
164 RedirectStandardOutput = true,
\r
165 RedirectStandardError = enableLogging ? true : false,
\r
166 UseShellExecute = false,
\r
167 CreateNoWindow = !Init.ShowCliForInGuiEncodeStatus ? true : false
\r
170 this.HbProcess = Process.Start(cliStart);
\r
174 this.HbProcess.ErrorDataReceived += HbProcErrorDataReceived;
\r
175 this.HbProcess.BeginErrorReadLine();
\r
178 this.processID = HbProcess.Id;
\r
179 this.processHandle = HbProcess.Handle;
\r
181 // Set the process Priority
\r
182 if (this.processID != -1)
\r
184 this.HbProcess.EnableRaisingEvents = true;
\r
185 this.HbProcess.Exited += HbProcess_Exited;
\r
188 // Set the Process Priority
\r
189 switch (Init.ProcessPriority)
\r
192 this.HbProcess.PriorityClass = ProcessPriorityClass.RealTime;
\r
195 this.HbProcess.PriorityClass = ProcessPriorityClass.High;
\r
197 case "Above Normal":
\r
198 this.HbProcess.PriorityClass = ProcessPriorityClass.AboveNormal;
\r
201 this.HbProcess.PriorityClass = ProcessPriorityClass.Normal;
\r
204 this.HbProcess.PriorityClass = ProcessPriorityClass.Idle;
\r
207 this.HbProcess.PriorityClass = ProcessPriorityClass.BelowNormal;
\r
211 // Fire the Encode Started Event
\r
212 if (this.EncodeStarted != null)
\r
213 this.EncodeStarted(this, new EventArgs());
\r
215 catch (Exception exc)
\r
217 Main.ShowExceptiowWindow("It would appear that HandBrakeCLI has not started correctly." +
\r
218 "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
224 /// Kill the CLI process
\r
230 if (this.HbProcess != null) this.HbProcess.Kill();
\r
232 catch (Exception exc)
\r
234 Main.ShowExceptiowWindow("Unable to stop HandBrakeCLI. It may not be running.", exc.ToString());
\r
237 if (this.EncodeEnded != null)
\r
238 this.EncodeEnded(this, new EventArgs());
\r
242 /// Attempt to Safely kill a DirectRun() CLI
\r
243 /// NOTE: This will not work with a MinGW CLI
\r
244 /// Note: http://www.cygwin.com/ml/cygwin/2006-03/msg00330.html
\r
246 public void SafelyClose()
\r
248 if ((int)this.processHandle == 0)
\r
251 // Allow the CLI to exit cleanly
\r
252 Win32.SetForegroundWindow((int)this.processHandle);
\r
253 SendKeys.Send("^C");
\r
256 /*/if (HbProcess != null)
\r
258 // HbProcess.StandardInput.AutoFlush = true;
\r
259 // HbProcess.StandardInput.WriteLine("^c^z");
\r
266 /// Save a copy of the log to the users desired location or a default location
\r
267 /// if this feature is enabled in options.
\r
269 /// <param name="destination">
\r
270 /// The Destination File Path
\r
272 protected void CopyLog(string destination)
\r
276 string logDir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) +
\r
277 "\\HandBrake\\logs";
\r
278 string tempLogFile = Path.Combine(logDir, string.Format("last_encode_log{0}.txt", Init.InstanceId));
\r
280 string encodeDestinationPath = Path.GetDirectoryName(destination);
\r
281 string destinationFile = Path.GetFileName(destination);
\r
282 string encodeLogFile = destinationFile + " " +
\r
283 DateTime.Now.ToString().Replace("/", "-").Replace(":", "-") + ".txt";
\r
285 // Make sure the log directory exists.
\r
286 if (!Directory.Exists(logDir))
\r
287 Directory.CreateDirectory(logDir);
\r
289 // Copy the Log to HandBrakes log folder in the users applciation data folder.
\r
290 File.Copy(tempLogFile, Path.Combine(logDir, encodeLogFile));
\r
292 // Save a copy of the log file in the same location as the enocde.
\r
293 if (Init.SaveLogWithVideo)
\r
294 File.Copy(tempLogFile, Path.Combine(encodeDestinationPath, encodeLogFile));
\r
296 // Save a copy of the log file to a user specified location
\r
297 if (Directory.Exists(Init.SaveLogPath))
\r
298 if (Init.SaveLogPath != String.Empty && Init.SaveLogToSpecifiedPath)
\r
299 File.Copy(tempLogFile, Path.Combine(Init.SaveLogPath, encodeLogFile));
\r
301 catch (Exception exc)
\r
303 Main.ShowExceptiowWindow("Unable to make a copy of the log file", exc.ToString());
\r
308 /// The HandBrakeCLI process has exited.
\r
310 /// <param name="sender">
\r
313 /// <param name="e">
\r
316 private void HbProcess_Exited(object sender, EventArgs e)
\r
318 IsEncoding = false;
\r
319 if (this.EncodeEnded != null)
\r
320 this.EncodeEnded(this, new EventArgs());
\r
322 if (windowsSeven.IsWindowsSeven)
\r
324 windowsSeven.SetTaskBarProgressToNoProgress();
\r
327 if (Init.PreventSleep)
\r
329 Win32.AllowSleep();
\r
334 if (fileWriter != null)
\r
335 fileWriter.Close();
\r
337 catch (Exception exc)
\r
339 Main.ShowExceptiowWindow("Unable to close the log file wrtier", exc.ToString());
\r
344 /// Read the log file
\r
346 private void ReadFile()
\r
348 logBuffer = new StringBuilder();
\r
351 // 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
352 // we'll need to make a copy of it.
\r
353 string logDir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\HandBrake\\logs";
\r
354 string logFile = Path.Combine(logDir, string.Format("last_encode_log{0}.txt", Init.InstanceId));
\r
355 string logFile2 = Path.Combine(logDir, string.Format("tmp_appReadable_log{0}.txt", Init.InstanceId));
\r
356 int logFilePosition = 0;
\r
360 // Make sure the application readable log file does not already exist. FileCopy fill fail if it does.
\r
361 if (File.Exists(logFile2))
\r
362 File.Delete(logFile2);
\r
364 // Copy the log file.
\r
365 if (File.Exists(logFile))
\r
366 File.Copy(logFile, logFile2, true);
\r
370 // Start the Reader
\r
371 // Only use text which continues on from the last read line
\r
372 StreamReader sr = new StreamReader(logFile2);
\r
375 while ((line = sr.ReadLine()) != null)
\r
377 if (i > logFilePosition)
\r
379 logBuffer.AppendLine(line);
\r
387 catch (Exception exc)
\r
389 Main.ShowExceptiowWindow("Unable to read log file", exc.ToString());
\r
395 /// Setup the logging.
\r
397 /// <param name="encodeJob">
\r
398 /// The encode Job.
\r
400 private void SetupLogging(Job encodeJob)
\r
402 string logDir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\HandBrake\\logs";
\r
403 string logFile = Path.Combine(logDir, string.Format("last_encode_log{0}.txt", Init.InstanceId));
\r
404 string logFile2 = Path.Combine(logDir, string.Format("tmp_appReadable_log{0}.txt", Init.InstanceId));
\r
408 logBuffer = new StringBuilder();
\r
410 // Clear the current Encode Logs
\r
411 if (File.Exists(logFile)) File.Delete(logFile);
\r
412 if (File.Exists(logFile2)) File.Delete(logFile2);
\r
414 fileWriter = new StreamWriter(logFile) { AutoFlush = true };
\r
416 fileWriter.WriteLine(Logging.CreateCliLogHeader(encodeJob));
\r
417 logBuffer.AppendLine(Logging.CreateCliLogHeader(encodeJob));
\r
419 catch (Exception exc)
\r
421 if (fileWriter != null)
\r
422 fileWriter.Close();
\r
423 Main.ShowExceptiowWindow("Error", exc.ToString());
\r
428 /// Recieve the Standard Error information and process it
\r
430 /// <param name="sender">
\r
431 /// The Sender Object
\r
433 /// <param name="e">
\r
434 /// DataReceived EventArgs
\r
436 private void HbProcErrorDataReceived(object sender, DataReceivedEventArgs e)
\r
438 if (!String.IsNullOrEmpty(e.Data))
\r
441 logBuffer.AppendLine(e.Data);
\r
445 if (fileWriter != null)
\r
446 fileWriter.WriteLine(e.Data);
\r
448 catch (Exception exc)
\r
450 Main.ShowExceptiowWindow("Unable to write log data...", exc.ToString());
\r
455 #region Encode Status from Standard Output
\r
460 /// <param name="sender">
\r
463 /// <param name="e">
\r
466 private void Encode_EncodeStarted(object sender, EventArgs e)
\r
468 Thread monitor = new Thread(EncodeMonitor);
\r
473 /// Monitor the Job
\r
475 private void EncodeMonitor()
\r
479 Parser encode = new Parser(HbProcess.StandardOutput.BaseStream);
\r
480 encode.OnEncodeProgress += EncodeOnEncodeProgress;
\r
481 while (!encode.EndOfStream)
\r
482 encode.ReadEncodeStatus();
\r
484 catch (Exception exc)
\r
486 Main.ShowExceptiowWindow("An Unknown Error has occured", exc.ToString());
\r
491 /// Displays the Encode status in the GUI
\r
493 /// <param name="sender">The sender</param>
\r
494 /// <param name="currentTask">The current task</param>
\r
495 /// <param name="taskCount">Number of tasks</param>
\r
496 /// <param name="percentComplete">Percent complete</param>
\r
497 /// <param name="currentFps">Current encode speed in fps</param>
\r
498 /// <param name="avg">Avg encode speed</param>
\r
499 /// <param name="timeRemaining">Time Left</param>
\r
500 private void EncodeOnEncodeProgress(object sender, int currentTask, int taskCount, float percentComplete, float currentFps, float avg, string timeRemaining)
\r
502 EncodeProgressEventArgs eventArgs = new EncodeProgressEventArgs
\r
504 AverageFrameRate = avg,
\r
505 CurrentFrameRate = currentFps,
\r
506 EstimatedTimeLeft = timeRemaining,
\r
507 PercentComplete = percentComplete,
\r
508 Task = currentTask,
\r
509 TaskCount = taskCount
\r
512 if (this.EncodeStatusChanged != null)
\r
513 this.EncodeStatusChanged(this, eventArgs);
\r
515 if (windowsSeven.IsWindowsSeven)
\r
518 int.TryParse(Math.Round(percentComplete).ToString(), out percent);
\r
520 windowsSeven.SetTaskBarProgress(percent);
\r