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.Kill();
\r
247 catch (Exception exc)
\r
249 errorService.ShowError("Unable to stop HandBrakeCLI. It may not be running.", exc.ToString());
\r
252 if (this.EncodeEnded != null)
\r
253 this.EncodeEnded(this, new EventArgs());
\r
257 /// Attempt to Safely kill a DirectRun() CLI
\r
258 /// NOTE: This will not work with a MinGW CLI
\r
259 /// Note: http://www.cygwin.com/ml/cygwin/2006-03/msg00330.html
\r
261 public void SafelyClose()
\r
263 if ((int)this.processHandle == 0)
\r
266 // Allow the CLI to exit cleanly
\r
267 Win32.SetForegroundWindow((int)this.processHandle);
\r
268 SendKeys.Send("^C");
\r
271 /*/if (HbProcess != null)
\r
273 // HbProcess.StandardInput.AutoFlush = true;
\r
274 // HbProcess.StandardInput.WriteLine("^c^z");
\r
281 /// Save a copy of the log to the users desired location or a default location
\r
282 /// if this feature is enabled in options.
\r
284 /// <param name="destination">
\r
285 /// The Destination File Path
\r
287 protected void CopyLog(string destination)
\r
291 string logDir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) +
\r
292 "\\HandBrake\\logs";
\r
293 string tempLogFile = Path.Combine(logDir, string.Format("last_encode_log{0}.txt", Init.InstanceId));
\r
295 string encodeDestinationPath = Path.GetDirectoryName(destination);
\r
296 string destinationFile = Path.GetFileName(destination);
\r
297 string encodeLogFile = destinationFile + " " +
\r
298 DateTime.Now.ToString().Replace("/", "-").Replace(":", "-") + ".txt";
\r
300 // Make sure the log directory exists.
\r
301 if (!Directory.Exists(logDir))
\r
302 Directory.CreateDirectory(logDir);
\r
304 // Copy the Log to HandBrakes log folder in the users applciation data folder.
\r
305 File.Copy(tempLogFile, Path.Combine(logDir, encodeLogFile));
\r
307 // Save a copy of the log file in the same location as the enocde.
\r
308 if (Init.SaveLogWithVideo)
\r
309 File.Copy(tempLogFile, Path.Combine(encodeDestinationPath, encodeLogFile));
\r
311 // Save a copy of the log file to a user specified location
\r
312 if (Directory.Exists(Init.SaveLogPath))
\r
313 if (Init.SaveLogPath != String.Empty && Init.SaveLogToSpecifiedPath)
\r
314 File.Copy(tempLogFile, Path.Combine(Init.SaveLogPath, encodeLogFile));
\r
316 catch (Exception exc)
\r
318 errorService.ShowError("Unable to make a copy of the log file", exc.ToString());
\r
323 /// The HandBrakeCLI process has exited.
\r
325 /// <param name="sender">
\r
328 /// <param name="e">
\r
331 private void HbProcess_Exited(object sender, EventArgs e)
\r
333 IsEncoding = false;
\r
334 if (this.EncodeEnded != null)
\r
335 this.EncodeEnded(this, new EventArgs());
\r
337 if (windowsSeven.IsWindowsSeven)
\r
339 windowsSeven.SetTaskBarProgressToNoProgress();
\r
342 if (Init.PreventSleep)
\r
344 Win32.AllowSleep();
\r
349 if (fileWriter != null)
\r
351 fileWriter.Close();
\r
352 fileWriter.Dispose();
\r
355 catch (Exception exc)
\r
357 errorService.ShowError("Unable to close the log file wrtier", exc.ToString());
\r
362 /// Read the log file
\r
364 private void ReadFile()
\r
366 logBuffer = new StringBuilder();
\r
369 // 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
370 // we'll need to make a copy of it.
\r
371 string logDir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\HandBrake\\logs";
\r
372 string logFile = Path.Combine(logDir, string.Format("last_encode_log{0}.txt", Init.InstanceId));
\r
373 string logFile2 = Path.Combine(logDir, string.Format("tmp_appReadable_log{0}.txt", Init.InstanceId));
\r
374 int logFilePosition = 0;
\r
378 // Copy the log file.
\r
379 if (File.Exists(logFile))
\r
380 File.Copy(logFile, logFile2, true);
\r
384 // Start the Reader
\r
385 // Only use text which continues on from the last read line
\r
386 using (StreamReader sr = new StreamReader(logFile2))
\r
390 while ((line = sr.ReadLine()) != null)
\r
392 if (i > logFilePosition)
\r
394 logBuffer.AppendLine(line);
\r
402 catch (Exception exc)
\r
404 throw new Exception("Unable to read log file" + Environment.NewLine + exc);
\r
410 /// Setup the logging.
\r
412 /// <param name="encodeJob">
\r
413 /// The encode Job.
\r
415 private void SetupLogging(Job encodeJob)
\r
417 string logDir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\HandBrake\\logs";
\r
418 string logFile = Path.Combine(logDir, string.Format("last_encode_log{0}.txt", Init.InstanceId));
\r
419 string logFile2 = Path.Combine(logDir, string.Format("tmp_appReadable_log{0}.txt", Init.InstanceId));
\r
423 logBuffer = new StringBuilder();
\r
425 // Clear the current Encode Logs
\r
426 if (File.Exists(logFile)) File.Delete(logFile);
\r
427 if (File.Exists(logFile2)) File.Delete(logFile2);
\r
429 fileWriter = new StreamWriter(logFile) { AutoFlush = true };
\r
431 fileWriter.WriteLine(Logging.CreateCliLogHeader(encodeJob));
\r
432 logBuffer.AppendLine(Logging.CreateCliLogHeader(encodeJob));
\r
434 catch (Exception exc)
\r
436 if (fileWriter != null)
\r
438 fileWriter.Close();
\r
439 fileWriter.Dispose();
\r
442 errorService.ShowError("Error", exc.ToString());
\r
447 /// Recieve the Standard Error information and process it
\r
449 /// <param name="sender">
\r
450 /// The Sender Object
\r
452 /// <param name="e">
\r
453 /// DataReceived EventArgs
\r
455 private void HbProcErrorDataReceived(object sender, DataReceivedEventArgs e)
\r
457 if (!String.IsNullOrEmpty(e.Data))
\r
460 logBuffer.AppendLine(e.Data);
\r
464 if (fileWriter != null && fileWriter.BaseStream.CanWrite)
\r
466 fileWriter.WriteLine(e.Data);
\r
469 catch (Exception exc)
\r
471 // errorService.ShowError("Unable to write log data...", exc.ToString());
\r
476 #region Encode Status from Standard Output
\r
481 /// <param name="sender">
\r
484 /// <param name="e">
\r
487 private void Encode_EncodeStarted(object sender, EventArgs e)
\r
489 Thread monitor = new Thread(EncodeMonitor);
\r
494 /// Monitor the Job
\r
496 private void EncodeMonitor()
\r
500 Parser encode = new Parser(HbProcess.StandardOutput.BaseStream);
\r
501 encode.OnEncodeProgress += EncodeOnEncodeProgress;
\r
502 while (!encode.EndOfStream)
\r
503 encode.ReadEncodeStatus();
\r
505 catch (Exception exc)
\r
507 EncodeOnEncodeProgress(null, 0, 0, 0, 0, 0, "Unknown, status not available..");
\r
512 /// Displays the Encode status in the GUI
\r
514 /// <param name="sender">The sender</param>
\r
515 /// <param name="currentTask">The current task</param>
\r
516 /// <param name="taskCount">Number of tasks</param>
\r
517 /// <param name="percentComplete">Percent complete</param>
\r
518 /// <param name="currentFps">Current encode speed in fps</param>
\r
519 /// <param name="avg">Avg encode speed</param>
\r
520 /// <param name="timeRemaining">Time Left</param>
\r
521 private void EncodeOnEncodeProgress(object sender, int currentTask, int taskCount, float percentComplete, float currentFps, float avg, string timeRemaining)
\r
523 EncodeProgressEventArgs eventArgs = new EncodeProgressEventArgs
\r
525 AverageFrameRate = avg,
\r
526 CurrentFrameRate = currentFps,
\r
527 EstimatedTimeLeft = timeRemaining,
\r
528 PercentComplete = percentComplete,
\r
529 Task = currentTask,
\r
530 TaskCount = taskCount
\r
533 if (this.EncodeStatusChanged != null)
\r
534 this.EncodeStatusChanged(this, eventArgs);
\r
536 if (windowsSeven.IsWindowsSeven)
\r
539 int.TryParse(Math.Round(percentComplete).ToString(), out percent);
\r
541 windowsSeven.SetTaskBarProgress(percent);
\r