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
24 /* Private Variables */
\r
34 private StringBuilder logBuffer;
\r
37 /// The line number thats been read to in the log file
\r
39 private int logFilePosition;
\r
42 /// A Timer for this window
\r
44 private Timer windowTimer;
\r
47 /// Gets The Process Handle
\r
49 private IntPtr processHandle;
\r
52 /// Gets the Process ID
\r
54 private int processID;
\r
56 /* Event Handlers */
\r
59 /// Fires when a new CLI Job starts
\r
61 public event EventHandler EncodeStarted;
\r
64 /// Fires when a CLI job finishes.
\r
66 public event EventHandler EncodeEnded;
\r
71 /// Gets or sets The HB Process
\r
73 public Process HbProcess { get; set; }
\r
76 /// Gets a value indicating whether IsEncoding.
\r
78 public bool IsEncoding { get; private set; }
\r
80 /* Public Methods */
\r
83 /// Gets ActivityLog.
\r
85 public string ActivityLog
\r
89 if (logBuffer == null)
\r
95 return logBuffer != null ? logBuffer.ToString() : string.Empty;
\r
100 /// Create a preview sample video
\r
102 /// <param name="query">
\r
105 public void CreatePreviewSample(string query)
\r
107 this.Run(new Job { Query = query }, true);
\r
111 /// Kill the CLI process
\r
115 if (this.HbProcess != null)
\r
116 this.HbProcess.Kill();
\r
118 Process[] list = Process.GetProcessesByName("HandBrakeCLI");
\r
119 foreach (Process process in list)
\r
122 if (this.EncodeEnded != null)
\r
123 this.EncodeEnded(this, new EventArgs());
\r
127 /// Attempt to Safely kill a DirectRun() CLI
\r
128 /// NOTE: This will not work with a MinGW CLI
\r
129 /// Note: http://www.cygwin.com/ml/cygwin/2006-03/msg00330.html
\r
131 public void SafelyClose()
\r
133 if ((int)this.processHandle == 0)
\r
136 // Allow the CLI to exit cleanly
\r
137 Win32.SetForegroundWindow((int)this.processHandle);
\r
138 SendKeys.Send("^C");
\r
141 // HbProcess.StandardInput.AutoFlush = true;
\r
142 // HbProcess.StandardInput.WriteLine("^C");
\r
146 /// Execute a HandBrakeCLI process.
\r
148 /// <param name="encJob">
\r
151 /// <param name="RequireStandardOuput">
\r
152 /// Set to True to show no window and force standard output redirect
\r
154 protected void Run(Job encJob, bool RequireStandardOuput)
\r
162 string handbrakeCLIPath = Path.Combine(Application.StartupPath, "HandBrakeCLI.exe");
\r
163 string logPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\HandBrake\\logs", "last_encode_log.txt");
\r
164 string strCmdLine = String.Format(@" /C """"{0}"" {1} 2>""{2}"" """, handbrakeCLIPath, encJob.Query, logPath);
\r
165 var cliStart = new ProcessStartInfo("CMD.exe", strCmdLine);
\r
167 if (Settings.Default.enocdeStatusInGui || RequireStandardOuput)
\r
169 cliStart.RedirectStandardOutput = true;
\r
170 cliStart.UseShellExecute = false;
\r
171 if (!Settings.Default.showCliForInGuiEncodeStatus || RequireStandardOuput)
\r
172 cliStart.CreateNoWindow = true;
\r
174 if (Settings.Default.cli_minimized)
\r
175 cliStart.WindowStyle = ProcessWindowStyle.Minimized;
\r
177 Process[] before = Process.GetProcesses(); // Get a list of running processes before starting.
\r
178 HbProcess = Process.Start(cliStart);
\r
179 this.processID = Main.GetCliProcess(before);
\r
181 if (HbProcess != null)
\r
182 this.processHandle = HbProcess.MainWindowHandle; // Set the process Handle
\r
184 // Start the Log Monitor
\r
185 windowTimer = new Timer(new TimerCallback(ReadFile), null, 1000, 1000);
\r
187 // Set the process Priority
\r
188 Process hbCliProcess = null;
\r
189 if (this.processID != -1)
\r
191 hbCliProcess = Process.GetProcessById(this.processID);
\r
192 hbCliProcess.EnableRaisingEvents = true;
\r
193 hbCliProcess.Exited += new EventHandler(HbProcess_Exited);
\r
196 if (hbCliProcess != null)
\r
197 switch (Settings.Default.processPriority)
\r
200 hbCliProcess.PriorityClass = ProcessPriorityClass.RealTime;
\r
203 hbCliProcess.PriorityClass = ProcessPriorityClass.High;
\r
205 case "Above Normal":
\r
206 hbCliProcess.PriorityClass = ProcessPriorityClass.AboveNormal;
\r
209 hbCliProcess.PriorityClass = ProcessPriorityClass.Normal;
\r
212 hbCliProcess.PriorityClass = ProcessPriorityClass.Idle;
\r
215 hbCliProcess.PriorityClass = ProcessPriorityClass.BelowNormal;
\r
219 // Fire the Encode Started Event
\r
220 if (this.EncodeStarted != null)
\r
221 this.EncodeStarted(this, new EventArgs());
\r
223 catch (Exception exc)
\r
226 "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
229 MessageBoxButtons.OK,
\r
230 MessageBoxIcon.Error);
\r
235 /// The HandBrakeCLI process has exited.
\r
237 /// <param name="sender">
\r
240 /// <param name="e">
\r
243 private void HbProcess_Exited(object sender, EventArgs e)
\r
245 IsEncoding = false;
\r
249 /// Function to run the CLI directly rather than via CMD
\r
250 /// TODO: Code to handle the Log data has yet to be written.
\r
251 /// TODO: Code to handle the % / ETA info has to be written.
\r
253 /// <param name="query">
\r
256 protected void DirectRun(string query)
\r
260 if (this.EncodeStarted != null)
\r
261 this.EncodeStarted(this, new EventArgs());
\r
268 string handbrakeCLIPath = Path.Combine(Environment.CurrentDirectory, "HandBrakeCLI.exe");
\r
269 HbProcess = new Process
\r
273 FileName = handbrakeCLIPath,
\r
275 UseShellExecute = false,
\r
276 RedirectStandardOutput = true,
\r
277 RedirectStandardError = true,
\r
278 RedirectStandardInput = true,
\r
279 CreateNoWindow = false,
\r
280 WindowStyle = ProcessWindowStyle.Minimized
\r
284 // Setup event handlers for rediected data
\r
285 HbProcess.ErrorDataReceived += new DataReceivedEventHandler(HbProcErrorDataReceived);
\r
286 HbProcess.OutputDataReceived += new DataReceivedEventHandler(HbProcOutputDataReceived);
\r
288 // Start the process
\r
291 // Setup the asynchronous reading of stdin and stderr
\r
292 HbProcess.BeginErrorReadLine();
\r
293 HbProcess.BeginOutputReadLine();
\r
295 // Set the Process Priority);
\r
296 switch (Settings.Default.processPriority)
\r
299 HbProcess.PriorityClass = ProcessPriorityClass.RealTime;
\r
302 HbProcess.PriorityClass = ProcessPriorityClass.High;
\r
304 case "Above Normal":
\r
305 HbProcess.PriorityClass = ProcessPriorityClass.AboveNormal;
\r
308 HbProcess.PriorityClass = ProcessPriorityClass.Normal;
\r
311 HbProcess.PriorityClass = ProcessPriorityClass.Idle;
\r
314 HbProcess.PriorityClass = ProcessPriorityClass.BelowNormal;
\r
318 // Set the class items
\r
319 this.processID = HbProcess.Id;
\r
320 this.processHandle = HbProcess.Handle;
\r
322 catch (Exception exc)
\r
324 Console.WriteLine(exc);
\r
329 /// Perform an action after an encode. e.g a shutdown, standby, restart etc.
\r
331 protected void Finish()
\r
335 windowTimer.Dispose();
\r
339 if (this.EncodeEnded != null)
\r
340 this.EncodeEnded(this, new EventArgs());
\r
343 if (Settings.Default.growlQueue)
\r
344 GrowlCommunicator.Notify("Queue Completed", "Put down that cocktail...\nyour Handbrake queue is done.");
\r
346 // Do something whent he encode ends.
\r
347 switch (Settings.Default.CompletionOption)
\r
350 Process.Start("Shutdown", "-s -t 60");
\r
353 Win32.ExitWindowsEx(0, 0);
\r
356 Application.SetSuspendState(PowerState.Suspend, true, true);
\r
359 Application.SetSuspendState(PowerState.Hibernate, true, true);
\r
361 case "Lock System":
\r
362 Win32.LockWorkStation();
\r
364 case "Quit HandBrake":
\r
365 Application.Exit();
\r
373 /// Add the CLI Query to the Log File.
\r
375 /// <param name="encJob">
\r
376 /// The Encode Job Object
\r
378 protected void AddCLIQueryToLog(Job encJob)
\r
382 string logDir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) +
\r
383 "\\HandBrake\\logs";
\r
384 string logPath = Path.Combine(logDir, "last_encode_log.txt");
\r
386 var reader = new StreamReader(File.Open(logPath, FileMode.Open, FileAccess.Read, FileShare.Read));
\r
387 string log = reader.ReadToEnd();
\r
390 var writer = new StreamWriter(File.Create(logPath));
\r
392 writer.WriteLine("### CLI Query: " + encJob.Query);
\r
393 writer.WriteLine("### User Query: " + encJob.CustomQuery);
\r
394 writer.WriteLine("#########################################");
\r
395 writer.WriteLine(log);
\r
406 /// Save a copy of the log to the users desired location or a default location
\r
407 /// if this feature is enabled in options.
\r
409 /// <param name="destination">
\r
410 /// The Destination File Path
\r
412 protected void CopyLog(string destination)
\r
416 string logDir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) +
\r
417 "\\HandBrake\\logs";
\r
418 string tempLogFile = Path.Combine(logDir, "last_encode_log.txt");
\r
420 string encodeDestinationPath = Path.GetDirectoryName(destination);
\r
421 string destinationFile = Path.GetFileName(destination);
\r
422 string encodeLogFile = destinationFile + " " +
\r
423 DateTime.Now.ToString().Replace("/", "-").Replace(":", "-") + ".txt";
\r
425 // Make sure the log directory exists.
\r
426 if (!Directory.Exists(logDir))
\r
427 Directory.CreateDirectory(logDir);
\r
429 // Copy the Log to HandBrakes log folder in the users applciation data folder.
\r
430 File.Copy(tempLogFile, Path.Combine(logDir, encodeLogFile));
\r
432 // Save a copy of the log file in the same location as the enocde.
\r
433 if (Settings.Default.saveLogWithVideo)
\r
434 File.Copy(tempLogFile, Path.Combine(encodeDestinationPath, encodeLogFile));
\r
436 // Save a copy of the log file to a user specified location
\r
437 if (Directory.Exists(Settings.Default.saveLogPath))
\r
438 if (Settings.Default.saveLogPath != String.Empty && Settings.Default.saveLogToSpecifiedPath)
\r
439 File.Copy(tempLogFile, Path.Combine(Settings.Default.saveLogPath, encodeLogFile));
\r
441 catch (Exception exc)
\r
444 "Something went a bit wrong trying to copy your log file.\nError Information:\n\n" + exc,
\r
446 MessageBoxButtons.OK,
\r
447 MessageBoxIcon.Error);
\r
452 /// Read the log file
\r
454 /// <param name="n">
\r
457 private void ReadFile(object n)
\r
461 // 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
462 // we'll need to make a copy of it.
\r
463 string logDir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) +
\r
464 "\\HandBrake\\logs";
\r
465 string logFile = Path.Combine(logDir, "last_encode_log.txt");
\r
466 string logFile2 = Path.Combine(logDir, "tmp_appReadable_log.txt");
\r
470 // Make sure the application readable log file does not already exist. FileCopy fill fail if it does.
\r
471 if (File.Exists(logFile2))
\r
472 File.Delete(logFile2);
\r
474 // Copy the log file.
\r
475 if (File.Exists(logFile))
\r
476 File.Copy(logFile, logFile2, true);
\r
483 // Put the Query and User Generated Query Flag on the log.
\r
484 if (logFilePosition == 0 && job.Query != null)
\r
486 logBuffer.AppendLine("### CLI Query: " + job.Query);
\r
487 logBuffer.AppendLine("### User Query: " + job.CustomQuery);
\r
488 logBuffer.AppendLine("#########################################");
\r
491 // Start the Reader
\r
492 // Only use text which continues on from the last read line
\r
493 StreamReader sr = new StreamReader(logFile2);
\r
496 while ((line = sr.ReadLine()) != null)
\r
498 if (i > logFilePosition)
\r
500 logBuffer.AppendLine(line);
\r
516 /// Reset the Log Reader
\r
518 private void ResetLogReader()
\r
520 logFilePosition = 0;
\r
521 logBuffer = new StringBuilder();
\r
525 /// Recieve the Standard Error information and process it
\r
527 /// <param name="sender">
\r
528 /// The Sender Object
\r
530 /// <param name="e">
\r
531 /// DataReceived EventArgs
\r
533 private void HbProcErrorDataReceived(object sender, DataReceivedEventArgs e)
\r
535 if (!String.IsNullOrEmpty(e.Data))
\r
538 logBuffer.AppendLine(e.Data);
\r
543 /// Standard Input Data Recieved from the CLI
\r
545 /// <param name="sender">
\r
546 /// The Sender Object
\r
548 /// <param name="e">
\r
549 /// DataReceived EventArgs
\r
551 private void HbProcOutputDataReceived(object sender, DataReceivedEventArgs e)
\r
553 if (!String.IsNullOrEmpty(e.Data))
\r
556 logBuffer.AppendLine(e.Data);
\r