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
29 /// The Error Service
\r
31 protected IErrorService errorService;
\r
36 private StringBuilder logBuffer;
\r
39 /// The Log file writer
\r
41 private StreamWriter fileWriter;
\r
44 /// Gets The Process Handle
\r
46 private IntPtr processHandle;
\r
49 /// Gets the Process ID
\r
51 private int processID;
\r
54 /// Windows 7 API Pack wrapper
\r
56 private Win7 windowsSeven = new Win7();
\r
63 /// Initializes a new instance of the <see cref="Encode"/> class.
\r
67 this.EncodeStarted += Encode_EncodeStarted;
\r
68 GrowlCommunicator.Register();
\r
70 this.errorService = new ErrorService();
\r
73 #region Delegates and Event Handlers
\r
76 /// Encode Progess Status
\r
78 /// <param name="sender">
\r
81 /// <param name="e">
\r
82 /// The EncodeProgressEventArgs.
\r
84 public delegate void EncodeProgessStatus(object sender, EncodeProgressEventArgs e);
\r
86 /* Event Handlers */
\r
89 /// Fires when a new CLI Job starts
\r
91 public event EventHandler EncodeStarted;
\r
94 /// Fires when a CLI job finishes.
\r
96 public event EventHandler EncodeEnded;
\r
99 /// Encode process has progressed
\r
101 public event EncodeProgessStatus EncodeStatusChanged;
\r
107 /// Gets or sets The HB Process
\r
109 protected Process HbProcess { get; set; }
\r
112 /// Gets a value indicating whether IsEncoding.
\r
114 public bool IsEncoding { get; private set; }
\r
117 /// Gets ActivityLog.
\r
119 public string ActivityLog
\r
123 if (this.IsEncoding == false)
\r
127 ReadFile(); // Read the last log file back in if it exists
\r
129 catch (Exception exc)
\r
131 return exc.ToString();
\r
135 return string.IsNullOrEmpty(this.logBuffer.ToString()) ? "No log data available..." : this.logBuffer.ToString();
\r
139 /* Public Methods */
\r
142 /// Create a preview sample video
\r
144 /// <param name="query">
\r
147 public void CreatePreviewSample(string query)
\r
149 this.Run(new Job { Query = query }, false);
\r
153 /// Execute a HandBrakeCLI process.
\r
155 /// <param name="encJob">
\r
158 /// <param name="enableLogging">
\r
159 /// Enable Logging. When Disabled we onlt parse Standard Ouput for progress info. Standard Error log data is ignored.
\r
161 protected void Run(Job encJob, bool enableLogging)
\r
168 SetupLogging(encJob);
\r
170 if (Init.PreventSleep)
\r
172 Win32.PreventSleep();
\r
175 string handbrakeCLIPath = Path.Combine(Application.StartupPath, "HandBrakeCLI.exe");
\r
176 ProcessStartInfo cliStart = new ProcessStartInfo(handbrakeCLIPath, encJob.Query)
\r
178 RedirectStandardOutput = true,
\r
179 RedirectStandardError = enableLogging ? true : false,
\r
180 UseShellExecute = false,
\r
181 CreateNoWindow = !Init.ShowCliForInGuiEncodeStatus ? true : false
\r
184 this.HbProcess = Process.Start(cliStart);
\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 += HbProcess_Exited;
\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 errorService.ShowError("It would appear that HandBrakeCLI has not started correctly." +
\r
232 "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
238 /// Kill the CLI process
\r
244 if (this.HbProcess != null) this.HbProcess.Kill();
\r
246 catch (Exception exc)
\r
248 errorService.ShowError("Unable to stop HandBrakeCLI. It may not be running.", exc.ToString());
\r
251 if (this.EncodeEnded != null)
\r
252 this.EncodeEnded(this, new EventArgs());
\r
256 /// Attempt to Safely kill a DirectRun() CLI
\r
257 /// NOTE: This will not work with a MinGW CLI
\r
258 /// Note: http://www.cygwin.com/ml/cygwin/2006-03/msg00330.html
\r
260 public void SafelyClose()
\r
262 if ((int)this.processHandle == 0)
\r
265 // Allow the CLI to exit cleanly
\r
266 Win32.SetForegroundWindow((int)this.processHandle);
\r
267 SendKeys.Send("^C");
\r
270 /*/if (HbProcess != null)
\r
272 // HbProcess.StandardInput.AutoFlush = true;
\r
273 // HbProcess.StandardInput.WriteLine("^c^z");
\r
280 /// Save a copy of the log to the users desired location or a default location
\r
281 /// if this feature is enabled in options.
\r
283 /// <param name="destination">
\r
284 /// The Destination File Path
\r
286 protected void CopyLog(string destination)
\r
290 string logDir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) +
\r
291 "\\HandBrake\\logs";
\r
292 string tempLogFile = Path.Combine(logDir, string.Format("last_encode_log{0}.txt", Init.InstanceId));
\r
294 string encodeDestinationPath = Path.GetDirectoryName(destination);
\r
295 string destinationFile = Path.GetFileName(destination);
\r
296 string encodeLogFile = destinationFile + " " +
\r
297 DateTime.Now.ToString().Replace("/", "-").Replace(":", "-") + ".txt";
\r
299 // Make sure the log directory exists.
\r
300 if (!Directory.Exists(logDir))
\r
301 Directory.CreateDirectory(logDir);
\r
303 // Copy the Log to HandBrakes log folder in the users applciation data folder.
\r
304 File.Copy(tempLogFile, Path.Combine(logDir, encodeLogFile));
\r
306 // Save a copy of the log file in the same location as the enocde.
\r
307 if (Init.SaveLogWithVideo)
\r
308 File.Copy(tempLogFile, Path.Combine(encodeDestinationPath, encodeLogFile));
\r
310 // Save a copy of the log file to a user specified location
\r
311 if (Directory.Exists(Init.SaveLogPath))
\r
312 if (Init.SaveLogPath != String.Empty && Init.SaveLogToSpecifiedPath)
\r
313 File.Copy(tempLogFile, Path.Combine(Init.SaveLogPath, encodeLogFile));
\r
315 catch (Exception exc)
\r
317 errorService.ShowError("Unable to make a copy of the log file", exc.ToString());
\r
322 /// The HandBrakeCLI process has exited.
\r
324 /// <param name="sender">
\r
327 /// <param name="e">
\r
330 private void HbProcess_Exited(object sender, EventArgs e)
\r
332 IsEncoding = false;
\r
333 if (this.EncodeEnded != null)
\r
334 this.EncodeEnded(this, new EventArgs());
\r
336 if (windowsSeven.IsWindowsSeven)
\r
338 windowsSeven.SetTaskBarProgressToNoProgress();
\r
341 if (Init.PreventSleep)
\r
343 Win32.AllowSleep();
\r
348 if (fileWriter != null)
\r
350 fileWriter.Close();
\r
351 fileWriter.Dispose();
\r
354 catch (Exception exc)
\r
356 errorService.ShowError("Unable to close the log file wrtier", exc.ToString());
\r
361 /// Read the log file
\r
363 private void ReadFile()
\r
365 logBuffer = new StringBuilder();
\r
368 // 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
369 // we'll need to make a copy of it.
\r
370 string logDir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\HandBrake\\logs";
\r
371 string logFile = Path.Combine(logDir, string.Format("last_encode_log{0}.txt", Init.InstanceId));
\r
372 string logFile2 = Path.Combine(logDir, string.Format("tmp_appReadable_log{0}.txt", Init.InstanceId));
\r
373 int logFilePosition = 0;
\r
377 // Copy the log file.
\r
378 if (File.Exists(logFile))
\r
379 File.Copy(logFile, logFile2, true);
\r
383 // Start the Reader
\r
384 // Only use text which continues on from the last read line
\r
385 using (StreamReader sr = new StreamReader(logFile2))
\r
389 while ((line = sr.ReadLine()) != null)
\r
391 if (i > logFilePosition)
\r
393 logBuffer.AppendLine(line);
\r
401 catch (Exception exc)
\r
403 throw new Exception("Unable to read log file" + Environment.NewLine + exc);
\r
409 /// Setup the logging.
\r
411 /// <param name="encodeJob">
\r
412 /// The encode Job.
\r
414 private void SetupLogging(Job encodeJob)
\r
416 string logDir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\HandBrake\\logs";
\r
417 string logFile = Path.Combine(logDir, string.Format("last_encode_log{0}.txt", Init.InstanceId));
\r
418 string logFile2 = Path.Combine(logDir, string.Format("tmp_appReadable_log{0}.txt", Init.InstanceId));
\r
422 logBuffer = new StringBuilder();
\r
424 // Clear the current Encode Logs
\r
425 if (File.Exists(logFile)) File.Delete(logFile);
\r
426 if (File.Exists(logFile2)) File.Delete(logFile2);
\r
428 fileWriter = new StreamWriter(logFile) { AutoFlush = true };
\r
430 fileWriter.WriteLine(Logging.CreateCliLogHeader(encodeJob));
\r
431 logBuffer.AppendLine(Logging.CreateCliLogHeader(encodeJob));
\r
433 catch (Exception exc)
\r
435 if (fileWriter != null)
\r
437 fileWriter.Close();
\r
438 fileWriter.Dispose();
\r
441 errorService.ShowError("Error", exc.ToString());
\r
446 /// Recieve the Standard Error information and process it
\r
448 /// <param name="sender">
\r
449 /// The Sender Object
\r
451 /// <param name="e">
\r
452 /// DataReceived EventArgs
\r
454 private void HbProcErrorDataReceived(object sender, DataReceivedEventArgs e)
\r
456 if (!String.IsNullOrEmpty(e.Data))
\r
459 logBuffer.AppendLine(e.Data);
\r
463 if (fileWriter != null && fileWriter.BaseStream.CanWrite)
\r
465 fileWriter.WriteLine(e.Data);
\r
468 catch (Exception exc)
\r
470 // errorService.ShowError("Unable to write log data...", exc.ToString());
\r
475 #region Encode Status from Standard Output
\r
480 /// <param name="sender">
\r
483 /// <param name="e">
\r
486 private void Encode_EncodeStarted(object sender, EventArgs e)
\r
488 Thread monitor = new Thread(EncodeMonitor);
\r
493 /// Monitor the Job
\r
495 private void EncodeMonitor()
\r
499 Parser encode = new Parser(HbProcess.StandardOutput.BaseStream);
\r
500 encode.OnEncodeProgress += EncodeOnEncodeProgress;
\r
501 while (!encode.EndOfStream)
\r
502 encode.ReadEncodeStatus();
\r
504 catch (Exception exc)
\r
506 EncodeOnEncodeProgress(null, 0, 0, 0, 0, 0, "Unknown, status not available..");
\r
511 /// Displays the Encode status in the GUI
\r
513 /// <param name="sender">The sender</param>
\r
514 /// <param name="currentTask">The current task</param>
\r
515 /// <param name="taskCount">Number of tasks</param>
\r
516 /// <param name="percentComplete">Percent complete</param>
\r
517 /// <param name="currentFps">Current encode speed in fps</param>
\r
518 /// <param name="avg">Avg encode speed</param>
\r
519 /// <param name="timeRemaining">Time Left</param>
\r
520 private void EncodeOnEncodeProgress(object sender, int currentTask, int taskCount, float percentComplete, float currentFps, float avg, string timeRemaining)
\r
522 EncodeProgressEventArgs eventArgs = new EncodeProgressEventArgs
\r
524 AverageFrameRate = avg,
\r
525 CurrentFrameRate = currentFps,
\r
526 EstimatedTimeLeft = timeRemaining,
\r
527 PercentComplete = percentComplete,
\r
528 Task = currentTask,
\r
529 TaskCount = taskCount
\r
532 if (this.EncodeStatusChanged != null)
\r
533 this.EncodeStatusChanged(this, eventArgs);
\r
535 if (windowsSeven.IsWindowsSeven)
\r
538 int.TryParse(Math.Round(percentComplete).ToString(), out percent);
\r
540 windowsSeven.SetTaskBarProgress(percent);
\r