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.EventArgs;
\r
16 using HandBrake.ApplicationServices.Functions;
\r
17 using HandBrake.ApplicationServices.Model;
\r
18 using HandBrake.ApplicationServices.Parsing;
\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
56 /// Initializes a new instance of the <see cref="Encode"/> class.
\r
60 this.EncodeStarted += this.EncodeEncodeStarted;
\r
61 GrowlCommunicator.Register();
\r
64 #region Delegates and Event Handlers
\r
67 /// Fires when a new CLI QueueTask starts
\r
69 public event EventHandler EncodeStarted;
\r
72 /// Fires when a CLI QueueTask finishes.
\r
74 public event EncodeCompletedStatus EncodeCompleted;
\r
77 /// Encode process has progressed
\r
79 public event EncodeProgessStatus EncodeStatusChanged;
\r
85 /// Gets or sets The HB Process
\r
87 protected Process HbProcess { get; set; }
\r
90 /// Gets a value indicating whether IsEncoding.
\r
92 public bool IsEncoding { get; private set; }
\r
95 /// Gets ActivityLog.
\r
97 public string ActivityLog
\r
101 if (this.IsEncoding == false)
\r
105 ReadFile(); // Read the last log file back in if it exists
\r
107 catch (Exception exc)
\r
109 return exc.ToString();
\r
113 return string.IsNullOrEmpty(this.logBuffer.ToString()) ? "No log data available..." : this.logBuffer.ToString();
\r
119 #region Public Methods
\r
122 /// Execute a HandBrakeCLI process.
\r
124 /// <param name="encodeQueueTask">
\r
125 /// The encodeQueueTask.
\r
127 /// <param name="enableLogging">
\r
128 /// Enable Logging. When Disabled we onlt parse Standard Ouput for progress info. Standard Error log data is ignored.
\r
130 public void Start(QueueTask encodeQueueTask, bool enableLogging)
\r
134 QueueTask queueTask = encodeQueueTask;
\r
136 if (queueTask == null)
\r
138 throw new ArgumentNullException("QueueTask was null");
\r
143 throw new Exception("HandBrake is already encodeing.");
\r
152 SetupLogging(queueTask);
\r
156 IsEncoding = false;
\r
161 if (Init.PreventSleep)
\r
163 Win32.PreventSleep();
\r
166 string handbrakeCLIPath = Path.Combine(Application.StartupPath, "HandBrakeCLI.exe");
\r
167 ProcessStartInfo cliStart = new ProcessStartInfo(handbrakeCLIPath, queueTask.Query)
\r
169 RedirectStandardOutput = true,
\r
170 RedirectStandardError = enableLogging ? true : false,
\r
171 UseShellExecute = false,
\r
172 CreateNoWindow = !Init.ShowCliForInGuiEncodeStatus ? true : false
\r
175 this.HbProcess = Process.Start(cliStart);
\r
179 this.HbProcess.ErrorDataReceived += HbProcErrorDataReceived;
\r
180 this.HbProcess.BeginErrorReadLine();
\r
183 this.processId = HbProcess.Id;
\r
184 this.processHandle = HbProcess.Handle;
\r
186 // Set the process Priority
\r
187 if (this.processId != -1)
\r
189 this.HbProcess.EnableRaisingEvents = true;
\r
190 this.HbProcess.Exited += this.HbProcessExited;
\r
193 // Set the Process Priority
\r
194 switch (Init.ProcessPriority)
\r
197 this.HbProcess.PriorityClass = ProcessPriorityClass.RealTime;
\r
200 this.HbProcess.PriorityClass = ProcessPriorityClass.High;
\r
202 case "Above Normal":
\r
203 this.HbProcess.PriorityClass = ProcessPriorityClass.AboveNormal;
\r
206 this.HbProcess.PriorityClass = ProcessPriorityClass.Normal;
\r
209 this.HbProcess.PriorityClass = ProcessPriorityClass.Idle;
\r
212 this.HbProcess.PriorityClass = ProcessPriorityClass.BelowNormal;
\r
216 // Fire the Encode Started Event
\r
217 if (this.EncodeStarted != null)
\r
218 this.EncodeStarted(this, new EventArgs());
\r
220 catch (Exception exc)
\r
222 if (this.EncodeCompleted != null)
\r
223 this.EncodeCompleted(this, new EncodeCompletedEventArgs(false, exc, "An Error has occured in EncodeService.Run()"));
\r
228 /// Stop the Encode
\r
236 /// Kill the CLI process
\r
238 /// <param name="exc">
\r
239 /// The Exception that has occured.
\r
240 /// This will get bubbled up through the EncodeCompletedEventArgs
\r
242 public void Stop(Exception exc)
\r
246 if (this.HbProcess != null && !this.HbProcess.HasExited)
\r
248 this.HbProcess.Kill();
\r
253 // No need to report anything to the user. If it fails, it's probably already stopped.
\r
259 if (this.EncodeCompleted != null)
\r
260 this.EncodeCompleted(this, new EncodeCompletedEventArgs(true, null, string.Empty));
\r
264 if (this.EncodeCompleted != null)
\r
265 this.EncodeCompleted(this, new EncodeCompletedEventArgs(false, exc, "An Error has occured."));
\r
270 /// Attempt to Safely kill a DirectRun() CLI
\r
271 /// NOTE: This will not work with a MinGW CLI
\r
272 /// Note: http://www.cygwin.com/ml/cygwin/2006-03/msg00330.html
\r
274 public void SafelyStop()
\r
276 if ((int)this.processHandle == 0)
\r
279 // Allow the CLI to exit cleanly
\r
280 Win32.SetForegroundWindow((int)this.processHandle);
\r
281 SendKeys.Send("^C");
\r
284 /*/if (HbProcess != null)
\r
286 // HbProcess.StandardInput.AutoFlush = true;
\r
287 // HbProcess.StandardInput.WriteLine("^c^z");
\r
292 /// Save a copy of the log to the users desired location or a default location
\r
293 /// if this feature is enabled in options.
\r
295 /// <param name="destination">
\r
296 /// The Destination File Path
\r
298 public void ProcessLogs(string destination)
\r
302 string logDir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) +
\r
303 "\\HandBrake\\logs";
\r
304 string tempLogFile = Path.Combine(logDir, string.Format("last_encode_log{0}.txt", Init.InstanceId));
\r
306 string encodeDestinationPath = Path.GetDirectoryName(destination);
\r
307 string destinationFile = Path.GetFileName(destination);
\r
308 string encodeLogFile = destinationFile + " " +
\r
309 DateTime.Now.ToString().Replace("/", "-").Replace(":", "-") + ".txt";
\r
311 // Make sure the log directory exists.
\r
312 if (!Directory.Exists(logDir))
\r
313 Directory.CreateDirectory(logDir);
\r
315 // Copy the Log to HandBrakes log folder in the users applciation data folder.
\r
316 File.Copy(tempLogFile, Path.Combine(logDir, encodeLogFile));
\r
318 // Save a copy of the log file in the same location as the enocde.
\r
319 if (Init.SaveLogWithVideo)
\r
320 File.Copy(tempLogFile, Path.Combine(encodeDestinationPath, encodeLogFile));
\r
322 // Save a copy of the log file to a user specified location
\r
323 if (Directory.Exists(Init.SaveLogPath))
\r
324 if (Init.SaveLogPath != String.Empty && Init.SaveLogToSpecifiedPath)
\r
325 File.Copy(tempLogFile, Path.Combine(Init.SaveLogPath, encodeLogFile));
\r
327 catch (Exception exc)
\r
329 // This exception doesn't warrent user interaction, but it should be logged (TODO)
\r
335 #region Private Helper Methods
\r
338 /// The HandBrakeCLI process has exited.
\r
340 /// <param name="sender">
\r
343 /// <param name="e">
\r
346 private void HbProcessExited(object sender, EventArgs e)
\r
348 IsEncoding = false;
\r
350 if (windowsSeven.IsWindowsSeven)
\r
352 windowsSeven.SetTaskBarProgressToNoProgress();
\r
355 if (Init.PreventSleep)
\r
357 Win32.AllowSleep();
\r
362 if (fileWriter != null)
\r
364 fileWriter.Close();
\r
365 fileWriter.Dispose();
\r
368 catch (Exception exc)
\r
370 // This exception doesn't warrent user interaction, but it should be logged (TODO)
\r
373 if (this.EncodeCompleted != null)
\r
374 this.EncodeCompleted(this, new EncodeCompletedEventArgs(true, null, string.Empty));
\r
378 /// Read the log file
\r
380 private void ReadFile()
\r
382 logBuffer = new StringBuilder();
\r
385 // 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
386 // we'll need to make a copy of it.
\r
387 string logDir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\HandBrake\\logs";
\r
388 string logFile = Path.Combine(logDir, string.Format("last_encode_log{0}.txt", Init.InstanceId));
\r
389 string logFile2 = Path.Combine(logDir, string.Format("tmp_appReadable_log{0}.txt", Init.InstanceId));
\r
390 int logFilePosition = 0;
\r
394 // Copy the log file.
\r
395 if (File.Exists(logFile))
\r
396 File.Copy(logFile, logFile2, true);
\r
400 // Start the Reader
\r
401 // Only use text which continues on from the last read line
\r
402 using (StreamReader sr = new StreamReader(logFile2))
\r
406 while ((line = sr.ReadLine()) != null)
\r
408 if (i > logFilePosition)
\r
410 logBuffer.AppendLine(line);
\r
418 catch (Exception exc)
\r
421 Environment.NewLine + "Unable to read Log file..." + Environment.NewLine + exc +
\r
422 Environment.NewLine);
\r
428 /// Setup the logging.
\r
430 /// <param name="encodeQueueTask">
\r
431 /// The encode QueueTask.
\r
433 private void SetupLogging(QueueTask encodeQueueTask)
\r
435 string logDir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\HandBrake\\logs";
\r
436 string logFile = Path.Combine(logDir, string.Format("last_encode_log{0}.txt", Init.InstanceId));
\r
437 string logFile2 = Path.Combine(logDir, string.Format("tmp_appReadable_log{0}.txt", Init.InstanceId));
\r
441 logBuffer = new StringBuilder();
\r
443 // Clear the current Encode Logs
\r
444 if (File.Exists(logFile)) File.Delete(logFile);
\r
445 if (File.Exists(logFile2)) File.Delete(logFile2);
\r
447 fileWriter = new StreamWriter(logFile) { AutoFlush = true };
\r
449 fileWriter.WriteLine(Logging.CreateCliLogHeader(encodeQueueTask));
\r
450 logBuffer.AppendLine(Logging.CreateCliLogHeader(encodeQueueTask));
\r
454 if (fileWriter != null)
\r
456 fileWriter.Close();
\r
457 fileWriter.Dispose();
\r
464 /// Recieve the Standard Error information and process it
\r
466 /// <param name="sender">
\r
467 /// The Sender Object
\r
469 /// <param name="e">
\r
470 /// DataReceived EventArgs
\r
472 private void HbProcErrorDataReceived(object sender, DataReceivedEventArgs e)
\r
474 if (!String.IsNullOrEmpty(e.Data))
\r
479 logBuffer.AppendLine(e.Data);
\r
481 if (fileWriter != null && fileWriter.BaseStream.CanWrite)
\r
483 fileWriter.WriteLine(e.Data);
\r
485 // If the logging grows past 100MB, kill the encode and stop.
\r
486 if (fileWriter.BaseStream.Length > 100000000)
\r
488 this.Stop(new Exception("The encode has been stopped. The log file has grown to over 100MB which indicates a serious problem has occured with the encode." +
\r
489 "Please check the encode log for an indication of what the problem is."));
\r
493 catch (Exception exc)
\r
495 // errorService.ShowError("Unable to write log data...", exc.ToString());
\r
503 /// <param name="sender">
\r
506 /// <param name="e">
\r
509 private void EncodeEncodeStarted(object sender, EventArgs e)
\r
511 Thread monitor = new Thread(EncodeMonitor);
\r
516 /// Monitor the QueueTask
\r
518 private void EncodeMonitor()
\r
522 Parser encode = new Parser(HbProcess.StandardOutput.BaseStream);
\r
523 encode.OnEncodeProgress += EncodeOnEncodeProgress;
\r
524 while (!encode.EndOfStream)
\r
525 encode.ReadEncodeStatus();
\r
527 catch (Exception exc)
\r
529 EncodeOnEncodeProgress(null, 0, 0, 0, 0, 0, "Unknown, status not available..");
\r
534 /// Displays the Encode status in the GUI
\r
536 /// <param name="sender">The sender</param>
\r
537 /// <param name="currentTask">The current task</param>
\r
538 /// <param name="taskCount">Number of tasks</param>
\r
539 /// <param name="percentComplete">Percent complete</param>
\r
540 /// <param name="currentFps">Current encode speed in fps</param>
\r
541 /// <param name="avg">Avg encode speed</param>
\r
542 /// <param name="timeRemaining">Time Left</param>
\r
543 private void EncodeOnEncodeProgress(object sender, int currentTask, int taskCount, float percentComplete, float currentFps, float avg, string timeRemaining)
\r
545 EncodeProgressEventArgs eventArgs = new EncodeProgressEventArgs
\r
547 AverageFrameRate = avg,
\r
548 CurrentFrameRate = currentFps,
\r
549 EstimatedTimeLeft = Converters.EncodeToTimespan(timeRemaining),
\r
550 PercentComplete = percentComplete,
\r
551 Task = currentTask,
\r
552 TaskCount = taskCount
\r
555 if (this.EncodeStatusChanged != null)
\r
556 this.EncodeStatusChanged(this, eventArgs);
\r
558 if (windowsSeven.IsWindowsSeven)
\r
561 int.TryParse(Math.Round(percentComplete).ToString(), out percent);
\r
563 windowsSeven.SetTaskBarProgress(percent);
\r