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.Framework.Services;
\r
16 using HandBrake.Framework.Services.Interfaces;
\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
23 /// Class which handles the CLI
\r
25 public class Encode : IEncode
\r
27 #region Private Variables
\r
30 /// The Error Service
\r
32 protected IErrorService errorService;
\r
37 private StringBuilder logBuffer;
\r
40 /// The Log file writer
\r
42 private StreamWriter fileWriter;
\r
45 /// Gets The Process Handle
\r
47 private IntPtr processHandle;
\r
50 /// Gets the Process ID
\r
52 private int processID;
\r
55 /// Windows 7 API Pack wrapper
\r
57 private Win7 windowsSeven = new Win7();
\r
64 /// Initializes a new instance of the <see cref="Encode"/> class.
\r
68 this.EncodeStarted += Encode_EncodeStarted;
\r
69 GrowlCommunicator.Register();
\r
71 this.errorService = new ErrorService();
\r
74 #region Delegates and Event Handlers
\r
77 /// Encode Progess Status
\r
79 /// <param name="sender">
\r
82 /// <param name="e">
\r
83 /// The EncodeProgressEventArgs.
\r
85 public delegate void EncodeProgessStatus(object sender, EncodeProgressEventArgs e);
\r
87 /* Event Handlers */
\r
90 /// Fires when a new CLI Job starts
\r
92 public event EventHandler EncodeStarted;
\r
95 /// Fires when a CLI job finishes.
\r
97 public event EventHandler EncodeEnded;
\r
100 /// Encode process has progressed
\r
102 public event EncodeProgessStatus EncodeStatusChanged;
\r
108 /// Gets or sets The HB Process
\r
110 protected Process HbProcess { get; set; }
\r
113 /// Gets a value indicating whether IsEncoding.
\r
115 public bool IsEncoding { get; private set; }
\r
118 /// Gets ActivityLog.
\r
120 public string ActivityLog
\r
124 if (this.IsEncoding == false)
\r
128 ReadFile(); // Read the last log file back in if it exists
\r
130 catch (Exception exc)
\r
132 return exc.ToString();
\r
136 return string.IsNullOrEmpty(this.logBuffer.ToString()) ? "No log data available..." : this.logBuffer.ToString();
\r
140 /* Public Methods */
\r
143 /// Create a preview sample video
\r
145 /// <param name="query">
\r
148 public void CreatePreviewSample(string query)
\r
150 this.Run(new Job { Query = query }, false);
\r
154 /// Execute a HandBrakeCLI process.
\r
156 /// <param name="encJob">
\r
159 /// <param name="enableLogging">
\r
160 /// Enable Logging. When Disabled we onlt parse Standard Ouput for progress info. Standard Error log data is ignored.
\r
162 protected void Run(Job encJob, bool enableLogging)
\r
169 SetupLogging(encJob);
\r
171 if (Init.PreventSleep)
\r
173 Win32.PreventSleep();
\r
176 string handbrakeCLIPath = Path.Combine(Application.StartupPath, "HandBrakeCLI.exe");
\r
177 ProcessStartInfo cliStart = new ProcessStartInfo(handbrakeCLIPath, encJob.Query)
\r
179 RedirectStandardOutput = true,
\r
180 RedirectStandardError = enableLogging ? true : false,
\r
181 UseShellExecute = false,
\r
182 CreateNoWindow = !Init.ShowCliForInGuiEncodeStatus ? true : false
\r
185 this.HbProcess = Process.Start(cliStart);
\r
189 this.HbProcess.ErrorDataReceived += HbProcErrorDataReceived;
\r
190 this.HbProcess.BeginErrorReadLine();
\r
193 this.processID = HbProcess.Id;
\r
194 this.processHandle = HbProcess.Handle;
\r
196 // Set the process Priority
\r
197 if (this.processID != -1)
\r
199 this.HbProcess.EnableRaisingEvents = true;
\r
200 this.HbProcess.Exited += HbProcess_Exited;
\r
203 // Set the Process Priority
\r
204 switch (Init.ProcessPriority)
\r
207 this.HbProcess.PriorityClass = ProcessPriorityClass.RealTime;
\r
210 this.HbProcess.PriorityClass = ProcessPriorityClass.High;
\r
212 case "Above Normal":
\r
213 this.HbProcess.PriorityClass = ProcessPriorityClass.AboveNormal;
\r
216 this.HbProcess.PriorityClass = ProcessPriorityClass.Normal;
\r
219 this.HbProcess.PriorityClass = ProcessPriorityClass.Idle;
\r
222 this.HbProcess.PriorityClass = ProcessPriorityClass.BelowNormal;
\r
226 // Fire the Encode Started Event
\r
227 if (this.EncodeStarted != null)
\r
228 this.EncodeStarted(this, new EventArgs());
\r
230 catch (Exception exc)
\r
232 errorService.ShowError("It would appear that HandBrakeCLI has not started correctly." +
\r
233 "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
239 /// Kill the CLI process
\r
245 if (this.HbProcess != null && !this.HbProcess.HasExited)
\r
247 this.HbProcess.Kill();
\r
250 catch (Exception exc)
\r
252 errorService.ShowError("Unable to stop HandBrakeCLI. It may not be running.", exc.ToString());
\r
255 if (this.EncodeEnded != null)
\r
256 this.EncodeEnded(this, new EventArgs());
\r
260 /// Attempt to Safely kill a DirectRun() CLI
\r
261 /// NOTE: This will not work with a MinGW CLI
\r
262 /// Note: http://www.cygwin.com/ml/cygwin/2006-03/msg00330.html
\r
264 public void SafelyClose()
\r
266 if ((int)this.processHandle == 0)
\r
269 // Allow the CLI to exit cleanly
\r
270 Win32.SetForegroundWindow((int)this.processHandle);
\r
271 SendKeys.Send("^C");
\r
274 /*/if (HbProcess != null)
\r
276 // HbProcess.StandardInput.AutoFlush = true;
\r
277 // HbProcess.StandardInput.WriteLine("^c^z");
\r
284 /// Save a copy of the log to the users desired location or a default location
\r
285 /// if this feature is enabled in options.
\r
287 /// <param name="destination">
\r
288 /// The Destination File Path
\r
290 protected void CopyLog(string destination)
\r
294 string logDir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) +
\r
295 "\\HandBrake\\logs";
\r
296 string tempLogFile = Path.Combine(logDir, string.Format("last_encode_log{0}.txt", Init.InstanceId));
\r
298 string encodeDestinationPath = Path.GetDirectoryName(destination);
\r
299 string destinationFile = Path.GetFileName(destination);
\r
300 string encodeLogFile = destinationFile + " " +
\r
301 DateTime.Now.ToString().Replace("/", "-").Replace(":", "-") + ".txt";
\r
303 // Make sure the log directory exists.
\r
304 if (!Directory.Exists(logDir))
\r
305 Directory.CreateDirectory(logDir);
\r
307 // Copy the Log to HandBrakes log folder in the users applciation data folder.
\r
308 File.Copy(tempLogFile, Path.Combine(logDir, encodeLogFile));
\r
310 // Save a copy of the log file in the same location as the enocde.
\r
311 if (Init.SaveLogWithVideo)
\r
312 File.Copy(tempLogFile, Path.Combine(encodeDestinationPath, encodeLogFile));
\r
314 // Save a copy of the log file to a user specified location
\r
315 if (Directory.Exists(Init.SaveLogPath))
\r
316 if (Init.SaveLogPath != String.Empty && Init.SaveLogToSpecifiedPath)
\r
317 File.Copy(tempLogFile, Path.Combine(Init.SaveLogPath, encodeLogFile));
\r
319 catch (Exception exc)
\r
321 errorService.ShowError("Unable to make a copy of the log file", exc.ToString());
\r
326 /// The HandBrakeCLI process has exited.
\r
328 /// <param name="sender">
\r
331 /// <param name="e">
\r
334 private void HbProcess_Exited(object sender, EventArgs e)
\r
336 IsEncoding = false;
\r
337 if (this.EncodeEnded != null)
\r
338 this.EncodeEnded(this, new EventArgs());
\r
340 if (windowsSeven.IsWindowsSeven)
\r
342 windowsSeven.SetTaskBarProgressToNoProgress();
\r
345 if (Init.PreventSleep)
\r
347 Win32.AllowSleep();
\r
352 if (fileWriter != null)
\r
354 fileWriter.Close();
\r
355 fileWriter.Dispose();
\r
358 catch (Exception exc)
\r
360 errorService.ShowError("Unable to close the log file wrtier", exc.ToString());
\r
365 /// Read the log file
\r
367 private void ReadFile()
\r
369 logBuffer = new StringBuilder();
\r
372 // 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
373 // we'll need to make a copy of it.
\r
374 string logDir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\HandBrake\\logs";
\r
375 string logFile = Path.Combine(logDir, string.Format("last_encode_log{0}.txt", Init.InstanceId));
\r
376 string logFile2 = Path.Combine(logDir, string.Format("tmp_appReadable_log{0}.txt", Init.InstanceId));
\r
377 int logFilePosition = 0;
\r
381 // Copy the log file.
\r
382 if (File.Exists(logFile))
\r
383 File.Copy(logFile, logFile2, true);
\r
387 // Start the Reader
\r
388 // Only use text which continues on from the last read line
\r
389 using (StreamReader sr = new StreamReader(logFile2))
\r
393 while ((line = sr.ReadLine()) != null)
\r
395 if (i > logFilePosition)
\r
397 logBuffer.AppendLine(line);
\r
405 catch (Exception exc)
\r
407 throw new Exception("Unable to read log file" + Environment.NewLine + exc);
\r
413 /// Setup the logging.
\r
415 /// <param name="encodeJob">
\r
416 /// The encode Job.
\r
418 private void SetupLogging(Job encodeJob)
\r
420 string logDir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\HandBrake\\logs";
\r
421 string logFile = Path.Combine(logDir, string.Format("last_encode_log{0}.txt", Init.InstanceId));
\r
422 string logFile2 = Path.Combine(logDir, string.Format("tmp_appReadable_log{0}.txt", Init.InstanceId));
\r
426 logBuffer = new StringBuilder();
\r
428 // Clear the current Encode Logs
\r
429 if (File.Exists(logFile)) File.Delete(logFile);
\r
430 if (File.Exists(logFile2)) File.Delete(logFile2);
\r
432 fileWriter = new StreamWriter(logFile) { AutoFlush = true };
\r
434 fileWriter.WriteLine(Logging.CreateCliLogHeader(encodeJob));
\r
435 logBuffer.AppendLine(Logging.CreateCliLogHeader(encodeJob));
\r
437 catch (Exception exc)
\r
439 if (fileWriter != null)
\r
441 fileWriter.Close();
\r
442 fileWriter.Dispose();
\r
445 errorService.ShowError("Error", exc.ToString());
\r
450 /// Recieve the Standard Error information and process it
\r
452 /// <param name="sender">
\r
453 /// The Sender Object
\r
455 /// <param name="e">
\r
456 /// DataReceived EventArgs
\r
458 private void HbProcErrorDataReceived(object sender, DataReceivedEventArgs e)
\r
460 if (!String.IsNullOrEmpty(e.Data))
\r
465 logBuffer.AppendLine(e.Data);
\r
467 if (fileWriter != null && fileWriter.BaseStream.CanWrite)
\r
469 fileWriter.WriteLine(e.Data);
\r
471 // If the logging grows past 100MB, kill the encode and stop.
\r
472 if (fileWriter.BaseStream.Length > 100000000)
\r
475 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
476 "Please check the encode log for an indication of what the problem is.");
\r
480 catch (Exception exc)
\r
482 // errorService.ShowError("Unable to write log data...", exc.ToString());
\r
487 #region Encode Status from Standard Output
\r
492 /// <param name="sender">
\r
495 /// <param name="e">
\r
498 private void Encode_EncodeStarted(object sender, EventArgs e)
\r
500 Thread monitor = new Thread(EncodeMonitor);
\r
505 /// Monitor the Job
\r
507 private void EncodeMonitor()
\r
511 Parser encode = new Parser(HbProcess.StandardOutput.BaseStream);
\r
512 encode.OnEncodeProgress += EncodeOnEncodeProgress;
\r
513 while (!encode.EndOfStream)
\r
514 encode.ReadEncodeStatus();
\r
516 catch (Exception exc)
\r
518 EncodeOnEncodeProgress(null, 0, 0, 0, 0, 0, "Unknown, status not available..");
\r
523 /// Displays the Encode status in the GUI
\r
525 /// <param name="sender">The sender</param>
\r
526 /// <param name="currentTask">The current task</param>
\r
527 /// <param name="taskCount">Number of tasks</param>
\r
528 /// <param name="percentComplete">Percent complete</param>
\r
529 /// <param name="currentFps">Current encode speed in fps</param>
\r
530 /// <param name="avg">Avg encode speed</param>
\r
531 /// <param name="timeRemaining">Time Left</param>
\r
532 private void EncodeOnEncodeProgress(object sender, int currentTask, int taskCount, float percentComplete, float currentFps, float avg, string timeRemaining)
\r
534 EncodeProgressEventArgs eventArgs = new EncodeProgressEventArgs
\r
536 AverageFrameRate = avg,
\r
537 CurrentFrameRate = currentFps,
\r
538 EstimatedTimeLeft = timeRemaining,
\r
539 PercentComplete = percentComplete,
\r
540 Task = currentTask,
\r
541 TaskCount = taskCount
\r
544 if (this.EncodeStatusChanged != null)
\r
545 this.EncodeStatusChanged(this, eventArgs);
\r
547 if (windowsSeven.IsWindowsSeven)
\r
550 int.TryParse(Math.Round(percentComplete).ToString(), out percent);
\r
552 windowsSeven.SetTaskBarProgress(percent);
\r