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.ComponentModel;
\r
10 using System.Diagnostics;
\r
13 using System.Threading;
\r
14 using System.Windows.Forms;
\r
16 using HandBrake.ApplicationServices.EventArgs;
\r
17 using HandBrake.ApplicationServices.Functions;
\r
18 using HandBrake.ApplicationServices.Model;
\r
19 using HandBrake.ApplicationServices.Parsing;
\r
20 using HandBrake.ApplicationServices.Services.Interfaces;
\r
21 using HandBrake.ApplicationServices.Utilities;
\r
24 /// Class which handles the CLI
\r
26 public class Encode : IEncode
\r
28 #region Private Variables
\r
33 private StringBuilder logBuffer;
\r
36 /// The Log file writer
\r
38 private StreamWriter fileWriter;
\r
41 /// Gets The Process Handle
\r
43 private IntPtr processHandle;
\r
46 /// Gets the Process ID
\r
48 private int processId;
\r
51 /// Windows 7 API Pack wrapper
\r
53 private Win7 windowsSeven = new Win7();
\r
56 /// A Lock for the filewriter
\r
58 static readonly object fileWriterLock = new object();
\r
63 /// Initializes a new instance of the <see cref="Encode"/> class.
\r
67 this.EncodeStarted += this.EncodeEncodeStarted;
\r
68 GrowlCommunicator.Register();
\r
71 #region Delegates and Event Handlers
\r
74 /// Fires when a new CLI QueueTask starts
\r
76 public event EventHandler EncodeStarted;
\r
79 /// Fires when a CLI QueueTask finishes.
\r
81 public event EncodeCompletedStatus EncodeCompleted;
\r
84 /// Encode process has progressed
\r
86 public event EncodeProgessStatus EncodeStatusChanged;
\r
92 /// Gets or sets The HB Process
\r
94 protected Process HbProcess { get; set; }
\r
97 /// Gets a value indicating whether IsEncoding.
\r
99 public bool IsEncoding { get; private set; }
\r
102 /// Gets ActivityLog.
\r
104 public string ActivityLog
\r
108 if (this.IsEncoding == false)
\r
112 ReadFile(); // Read the last log file back in if it exists
\r
114 catch (Exception exc)
\r
116 return exc.ToString();
\r
120 return string.IsNullOrEmpty(this.logBuffer.ToString()) ? "No log data available..." : this.logBuffer.ToString();
\r
126 #region Public Methods
\r
129 /// Execute a HandBrakeCLI process.
\r
131 /// <param name="encodeQueueTask">
\r
132 /// The encodeQueueTask.
\r
134 /// <param name="enableLogging">
\r
135 /// Enable Logging. When Disabled we onlt parse Standard Ouput for progress info. Standard Error log data is ignored.
\r
137 public void Start(QueueTask encodeQueueTask, bool enableLogging)
\r
141 QueueTask queueTask = encodeQueueTask;
\r
143 if (queueTask == null)
\r
145 throw new ArgumentNullException("QueueTask was null");
\r
150 throw new Exception("HandBrake is already encodeing.");
\r
159 SetupLogging(queueTask);
\r
163 IsEncoding = false;
\r
168 if (Init.PreventSleep)
\r
170 Win32.PreventSleep();
\r
173 string handbrakeCLIPath = Path.Combine(Application.StartupPath, "HandBrakeCLI.exe");
\r
174 ProcessStartInfo cliStart = new ProcessStartInfo(handbrakeCLIPath, queueTask.Query)
\r
176 RedirectStandardOutput = true,
\r
177 RedirectStandardError = enableLogging ? true : false,
\r
178 UseShellExecute = false,
\r
179 CreateNoWindow = !Init.ShowCliForInGuiEncodeStatus ? true : false
\r
182 this.HbProcess = new Process { StartInfo = cliStart };
\r
184 this.HbProcess.Start();
\r
188 this.HbProcess.ErrorDataReceived += HbProcErrorDataReceived;
\r
189 this.HbProcess.BeginErrorReadLine();
\r
192 this.processId = HbProcess.Id;
\r
193 this.processHandle = HbProcess.Handle;
\r
195 // Set the process Priority
\r
196 if (this.processId != -1)
\r
198 this.HbProcess.EnableRaisingEvents = true;
\r
199 this.HbProcess.Exited += this.HbProcessExited;
\r
202 // Set the Process Priority
\r
203 switch (Init.ProcessPriority)
\r
206 this.HbProcess.PriorityClass = ProcessPriorityClass.RealTime;
\r
209 this.HbProcess.PriorityClass = ProcessPriorityClass.High;
\r
211 case "Above Normal":
\r
212 this.HbProcess.PriorityClass = ProcessPriorityClass.AboveNormal;
\r
215 this.HbProcess.PriorityClass = ProcessPriorityClass.Normal;
\r
218 this.HbProcess.PriorityClass = ProcessPriorityClass.Idle;
\r
221 this.HbProcess.PriorityClass = ProcessPriorityClass.BelowNormal;
\r
225 // Fire the Encode Started Event
\r
226 if (this.EncodeStarted != null)
\r
227 this.EncodeStarted(this, new EventArgs());
\r
229 catch (Exception exc)
\r
231 if (this.EncodeCompleted != null)
\r
232 this.EncodeCompleted(this, new EncodeCompletedEventArgs(false, exc, "An Error has occured in EncodeService.Run()"));
\r
237 /// Stop the Encode
\r
245 /// Kill the CLI process
\r
247 /// <param name="exc">
\r
248 /// The Exception that has occured.
\r
249 /// This will get bubbled up through the EncodeCompletedEventArgs
\r
251 public void Stop(Exception exc)
\r
255 if (this.HbProcess != null && !this.HbProcess.HasExited)
\r
257 this.HbProcess.Kill();
\r
262 // No need to report anything to the user. If it fails, it's probably already stopped.
\r
268 if (this.EncodeCompleted != null)
\r
269 this.EncodeCompleted(this, new EncodeCompletedEventArgs(true, null, string.Empty));
\r
273 if (this.EncodeCompleted != null)
\r
274 this.EncodeCompleted(this, new EncodeCompletedEventArgs(false, exc, "An Error has occured."));
\r
279 /// Attempt to Safely kill a DirectRun() CLI
\r
280 /// NOTE: This will not work with a MinGW CLI
\r
281 /// Note: http://www.cygwin.com/ml/cygwin/2006-03/msg00330.html
\r
283 public void SafelyStop()
\r
285 if ((int)this.processHandle == 0)
\r
288 // Allow the CLI to exit cleanly
\r
289 Win32.SetForegroundWindow((int)this.processHandle);
\r
290 SendKeys.Send("^C");
\r
293 /*/if (HbProcess != null)
\r
295 // HbProcess.StandardInput.AutoFlush = true;
\r
296 // HbProcess.StandardInput.WriteLine("^c^z");
\r
301 /// Save a copy of the log to the users desired location or a default location
\r
302 /// if this feature is enabled in options.
\r
304 /// <param name="destination">
\r
305 /// The Destination File Path
\r
307 public void ProcessLogs(string destination)
\r
311 string logDir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) +
\r
312 "\\HandBrake\\logs";
\r
313 string tempLogFile = Path.Combine(logDir, string.Format("last_encode_log{0}.txt", Init.InstanceId));
\r
315 string encodeDestinationPath = Path.GetDirectoryName(destination);
\r
316 string destinationFile = Path.GetFileName(destination);
\r
317 string encodeLogFile = destinationFile + " " +
\r
318 DateTime.Now.ToString().Replace("/", "-").Replace(":", "-") + ".txt";
\r
320 // Make sure the log directory exists.
\r
321 if (!Directory.Exists(logDir))
\r
322 Directory.CreateDirectory(logDir);
\r
324 // Copy the Log to HandBrakes log folder in the users applciation data folder.
\r
325 File.Copy(tempLogFile, Path.Combine(logDir, encodeLogFile));
\r
327 // Save a copy of the log file in the same location as the enocde.
\r
328 if (Init.SaveLogWithVideo)
\r
329 File.Copy(tempLogFile, Path.Combine(encodeDestinationPath, encodeLogFile));
\r
331 // Save a copy of the log file to a user specified location
\r
332 if (Directory.Exists(Init.SaveLogPath))
\r
333 if (Init.SaveLogPath != String.Empty && Init.SaveLogToSpecifiedPath)
\r
334 File.Copy(tempLogFile, Path.Combine(Init.SaveLogPath, encodeLogFile));
\r
336 catch (Exception exc)
\r
338 // This exception doesn't warrent user interaction, but it should be logged (TODO)
\r
344 #region Private Helper Methods
\r
347 /// The HandBrakeCLI process has exited.
\r
349 /// <param name="sender">
\r
352 /// <param name="e">
\r
355 private void HbProcessExited(object sender, EventArgs e)
\r
357 IsEncoding = false;
\r
358 if (windowsSeven.IsWindowsSeven)
\r
360 windowsSeven.SetTaskBarProgressToNoProgress();
\r
363 if (Init.PreventSleep)
\r
365 Win32.AllowSleep();
\r
370 lock (fileWriterLock)
\r
372 // This is just a quick hack to ensure that we are done processing the logging data.
\r
373 // Logging data comes in after the exit event has processed sometimes. We should really impliment ISyncronizingInvoke
\r
374 // and set the SyncObject on the process. I think this may resolve this properly.
\r
375 // For now, just wait 2.5 seconds to let any trailing log messages come in and be processed.
\r
376 Thread.Sleep(2500);
\r
378 this.HbProcess.CancelErrorRead();
\r
380 if (fileWriter != null)
\r
382 fileWriter.Close();
\r
383 fileWriter.Dispose();
\r
389 catch (Exception exc)
\r
391 // This exception doesn't warrent user interaction, but it should be logged (TODO)
\r
394 if (this.EncodeCompleted != null)
\r
395 this.EncodeCompleted(this, new EncodeCompletedEventArgs(true, null, string.Empty));
\r
399 /// Read the log file
\r
401 private void ReadFile()
\r
403 logBuffer = new StringBuilder();
\r
406 // 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
407 // we'll need to make a copy of it.
\r
408 string logDir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\HandBrake\\logs";
\r
409 string logFile = Path.Combine(logDir, string.Format("last_encode_log{0}.txt", Init.InstanceId));
\r
410 string logFile2 = Path.Combine(logDir, string.Format("tmp_appReadable_log{0}.txt", Init.InstanceId));
\r
411 int logFilePosition = 0;
\r
415 // Copy the log file.
\r
416 if (File.Exists(logFile))
\r
417 File.Copy(logFile, logFile2, true);
\r
421 // Start the Reader
\r
422 // Only use text which continues on from the last read line
\r
423 using (StreamReader sr = new StreamReader(logFile2))
\r
427 while ((line = sr.ReadLine()) != null)
\r
429 if (i > logFilePosition)
\r
431 logBuffer.AppendLine(line);
\r
439 catch (Exception exc)
\r
442 Environment.NewLine + "Unable to read Log file..." + Environment.NewLine + exc +
\r
443 Environment.NewLine);
\r
449 /// Setup the logging.
\r
451 /// <param name="encodeQueueTask">
\r
452 /// The encode QueueTask.
\r
454 private void SetupLogging(QueueTask encodeQueueTask)
\r
456 string logDir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\HandBrake\\logs";
\r
457 string logFile = Path.Combine(logDir, string.Format("last_encode_log{0}.txt", Init.InstanceId));
\r
458 string logFile2 = Path.Combine(logDir, string.Format("tmp_appReadable_log{0}.txt", Init.InstanceId));
\r
462 logBuffer = new StringBuilder();
\r
464 // Clear the current Encode Logs
\r
465 if (File.Exists(logFile)) File.Delete(logFile);
\r
466 if (File.Exists(logFile2)) File.Delete(logFile2);
\r
468 fileWriter = new StreamWriter(logFile) { AutoFlush = true };
\r
470 fileWriter.WriteLine(UtilityService.CreateCliLogHeader(encodeQueueTask));
\r
471 logBuffer.AppendLine(UtilityService.CreateCliLogHeader(encodeQueueTask));
\r
475 if (fileWriter != null)
\r
477 fileWriter.Close();
\r
478 fileWriter.Dispose();
\r
485 /// Recieve the Standard Error information and process it
\r
487 /// <param name="sender">
\r
488 /// The Sender Object
\r
490 /// <param name="e">
\r
491 /// DataReceived EventArgs
\r
493 private void HbProcErrorDataReceived(object sender, DataReceivedEventArgs e)
\r
495 if (!String.IsNullOrEmpty(e.Data))
\r
500 logBuffer.AppendLine(e.Data);
\r
502 lock (fileWriterLock)
\r
504 if (fileWriter != null && fileWriter.BaseStream.CanWrite)
\r
506 fileWriter.WriteLine(e.Data);
\r
508 // If the logging grows past 100MB, kill the encode and stop.
\r
509 if (fileWriter.BaseStream.Length > 100000000)
\r
513 "The encode has been stopped. The log file has grown to over 100MB which indicates a serious problem has occured with the encode." +
\r
514 "Please check the encode log for an indication of what the problem is."));
\r
519 catch (Exception exc)
\r
529 /// <param name="sender">
\r
532 /// <param name="e">
\r
535 private void EncodeEncodeStarted(object sender, EventArgs e)
\r
537 Thread monitor = new Thread(EncodeMonitor);
\r
542 /// Monitor the QueueTask
\r
544 private void EncodeMonitor()
\r
548 Parser encode = new Parser(HbProcess.StandardOutput.BaseStream);
\r
549 encode.OnEncodeProgress += EncodeOnEncodeProgress;
\r
550 while (!encode.EndOfStream)
\r
551 encode.ReadEncodeStatus();
\r
553 catch (Exception exc)
\r
555 EncodeOnEncodeProgress(null, 0, 0, 0, 0, 0, "Unknown, status not available..");
\r
560 /// Displays the Encode status in the GUI
\r
562 /// <param name="sender">The sender</param>
\r
563 /// <param name="currentTask">The current task</param>
\r
564 /// <param name="taskCount">Number of tasks</param>
\r
565 /// <param name="percentComplete">Percent complete</param>
\r
566 /// <param name="currentFps">Current encode speed in fps</param>
\r
567 /// <param name="avg">Avg encode speed</param>
\r
568 /// <param name="timeRemaining">Time Left</param>
\r
569 private void EncodeOnEncodeProgress(object sender, int currentTask, int taskCount, float percentComplete, float currentFps, float avg, string timeRemaining)
\r
571 EncodeProgressEventArgs eventArgs = new EncodeProgressEventArgs
\r
573 AverageFrameRate = avg,
\r
574 CurrentFrameRate = currentFps,
\r
575 EstimatedTimeLeft = Converters.EncodeToTimespan(timeRemaining),
\r
576 PercentComplete = percentComplete,
\r
577 Task = currentTask,
\r
578 TaskCount = taskCount
\r
581 if (this.EncodeStatusChanged != null)
\r
582 this.EncodeStatusChanged(this, eventArgs);
\r
584 if (windowsSeven.IsWindowsSeven)
\r
587 int.TryParse(Math.Round(percentComplete).ToString(), out percent);
\r
589 windowsSeven.SetTaskBarProgress(percent);
\r