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.Properties;
\r
19 using Timer = System.Threading.Timer;
\r
22 /// Class which handles the CLI
\r
26 /* Private Variables */
\r
36 private StringBuilder logBuffer;
\r
39 /// The line number thats been read to in the log file
\r
41 private int logFilePosition;
\r
44 /// A Timer for this window
\r
46 private Timer windowTimer;
\r
49 /// Gets The Process Handle
\r
51 private IntPtr processHandle;
\r
54 /// Gets the Process ID
\r
56 private int processID;
\r
58 /* Event Handlers */
\r
61 /// Fires when a new CLI Job starts
\r
63 public event EventHandler EncodeStarted;
\r
66 /// Fires when a CLI job finishes.
\r
68 public event EventHandler EncodeEnded;
\r
73 /// Gets or sets The HB Process
\r
75 public Process HbProcess { get; set; }
\r
78 /// Gets a value indicating whether IsEncoding.
\r
80 public bool IsEncoding { get; private set; }
\r
82 /* Public Methods */
\r
85 /// Gets ActivityLog.
\r
87 public string ActivityLog
\r
91 if (logBuffer == null)
\r
97 return logBuffer != null ? logBuffer.ToString() : string.Empty;
\r
102 /// Create a preview sample video
\r
104 /// <param name="query">
\r
107 public void CreatePreviewSample(string query)
\r
109 this.Run(new Job { Query = query }, true);
\r
113 /// Kill the CLI process
\r
117 if (this.HbProcess != null)
\r
118 this.HbProcess.Kill();
\r
120 Process[] list = Process.GetProcessesByName("HandBrakeCLI");
\r
121 foreach (Process process in list)
\r
124 if (this.EncodeEnded != null)
\r
125 this.EncodeEnded(this, new EventArgs());
\r
129 /// Attempt to Safely kill a DirectRun() CLI
\r
130 /// NOTE: This will not work with a MinGW CLI
\r
131 /// Note: http://www.cygwin.com/ml/cygwin/2006-03/msg00330.html
\r
133 public void SafelyClose()
\r
135 if ((int)this.processHandle == 0)
\r
138 // Allow the CLI to exit cleanly
\r
139 Win32.SetForegroundWindow((int)this.processHandle);
\r
140 SendKeys.Send("^C");
\r
143 // HbProcess.StandardInput.AutoFlush = true;
\r
144 // HbProcess.StandardInput.WriteLine("^C");
\r
148 /// Execute a HandBrakeCLI process.
\r
150 /// <param name="encJob">
\r
153 /// <param name="RequireStandardOuput">
\r
154 /// Set to True to show no window and force standard output redirect
\r
156 protected void Run(Job encJob, bool RequireStandardOuput)
\r
164 string handbrakeCLIPath = Path.Combine(Application.StartupPath, "HandBrakeCLI.exe");
\r
165 string logPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\HandBrake\\logs", "last_encode_log.txt");
\r
166 string strCmdLine = String.Format(@" /C """"{0}"" {1} 2>""{2}"" """, handbrakeCLIPath, encJob.Query, logPath);
\r
167 var cliStart = new ProcessStartInfo("CMD.exe", strCmdLine);
\r
169 if (Settings.Default.enocdeStatusInGui || RequireStandardOuput)
\r
171 cliStart.RedirectStandardOutput = true;
\r
172 cliStart.UseShellExecute = false;
\r
173 if (!Settings.Default.showCliForInGuiEncodeStatus || RequireStandardOuput)
\r
174 cliStart.CreateNoWindow = true;
\r
176 if (Settings.Default.cli_minimized)
\r
177 cliStart.WindowStyle = ProcessWindowStyle.Minimized;
\r
179 Process[] before = Process.GetProcesses(); // Get a list of running processes before starting.
\r
180 HbProcess = Process.Start(cliStart);
\r
181 this.processID = Main.GetCliProcess(before);
\r
183 if (HbProcess != null)
\r
184 this.processHandle = HbProcess.MainWindowHandle; // Set the process Handle
\r
186 // Start the Log Monitor
\r
187 windowTimer = new Timer(new TimerCallback(ReadFile), null, 1000, 1000);
\r
189 // Set the process Priority
\r
190 Process hbCliProcess = null;
\r
191 if (this.processID != -1)
\r
193 hbCliProcess = Process.GetProcessById(this.processID);
\r
194 hbCliProcess.EnableRaisingEvents = true;
\r
195 hbCliProcess.Exited += new EventHandler(HbProcess_Exited);
\r
198 if (hbCliProcess != null)
\r
199 switch (Settings.Default.processPriority)
\r
202 hbCliProcess.PriorityClass = ProcessPriorityClass.RealTime;
\r
205 hbCliProcess.PriorityClass = ProcessPriorityClass.High;
\r
207 case "Above Normal":
\r
208 hbCliProcess.PriorityClass = ProcessPriorityClass.AboveNormal;
\r
211 hbCliProcess.PriorityClass = ProcessPriorityClass.Normal;
\r
214 hbCliProcess.PriorityClass = ProcessPriorityClass.Idle;
\r
217 hbCliProcess.PriorityClass = ProcessPriorityClass.BelowNormal;
\r
221 // Fire the Encode Started Event
\r
222 if (this.EncodeStarted != null)
\r
223 this.EncodeStarted(this, new EventArgs());
\r
225 catch (Exception exc)
\r
227 Main.ShowExceptiowWindow("It would appear that HandBrakeCLI has not started correctly. You should take a look at the Activity log as it may indicate the reason why.\n\nDetailed Error Information: error occured in runCli()", exc.ToString());
\r
232 /// The HandBrakeCLI process has exited.
\r
234 /// <param name="sender">
\r
237 /// <param name="e">
\r
240 private void HbProcess_Exited(object sender, EventArgs e)
\r
242 IsEncoding = false;
\r
246 /// Function to run the CLI directly rather than via CMD
\r
247 /// TODO: Code to handle the Log data has yet to be written.
\r
248 /// TODO: Code to handle the % / ETA info has to be written.
\r
250 /// <param name="query">
\r
253 protected void DirectRun(string query)
\r
257 if (this.EncodeStarted != null)
\r
258 this.EncodeStarted(this, new EventArgs());
\r
265 string handbrakeCLIPath = Path.Combine(Environment.CurrentDirectory, "HandBrakeCLI.exe");
\r
266 HbProcess = new Process
\r
270 FileName = handbrakeCLIPath,
\r
272 UseShellExecute = false,
\r
273 RedirectStandardOutput = true,
\r
274 RedirectStandardError = true,
\r
275 RedirectStandardInput = true,
\r
276 CreateNoWindow = false,
\r
277 WindowStyle = ProcessWindowStyle.Minimized
\r
281 // Setup event handlers for rediected data
\r
282 HbProcess.ErrorDataReceived += new DataReceivedEventHandler(HbProcErrorDataReceived);
\r
283 HbProcess.OutputDataReceived += new DataReceivedEventHandler(HbProcOutputDataReceived);
\r
285 // Start the process
\r
288 // Setup the asynchronous reading of stdin and stderr
\r
289 HbProcess.BeginErrorReadLine();
\r
290 HbProcess.BeginOutputReadLine();
\r
292 // Set the Process Priority);
\r
293 switch (Settings.Default.processPriority)
\r
296 HbProcess.PriorityClass = ProcessPriorityClass.RealTime;
\r
299 HbProcess.PriorityClass = ProcessPriorityClass.High;
\r
301 case "Above Normal":
\r
302 HbProcess.PriorityClass = ProcessPriorityClass.AboveNormal;
\r
305 HbProcess.PriorityClass = ProcessPriorityClass.Normal;
\r
308 HbProcess.PriorityClass = ProcessPriorityClass.Idle;
\r
311 HbProcess.PriorityClass = ProcessPriorityClass.BelowNormal;
\r
315 // Set the class items
\r
316 this.processID = HbProcess.Id;
\r
317 this.processHandle = HbProcess.Handle;
\r
319 catch (Exception exc)
\r
321 Console.WriteLine(exc);
\r
326 /// Perform an action after an encode. e.g a shutdown, standby, restart etc.
\r
328 protected void Finish()
\r
332 windowTimer.Dispose();
\r
336 if (this.EncodeEnded != null)
\r
337 this.EncodeEnded(this, new EventArgs());
\r
340 if (Settings.Default.growlQueue)
\r
341 GrowlCommunicator.Notify("Queue Completed", "Put down that cocktail...\nyour Handbrake queue is done.");
\r
343 // Do something whent he encode ends.
\r
344 switch (Settings.Default.CompletionOption)
\r
347 Process.Start("Shutdown", "-s -t 60");
\r
350 Win32.ExitWindowsEx(0, 0);
\r
353 Application.SetSuspendState(PowerState.Suspend, true, true);
\r
356 Application.SetSuspendState(PowerState.Hibernate, true, true);
\r
358 case "Lock System":
\r
359 Win32.LockWorkStation();
\r
361 case "Quit HandBrake":
\r
362 Application.Exit();
\r
370 /// Add the CLI Query to the Log File.
\r
372 /// <param name="encJob">
\r
373 /// The Encode Job Object
\r
375 protected void AddCLIQueryToLog(Job encJob)
\r
379 string logDir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) +
\r
380 "\\HandBrake\\logs";
\r
381 string logPath = Path.Combine(logDir, "last_encode_log.txt");
\r
383 var reader = new StreamReader(File.Open(logPath, FileMode.Open, FileAccess.Read, FileShare.Read));
\r
384 string log = reader.ReadToEnd();
\r
387 var writer = new StreamWriter(File.Create(logPath));
\r
389 writer.WriteLine("### CLI Query: " + encJob.Query);
\r
390 writer.WriteLine("### User Query: " + encJob.CustomQuery);
\r
391 writer.WriteLine("#########################################");
\r
392 writer.WriteLine(log);
\r
403 /// Save a copy of the log to the users desired location or a default location
\r
404 /// if this feature is enabled in options.
\r
406 /// <param name="destination">
\r
407 /// The Destination File Path
\r
409 protected void CopyLog(string destination)
\r
413 string logDir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) +
\r
414 "\\HandBrake\\logs";
\r
415 string tempLogFile = Path.Combine(logDir, "last_encode_log.txt");
\r
417 string encodeDestinationPath = Path.GetDirectoryName(destination);
\r
418 string destinationFile = Path.GetFileName(destination);
\r
419 string encodeLogFile = destinationFile + " " +
\r
420 DateTime.Now.ToString().Replace("/", "-").Replace(":", "-") + ".txt";
\r
422 // Make sure the log directory exists.
\r
423 if (!Directory.Exists(logDir))
\r
424 Directory.CreateDirectory(logDir);
\r
426 // Copy the Log to HandBrakes log folder in the users applciation data folder.
\r
427 File.Copy(tempLogFile, Path.Combine(logDir, encodeLogFile));
\r
429 // Save a copy of the log file in the same location as the enocde.
\r
430 if (Settings.Default.saveLogWithVideo)
\r
431 File.Copy(tempLogFile, Path.Combine(encodeDestinationPath, encodeLogFile));
\r
433 // Save a copy of the log file to a user specified location
\r
434 if (Directory.Exists(Settings.Default.saveLogPath))
\r
435 if (Settings.Default.saveLogPath != String.Empty && Settings.Default.saveLogToSpecifiedPath)
\r
436 File.Copy(tempLogFile, Path.Combine(Settings.Default.saveLogPath, encodeLogFile));
\r
438 catch (Exception exc)
\r
440 Main.ShowExceptiowWindow("Unable to make a copy of the log file", exc.ToString());
\r
445 /// Read the log file
\r
447 /// <param name="n">
\r
450 private void ReadFile(object n)
\r
454 // 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
455 // we'll need to make a copy of it.
\r
456 string logDir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) +
\r
457 "\\HandBrake\\logs";
\r
458 string logFile = Path.Combine(logDir, "last_encode_log.txt");
\r
459 string logFile2 = Path.Combine(logDir, "tmp_appReadable_log.txt");
\r
463 // Make sure the application readable log file does not already exist. FileCopy fill fail if it does.
\r
464 if (File.Exists(logFile2))
\r
465 File.Delete(logFile2);
\r
467 // Copy the log file.
\r
468 if (File.Exists(logFile))
\r
469 File.Copy(logFile, logFile2, true);
\r
476 // Put the Query and User Generated Query Flag on the log.
\r
477 if (logFilePosition == 0 && job.Query != null)
\r
479 logBuffer.AppendLine("### CLI Query: " + job.Query);
\r
480 logBuffer.AppendLine("### User Query: " + job.CustomQuery);
\r
481 logBuffer.AppendLine("#########################################");
\r
484 // Start the Reader
\r
485 // Only use text which continues on from the last read line
\r
486 StreamReader sr = new StreamReader(logFile2);
\r
489 while ((line = sr.ReadLine()) != null)
\r
491 if (i > logFilePosition)
\r
493 logBuffer.AppendLine(line);
\r
509 /// Reset the Log Reader
\r
511 private void ResetLogReader()
\r
513 logFilePosition = 0;
\r
514 logBuffer = new StringBuilder();
\r
518 /// Recieve the Standard Error information and process it
\r
520 /// <param name="sender">
\r
521 /// The Sender Object
\r
523 /// <param name="e">
\r
524 /// DataReceived EventArgs
\r
526 private void HbProcErrorDataReceived(object sender, DataReceivedEventArgs e)
\r
528 if (!String.IsNullOrEmpty(e.Data))
\r
531 logBuffer.AppendLine(e.Data);
\r
536 /// Standard Input Data Recieved from the CLI
\r
538 /// <param name="sender">
\r
539 /// The Sender Object
\r
541 /// <param name="e">
\r
542 /// DataReceived EventArgs
\r
544 private void HbProcOutputDataReceived(object sender, DataReceivedEventArgs e)
\r
546 if (!String.IsNullOrEmpty(e.Data))
\r
549 logBuffer.AppendLine(e.Data);
\r