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.Framework.Services;
\r
17 using HandBrake.Framework.Services.Interfaces;
\r
18 using HandBrake.ApplicationServices.Functions;
\r
19 using HandBrake.ApplicationServices.Model;
\r
20 using HandBrake.ApplicationServices.Parsing;
\r
21 using HandBrake.ApplicationServices.Services.Interfaces;
\r
24 /// Class which handles the CLI
\r
26 public class Encode : IEncode
\r
28 #region Private Variables
\r
31 /// The Error Service
\r
33 protected IErrorService errorService;
\r
38 private StringBuilder logBuffer;
\r
41 /// The Log file writer
\r
43 private StreamWriter fileWriter;
\r
46 /// Gets The Process Handle
\r
48 private IntPtr processHandle;
\r
51 /// Gets the Process ID
\r
53 private int processID;
\r
56 /// Windows 7 API Pack wrapper
\r
58 private Win7 windowsSeven = new Win7();
\r
65 /// Initializes a new instance of the <see cref="Encode"/> class.
\r
69 this.EncodeStarted += Encode_EncodeStarted;
\r
70 GrowlCommunicator.Register();
\r
72 this.errorService = new ErrorService();
\r
75 #region Delegates and Event Handlers
\r
78 /// Encode Progess Status
\r
80 /// <param name="sender">
\r
83 /// <param name="e">
\r
84 /// The EncodeProgressEventArgs.
\r
86 public delegate void EncodeProgessStatus(object sender, EncodeProgressEventArgs e);
\r
88 /* Event Handlers */
\r
91 /// Fires when a new CLI Job starts
\r
93 public event EventHandler EncodeStarted;
\r
96 /// Fires when a CLI job finishes.
\r
98 public event EventHandler EncodeEnded;
\r
101 /// Encode process has progressed
\r
103 public event EncodeProgessStatus EncodeStatusChanged;
\r
109 /// Gets or sets The HB Process
\r
111 protected Process HbProcess { get; set; }
\r
114 /// Gets a value indicating whether IsEncoding.
\r
116 public bool IsEncoding { get; private set; }
\r
119 /// Gets ActivityLog.
\r
121 public string ActivityLog
\r
125 if (this.IsEncoding == false)
\r
129 ReadFile(); // Read the last log file back in if it exists
\r
131 catch (Exception exc)
\r
133 return exc.ToString();
\r
137 return string.IsNullOrEmpty(this.logBuffer.ToString()) ? "No log data available..." : this.logBuffer.ToString();
\r
141 /* Public Methods */
\r
144 /// Create a preview sample video
\r
146 /// <param name="query">
\r
149 public void CreatePreviewSample(string query)
\r
151 this.Run(new Job { Query = query }, false);
\r
155 /// Execute a HandBrakeCLI process.
\r
157 /// <param name="encJob">
\r
160 /// <param name="enableLogging">
\r
161 /// Enable Logging. When Disabled we onlt parse Standard Ouput for progress info. Standard Error log data is ignored.
\r
163 protected void Run(Job encJob, bool enableLogging)
\r
170 SetupLogging(encJob);
\r
172 if (Init.PreventSleep)
\r
174 Win32.PreventSleep();
\r
177 string handbrakeCLIPath = Path.Combine(Application.StartupPath, "HandBrakeCLI.exe");
\r
178 ProcessStartInfo cliStart = new ProcessStartInfo(handbrakeCLIPath, encJob.Query)
\r
180 RedirectStandardOutput = true,
\r
181 RedirectStandardError = enableLogging ? true : false,
\r
182 UseShellExecute = false,
\r
183 CreateNoWindow = !Init.ShowCliForInGuiEncodeStatus ? true : false
\r
186 this.HbProcess = Process.Start(cliStart);
\r
190 this.HbProcess.ErrorDataReceived += HbProcErrorDataReceived;
\r
191 this.HbProcess.BeginErrorReadLine();
\r
194 this.processID = HbProcess.Id;
\r
195 this.processHandle = HbProcess.Handle;
\r
197 // Set the process Priority
\r
198 if (this.processID != -1)
\r
200 this.HbProcess.EnableRaisingEvents = true;
\r
201 this.HbProcess.Exited += HbProcess_Exited;
\r
204 // Set the Process Priority
\r
205 switch (Init.ProcessPriority)
\r
208 this.HbProcess.PriorityClass = ProcessPriorityClass.RealTime;
\r
211 this.HbProcess.PriorityClass = ProcessPriorityClass.High;
\r
213 case "Above Normal":
\r
214 this.HbProcess.PriorityClass = ProcessPriorityClass.AboveNormal;
\r
217 this.HbProcess.PriorityClass = ProcessPriorityClass.Normal;
\r
220 this.HbProcess.PriorityClass = ProcessPriorityClass.Idle;
\r
223 this.HbProcess.PriorityClass = ProcessPriorityClass.BelowNormal;
\r
227 // Fire the Encode Started Event
\r
228 if (this.EncodeStarted != null)
\r
229 this.EncodeStarted(this, new EventArgs());
\r
231 catch (Exception exc)
\r
233 errorService.ShowError("It would appear that HandBrakeCLI has not started correctly." +
\r
234 "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
240 /// Kill the CLI process
\r
246 if (this.HbProcess != null && !this.HbProcess.HasExited)
\r
248 this.HbProcess.Kill();
\r
251 catch (Exception exc)
\r
253 errorService.ShowError("Unable to stop HandBrakeCLI. It may not be running.", exc.ToString());
\r
256 if (this.EncodeEnded != null)
\r
257 this.EncodeEnded(this, new EventArgs());
\r
261 /// Attempt to Safely kill a DirectRun() CLI
\r
262 /// NOTE: This will not work with a MinGW CLI
\r
263 /// Note: http://www.cygwin.com/ml/cygwin/2006-03/msg00330.html
\r
265 public void SafelyClose()
\r
267 if ((int)this.processHandle == 0)
\r
270 // Allow the CLI to exit cleanly
\r
271 Win32.SetForegroundWindow((int)this.processHandle);
\r
272 SendKeys.Send("^C");
\r
275 /*/if (HbProcess != null)
\r
277 // HbProcess.StandardInput.AutoFlush = true;
\r
278 // HbProcess.StandardInput.WriteLine("^c^z");
\r
285 /// Save a copy of the log to the users desired location or a default location
\r
286 /// if this feature is enabled in options.
\r
288 /// <param name="destination">
\r
289 /// The Destination File Path
\r
291 protected void CopyLog(string destination)
\r
295 string logDir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) +
\r
296 "\\HandBrake\\logs";
\r
297 string tempLogFile = Path.Combine(logDir, string.Format("last_encode_log{0}.txt", Init.InstanceId));
\r
299 string encodeDestinationPath = Path.GetDirectoryName(destination);
\r
300 string destinationFile = Path.GetFileName(destination);
\r
301 string encodeLogFile = destinationFile + " " +
\r
302 DateTime.Now.ToString().Replace("/", "-").Replace(":", "-") + ".txt";
\r
304 // Make sure the log directory exists.
\r
305 if (!Directory.Exists(logDir))
\r
306 Directory.CreateDirectory(logDir);
\r
308 // Copy the Log to HandBrakes log folder in the users applciation data folder.
\r
309 File.Copy(tempLogFile, Path.Combine(logDir, encodeLogFile));
\r
311 // Save a copy of the log file in the same location as the enocde.
\r
312 if (Init.SaveLogWithVideo)
\r
313 File.Copy(tempLogFile, Path.Combine(encodeDestinationPath, encodeLogFile));
\r
315 // Save a copy of the log file to a user specified location
\r
316 if (Directory.Exists(Init.SaveLogPath))
\r
317 if (Init.SaveLogPath != String.Empty && Init.SaveLogToSpecifiedPath)
\r
318 File.Copy(tempLogFile, Path.Combine(Init.SaveLogPath, encodeLogFile));
\r
320 catch (Exception exc)
\r
322 errorService.ShowError("Unable to make a copy of the log file", exc.ToString());
\r
327 /// The HandBrakeCLI process has exited.
\r
329 /// <param name="sender">
\r
332 /// <param name="e">
\r
335 private void HbProcess_Exited(object sender, EventArgs e)
\r
337 IsEncoding = false;
\r
338 if (this.EncodeEnded != null)
\r
339 this.EncodeEnded(this, new EventArgs());
\r
341 if (windowsSeven.IsWindowsSeven)
\r
343 windowsSeven.SetTaskBarProgressToNoProgress();
\r
346 if (Init.PreventSleep)
\r
348 Win32.AllowSleep();
\r
353 if (fileWriter != null)
\r
355 fileWriter.Close();
\r
356 fileWriter.Dispose();
\r
359 catch (Exception exc)
\r
361 errorService.ShowError("Unable to close the log file wrtier", exc.ToString());
\r
366 /// Read the log file
\r
368 private void ReadFile()
\r
370 logBuffer = new StringBuilder();
\r
373 // 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
374 // we'll need to make a copy of it.
\r
375 string logDir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\HandBrake\\logs";
\r
376 string logFile = Path.Combine(logDir, string.Format("last_encode_log{0}.txt", Init.InstanceId));
\r
377 string logFile2 = Path.Combine(logDir, string.Format("tmp_appReadable_log{0}.txt", Init.InstanceId));
\r
378 int logFilePosition = 0;
\r
382 // Copy the log file.
\r
383 if (File.Exists(logFile))
\r
384 File.Copy(logFile, logFile2, true);
\r
388 // Start the Reader
\r
389 // Only use text which continues on from the last read line
\r
390 using (StreamReader sr = new StreamReader(logFile2))
\r
394 while ((line = sr.ReadLine()) != null)
\r
396 if (i > logFilePosition)
\r
398 logBuffer.AppendLine(line);
\r
406 catch (Exception exc)
\r
408 throw new Exception("Unable to read log file" + Environment.NewLine + exc);
\r
414 /// Setup the logging.
\r
416 /// <param name="encodeJob">
\r
417 /// The encode Job.
\r
419 private void SetupLogging(Job encodeJob)
\r
421 string logDir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\HandBrake\\logs";
\r
422 string logFile = Path.Combine(logDir, string.Format("last_encode_log{0}.txt", Init.InstanceId));
\r
423 string logFile2 = Path.Combine(logDir, string.Format("tmp_appReadable_log{0}.txt", Init.InstanceId));
\r
427 logBuffer = new StringBuilder();
\r
429 // Clear the current Encode Logs
\r
430 if (File.Exists(logFile)) File.Delete(logFile);
\r
431 if (File.Exists(logFile2)) File.Delete(logFile2);
\r
433 fileWriter = new StreamWriter(logFile) { AutoFlush = true };
\r
435 fileWriter.WriteLine(Logging.CreateCliLogHeader(encodeJob));
\r
436 logBuffer.AppendLine(Logging.CreateCliLogHeader(encodeJob));
\r
438 catch (Exception exc)
\r
440 if (fileWriter != null)
\r
442 fileWriter.Close();
\r
443 fileWriter.Dispose();
\r
446 errorService.ShowError("Error", exc.ToString());
\r
451 /// Recieve the Standard Error information and process it
\r
453 /// <param name="sender">
\r
454 /// The Sender Object
\r
456 /// <param name="e">
\r
457 /// DataReceived EventArgs
\r
459 private void HbProcErrorDataReceived(object sender, DataReceivedEventArgs e)
\r
461 if (!String.IsNullOrEmpty(e.Data))
\r
466 logBuffer.AppendLine(e.Data);
\r
468 if (fileWriter != null && fileWriter.BaseStream.CanWrite)
\r
470 fileWriter.WriteLine(e.Data);
\r
472 // If the logging grows past 100MB, kill the encode and stop.
\r
473 if (fileWriter.BaseStream.Length > 100000000)
\r
476 errorService.ShowError("The encode has been stopped. The log file has grown to over 100MB which indicates a serious problem has occured with the encode.",
\r
477 "Please check the encode log for an indication of what the problem is.");
\r
481 catch (Exception exc)
\r
483 // errorService.ShowError("Unable to write log data...", exc.ToString());
\r
488 #region Encode Status from Standard Output
\r
493 /// <param name="sender">
\r
496 /// <param name="e">
\r
499 private void Encode_EncodeStarted(object sender, EventArgs e)
\r
501 Thread monitor = new Thread(EncodeMonitor);
\r
506 /// Monitor the Job
\r
508 private void EncodeMonitor()
\r
512 Parser encode = new Parser(HbProcess.StandardOutput.BaseStream);
\r
513 encode.OnEncodeProgress += EncodeOnEncodeProgress;
\r
514 while (!encode.EndOfStream)
\r
515 encode.ReadEncodeStatus();
\r
517 catch (Exception exc)
\r
519 EncodeOnEncodeProgress(null, 0, 0, 0, 0, 0, "Unknown, status not available..");
\r
524 /// Displays the Encode status in the GUI
\r
526 /// <param name="sender">The sender</param>
\r
527 /// <param name="currentTask">The current task</param>
\r
528 /// <param name="taskCount">Number of tasks</param>
\r
529 /// <param name="percentComplete">Percent complete</param>
\r
530 /// <param name="currentFps">Current encode speed in fps</param>
\r
531 /// <param name="avg">Avg encode speed</param>
\r
532 /// <param name="timeRemaining">Time Left</param>
\r
533 private void EncodeOnEncodeProgress(object sender, int currentTask, int taskCount, float percentComplete, float currentFps, float avg, string timeRemaining)
\r
535 EncodeProgressEventArgs eventArgs = new EncodeProgressEventArgs
\r
537 AverageFrameRate = avg,
\r
538 CurrentFrameRate = currentFps,
\r
539 EstimatedTimeLeft = Converters.EncodeToTimespan(timeRemaining),
\r
540 PercentComplete = percentComplete,
\r
541 Task = currentTask,
\r
542 TaskCount = taskCount
\r
545 if (this.EncodeStatusChanged != null)
\r
546 this.EncodeStatusChanged(this, eventArgs);
\r
548 if (windowsSeven.IsWindowsSeven)
\r
551 int.TryParse(Math.Round(percentComplete).ToString(), out percent);
\r
553 windowsSeven.SetTaskBarProgress(percent);
\r