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.Services
\r
9 using System.Diagnostics;
\r
12 using System.Threading;
\r
13 using System.Windows.Forms;
\r
17 using Timer = System.Threading.Timer;
\r
20 /// Class which handles the CLI
\r
32 private StringBuilder logBuffer;
\r
35 /// The line number thats been read to in the log file
\r
37 private int logFilePosition;
\r
40 /// A Timer for this window
\r
42 private Timer windowTimer;
\r
45 /// Fires when a new CLI Job starts
\r
47 public event EventHandler EncodeStarted;
\r
50 /// Fires when a CLI job finishes.
\r
52 public event EventHandler EncodeEnded;
\r
55 /// Gets or sets The HB Process
\r
57 public Process HbProcess { get; set; }
\r
60 /// Gets or sets The Process Handle
\r
62 public IntPtr ProcessHandle { get; set; }
\r
65 /// Gets or sets a value indicating whether HandBrakeCLI.exe is running
\r
67 public bool IsEncoding { get; set; }
\r
70 /// Gets or sets the Process ID
\r
72 public int ProcessID { get; set; }
\r
75 /// Gets ActivityLog.
\r
77 public string ActivityLog
\r
81 if (logBuffer != null)
\r
82 return logBuffer.ToString();
\r
84 return string.Empty;
\r
89 /// Create a preview sample video
\r
91 /// <param name="query">
\r
94 public void CreatePreviewSample(string query)
\r
96 this.Run(new Job {Query = query});
\r
100 /// Kill the CLI process
\r
104 if (this.HbProcess != null)
\r
105 this.HbProcess.Kill();
\r
107 Process[] list = Process.GetProcessesByName("HandBrakeCLI");
\r
108 foreach (Process process in list)
\r
111 if (this.EncodeEnded != null)
\r
112 this.EncodeEnded(this, new EventArgs());
\r
114 IsEncoding = false;
\r
118 /// Attempt to Safely kill a DirectRun() CLI
\r
119 /// NOTE: This will not work with a MinGW CLI
\r
120 /// Note: http://www.cygwin.com/ml/cygwin/2006-03/msg00330.html
\r
122 public void SafelyClose()
\r
124 if ((int)this.ProcessHandle == 0)
\r
127 // Allow the CLI to exit cleanly
\r
128 Win32.SetForegroundWindow((int)this.ProcessHandle);
\r
129 SendKeys.Send("^C");
\r
132 // HbProcess.StandardInput.AutoFlush = true;
\r
133 // HbProcess.StandardInput.WriteLine("^C");
\r
135 IsEncoding = false;
\r
139 /// Execute a HandBrakeCLI process.
\r
141 /// <param name="encJob">
\r
144 protected void Run(Job encJob)
\r
153 string handbrakeCLIPath = Path.Combine(Application.StartupPath, "HandBrakeCLI.exe");
\r
156 Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\HandBrake\\logs",
\r
157 "last_encode_log.txt");
\r
158 string strCmdLine = String.Format(@" /C """"{0}"" {1} 2>""{2}"" """, handbrakeCLIPath, encJob.Query, logPath);
\r
159 var cliStart = new ProcessStartInfo("CMD.exe", strCmdLine);
\r
161 if (Settings.Default.enocdeStatusInGui)
\r
163 cliStart.RedirectStandardOutput = true;
\r
164 cliStart.UseShellExecute = false;
\r
165 if (!Settings.Default.showCliForInGuiEncodeStatus)
\r
166 cliStart.CreateNoWindow = true;
\r
168 if (Settings.Default.cli_minimized)
\r
169 cliStart.WindowStyle = ProcessWindowStyle.Minimized;
\r
171 Process[] before = Process.GetProcesses(); // Get a list of running processes before starting.
\r
172 this.HbProcess = Process.Start(cliStart);
\r
173 this.ProcessID = Main.GetCliProcess(before);
\r
175 // Fire the Encode Started Event
\r
176 if (this.EncodeStarted != null)
\r
177 this.EncodeStarted(this, new EventArgs());
\r
179 if (this.HbProcess != null)
\r
180 this.ProcessHandle = this.HbProcess.MainWindowHandle; // Set the process Handle
\r
182 // Start the Log Monitor
\r
183 windowTimer = new Timer(new TimerCallback(ReadFile), null, 1000, 1000);
\r
185 // Set the process Priority
\r
186 Process hbCliProcess = null;
\r
187 if (this.ProcessID != -1)
\r
188 hbCliProcess = Process.GetProcessById(this.ProcessID);
\r
190 if (hbCliProcess != null)
\r
191 switch (Settings.Default.processPriority)
\r
194 hbCliProcess.PriorityClass = ProcessPriorityClass.RealTime;
\r
197 hbCliProcess.PriorityClass = ProcessPriorityClass.High;
\r
199 case "Above Normal":
\r
200 hbCliProcess.PriorityClass = ProcessPriorityClass.AboveNormal;
\r
203 hbCliProcess.PriorityClass = ProcessPriorityClass.Normal;
\r
206 hbCliProcess.PriorityClass = ProcessPriorityClass.Idle;
\r
209 hbCliProcess.PriorityClass = ProcessPriorityClass.BelowNormal;
\r
213 catch (Exception exc)
\r
216 "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()\n\n" +
\r
219 MessageBoxButtons.OK,
\r
220 MessageBoxIcon.Error);
\r
225 /// Function to run the CLI directly rather than via CMD
\r
226 /// TODO: Code to handle the Log data has yet to be written.
\r
227 /// TODO: Code to handle the % / ETA info has to be written.
\r
229 /// <param name="query">
\r
232 protected void DirectRun(string query)
\r
236 if (this.EncodeStarted != null)
\r
237 this.EncodeStarted(this, new EventArgs());
\r
243 string handbrakeCLIPath = Path.Combine(Environment.CurrentDirectory, "HandBrakeCLI.exe");
\r
244 HbProcess = new Process
\r
248 FileName = handbrakeCLIPath,
\r
250 UseShellExecute = false,
\r
251 RedirectStandardOutput = true,
\r
252 RedirectStandardError = true,
\r
253 RedirectStandardInput = true,
\r
254 CreateNoWindow = false,
\r
255 WindowStyle = ProcessWindowStyle.Minimized
\r
259 // Setup event handlers for rediected data
\r
260 HbProcess.ErrorDataReceived += new DataReceivedEventHandler(HbProcErrorDataReceived);
\r
261 HbProcess.OutputDataReceived += new DataReceivedEventHandler(HbProcOutputDataReceived);
\r
263 // Start the process
\r
266 // Setup the asynchronous reading of stdin and stderr
\r
267 HbProcess.BeginErrorReadLine();
\r
268 HbProcess.BeginOutputReadLine();
\r
270 // Set the Process Priority);
\r
271 switch (Settings.Default.processPriority)
\r
274 HbProcess.PriorityClass = ProcessPriorityClass.RealTime;
\r
277 HbProcess.PriorityClass = ProcessPriorityClass.High;
\r
279 case "Above Normal":
\r
280 HbProcess.PriorityClass = ProcessPriorityClass.AboveNormal;
\r
283 HbProcess.PriorityClass = ProcessPriorityClass.Normal;
\r
286 HbProcess.PriorityClass = ProcessPriorityClass.Idle;
\r
289 HbProcess.PriorityClass = ProcessPriorityClass.BelowNormal;
\r
293 // Set the class items
\r
294 this.ProcessID = HbProcess.Id;
\r
295 this.ProcessHandle = HbProcess.Handle;
\r
297 catch (Exception exc)
\r
299 Console.WriteLine(exc);
\r
304 /// Perform an action after an encode. e.g a shutdown, standby, restart etc.
\r
306 protected void Finish()
\r
308 if (this.EncodeEnded != null)
\r
309 this.EncodeEnded(this, new EventArgs());
\r
311 IsEncoding = false;
\r
315 windowTimer.Dispose();
\r
320 if (Settings.Default.growlQueue)
\r
321 GrowlCommunicator.Notify("Queue Completed", "Put down that cocktail...\nyour Handbrake queue is done.");
\r
323 // Do something whent he encode ends.
\r
324 switch (Settings.Default.CompletionOption)
\r
327 Process.Start("Shutdown", "-s -t 60");
\r
330 Win32.ExitWindowsEx(0, 0);
\r
333 Application.SetSuspendState(PowerState.Suspend, true, true);
\r
336 Application.SetSuspendState(PowerState.Hibernate, true, true);
\r
338 case "Lock System":
\r
339 Win32.LockWorkStation();
\r
341 case "Quit HandBrake":
\r
342 Application.Exit();
\r
350 /// Add the CLI Query to the Log File.
\r
352 /// <param name="encJob">
\r
353 /// The Encode Job Object
\r
355 protected void AddCLIQueryToLog(Job encJob)
\r
359 string logDir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\HandBrake\\logs";
\r
360 string logPath = Path.Combine(logDir, "last_encode_log.txt");
\r
362 var reader = new StreamReader(File.Open(logPath, FileMode.Open, FileAccess.Read, FileShare.Read));
\r
363 string log = reader.ReadToEnd();
\r
366 var writer = new StreamWriter(File.Create(logPath));
\r
368 writer.WriteLine("### CLI Query: " + encJob.Query);
\r
369 writer.WriteLine("### User Query: " + encJob.CustomQuery);
\r
370 writer.WriteLine("#########################################");
\r
371 writer.WriteLine(log);
\r
382 /// Save a copy of the log to the users desired location or a default location
\r
383 /// if this feature is enabled in options.
\r
385 /// <param name="destination">
\r
386 /// The Destination File Path
\r
388 protected void CopyLog(string destination)
\r
392 string logDir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) +
\r
393 "\\HandBrake\\logs";
\r
394 string tempLogFile = Path.Combine(logDir, "last_encode_log.txt");
\r
396 string encodeDestinationPath = Path.GetDirectoryName(destination);
\r
397 string destinationFile = Path.GetFileName(destination);
\r
398 string encodeLogFile = destinationFile + " " +
\r
399 DateTime.Now.ToString().Replace("/", "-").Replace(":", "-") + ".txt";
\r
401 // Make sure the log directory exists.
\r
402 if (!Directory.Exists(logDir))
\r
403 Directory.CreateDirectory(logDir);
\r
405 // Copy the Log to HandBrakes log folder in the users applciation data folder.
\r
406 File.Copy(tempLogFile, Path.Combine(logDir, encodeLogFile));
\r
408 // Save a copy of the log file in the same location as the enocde.
\r
409 if (Settings.Default.saveLogWithVideo)
\r
410 File.Copy(tempLogFile, Path.Combine(encodeDestinationPath, encodeLogFile));
\r
412 // Save a copy of the log file to a user specified location
\r
413 if (Directory.Exists(Settings.Default.saveLogPath))
\r
414 if (Settings.Default.saveLogPath != String.Empty && Settings.Default.saveLogToSpecifiedPath)
\r
415 File.Copy(tempLogFile, Path.Combine(Settings.Default.saveLogPath, encodeLogFile));
\r
417 catch (Exception exc)
\r
420 "Something went a bit wrong trying to copy your log file.\nError Information:\n\n" + exc,
\r
422 MessageBoxButtons.OK,
\r
423 MessageBoxIcon.Error);
\r
428 /// Read the log file
\r
430 /// <param name="n">
\r
433 private void ReadFile(object n)
\r
437 // 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
438 // we'll need to make a copy of it.
\r
439 string logDir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\HandBrake\\logs";
\r
440 string logFile = Path.Combine(logDir, "last_encode_log.txt");
\r
441 string logFile2 = Path.Combine(logDir, "tmp_appReadable_log.txt");
\r
445 // Make sure the application readable log file does not already exist. FileCopy fill fail if it does.
\r
446 if (File.Exists(logFile2))
\r
447 File.Delete(logFile2);
\r
449 // Copy the log file.
\r
450 if (File.Exists(logFile))
\r
451 File.Copy(logFile, logFile2, true);
\r
458 // Put the Query and User Generated Query Flag on the log.
\r
459 if (logFilePosition == 0)
\r
461 logBuffer.AppendLine("### CLI Query: " + job.Query);
\r
462 logBuffer.AppendLine("### User Query: " + job.CustomQuery);
\r
463 logBuffer.AppendLine("#########################################");
\r
466 // Start the Reader
\r
467 // Only use text which continues on from the last read line
\r
468 StreamReader sr = new StreamReader(logFile2);
\r
471 while ((line = sr.ReadLine()) != null)
\r
473 if (i > logFilePosition)
\r
475 logBuffer.AppendLine(line);
\r
491 /// Reset the Log Reader
\r
493 private void ResetLogReader()
\r
495 logFilePosition = 0;
\r
496 logBuffer = new StringBuilder();
\r
500 /// Recieve the Standard Error information and process it
\r
502 /// <param name="sender">
\r
503 /// The Sender Object
\r
505 /// <param name="e">
\r
506 /// DataReceived EventArgs
\r
508 private void HbProcErrorDataReceived(object sender, DataReceivedEventArgs e)
\r
510 if (!String.IsNullOrEmpty(e.Data))
\r
513 logBuffer.AppendLine(e.Data);
\r
518 /// Standard Input Data Recieved from the CLI
\r
520 /// <param name="sender">
\r
521 /// The Sender Object
\r
523 /// <param name="e">
\r
524 /// DataReceived EventArgs
\r
526 private void HbProcOutputDataReceived(object sender, DataReceivedEventArgs e)
\r
528 if (!String.IsNullOrEmpty(e.Data))
\r
531 logBuffer.AppendLine(e.Data);
\r