OSDN Git Service

49a836bb48339ef1e5ac3dcd4da64acee979bdf4
[handbrake-jp/handbrake-jp-git.git] / win / C# / EncodeQueue / Encode.cs
1 /*  Encode.cs $\r
2         \r
3            This file is part of the HandBrake source code.\r
4            Homepage: <http://handbrake.fr/>.\r
5            It may be used under the terms of the GNU General Public License. */\r
6 \r
7 using System;\r
8 using System.Diagnostics;\r
9 using System.IO;\r
10 using System.Windows.Forms;\r
11 using Handbrake.Functions;\r
12 \r
13 namespace Handbrake.EncodeQueue\r
14 {\r
15     public class Encode\r
16     {\r
17         private int ProcessID { get; set; }\r
18 \r
19         /// <summary>\r
20         /// The HB Process\r
21         /// </summary>\r
22         public Process HbProcess { get; set; }\r
23         \r
24         /// <summary>\r
25         /// The Process Handle\r
26         /// </summary>\r
27         public IntPtr ProcessHandle { get; set; }\r
28         \r
29         /// <summary>\r
30         /// Returns true of HandBrakeCLI.exe is running\r
31         /// </summary>\r
32         public Boolean IsEncoding { get; set; }     \r
33 \r
34         /// <summary>\r
35         /// Fires when a new CLI Job starts\r
36         /// </summary>\r
37         public event EventHandler EncodeStarted;\r
38 \r
39         /// <summary>\r
40         /// Fires when a CLI job finishes.\r
41         /// </summary>\r
42         public event EventHandler EncodeEnded;\r
43 \r
44         /// <summary>\r
45         /// Create a preview sample video\r
46         /// </summary>\r
47         /// <param name="query"></param>\r
48         public void CreatePreviewSample(string query)\r
49         {\r
50             Run(query);\r
51         }\r
52 \r
53         /// <summary>\r
54         /// Execute a HandBrakeCLI process.\r
55         /// </summary>\r
56         /// <param name="query">The CLI Query</param>\r
57         protected void Run(string query)\r
58         {\r
59             try\r
60             {\r
61                 if (EncodeStarted != null)\r
62                     EncodeStarted(this, new EventArgs());\r
63 \r
64                 IsEncoding = true;\r
65 \r
66                 string handbrakeCLIPath = Path.Combine(Application.StartupPath, "HandBrakeCLI.exe");\r
67                 string logPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\HandBrake\\logs", "last_encode_log.txt");\r
68                 string strCmdLine = String.Format(@" /C """"{0}"" {1} 2>""{2}"" """, handbrakeCLIPath, query, logPath);\r
69                 ProcessStartInfo cliStart = new ProcessStartInfo("CMD.exe", strCmdLine);\r
70 \r
71                 if (Properties.Settings.Default.enocdeStatusInGui)\r
72                 {\r
73                     cliStart.RedirectStandardOutput = true;\r
74                     cliStart.UseShellExecute = false;\r
75                     if (!Properties.Settings.Default.showCliForInGuiEncodeStatus)\r
76                         cliStart.CreateNoWindow = true;\r
77                 }\r
78                 if (Properties.Settings.Default.cli_minimized)\r
79                     cliStart.WindowStyle = ProcessWindowStyle.Minimized;\r
80 \r
81                 Process[] before = Process.GetProcesses(); // Get a list of running processes before starting.\r
82                 HbProcess = Process.Start(cliStart);\r
83                 ProcessID = Main.GetCliProcess(before);\r
84 \r
85                 if (HbProcess != null)\r
86                     ProcessHandle = HbProcess.MainWindowHandle; // Set the process Handle\r
87 \r
88                 // Set the process Priority\r
89                 Process hbCliProcess = null;\r
90                 if (ProcessID != -1)\r
91                     hbCliProcess = Process.GetProcessById(ProcessID);\r
92 \r
93                 if (hbCliProcess != null)\r
94                     switch (Properties.Settings.Default.processPriority)\r
95                     {\r
96                         case "Realtime":\r
97                             hbCliProcess.PriorityClass = ProcessPriorityClass.RealTime;\r
98                             break;\r
99                         case "High":\r
100                             hbCliProcess.PriorityClass = ProcessPriorityClass.High;\r
101                             break;\r
102                         case "Above Normal":\r
103                             hbCliProcess.PriorityClass = ProcessPriorityClass.AboveNormal;\r
104                             break;\r
105                         case "Normal":\r
106                             hbCliProcess.PriorityClass = ProcessPriorityClass.Normal;\r
107                             break;\r
108                         case "Low":\r
109                             hbCliProcess.PriorityClass = ProcessPriorityClass.Idle;\r
110                             break;\r
111                         default:\r
112                             hbCliProcess.PriorityClass = ProcessPriorityClass.BelowNormal;\r
113                             break;\r
114                     }\r
115             }\r
116             catch (Exception exc)\r
117             {\r
118                 MessageBox.Show("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\n   Detailed Error Information: error occured in runCli()\n\n" + exc, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);\r
119             }\r
120         }\r
121 \r
122         /// <summary>\r
123         /// Kill the CLI process\r
124         /// </summary>\r
125         public void Stop()\r
126         {\r
127             if (HbProcess != null)\r
128                 HbProcess.Kill();\r
129 \r
130             Process[] list = Process.GetProcessesByName("HandBrakeCLI");\r
131             foreach (Process process in list)\r
132                     process.Kill();\r
133 \r
134             IsEncoding = false;\r
135 \r
136             if (EncodeEnded != null)\r
137                 EncodeEnded(this, new EventArgs());\r
138         }\r
139 \r
140         /// <summary>\r
141         /// Perform an action after an encode. e.g a shutdown, standby, restart etc.\r
142         /// </summary>\r
143         protected void Finish()\r
144         {\r
145             IsEncoding = false;\r
146 \r
147             //Growl\r
148             if (Properties.Settings.Default.growlQueue)\r
149                 GrowlCommunicator.Notify("Queue Completed", "Put down that cocktail...\nyour Handbrake queue is done.");\r
150 \r
151             // Do something whent he encode ends.\r
152             switch (Properties.Settings.Default.CompletionOption)\r
153             {\r
154                 case "Shutdown":\r
155                     Process.Start("Shutdown", "-s -t 60");\r
156                     break;\r
157                 case "Log Off":\r
158                     Win32.ExitWindowsEx(0, 0);\r
159                     break;\r
160                 case "Suspend":\r
161                     Application.SetSuspendState(PowerState.Suspend, true, true);\r
162                     break;\r
163                 case "Hibernate":\r
164                     Application.SetSuspendState(PowerState.Hibernate, true, true);\r
165                     break;\r
166                 case "Lock System":\r
167                     Win32.LockWorkStation();\r
168                     break;\r
169                 case "Quit HandBrake":\r
170                     Application.Exit();\r
171                     break;\r
172                 default:\r
173                     break;\r
174             }\r
175         }\r
176 \r
177         /// <summary>\r
178         /// Add the CLI Query to the Log File.\r
179         /// </summary>\r
180         /// <param name="encJob"></param>\r
181         protected void AddCLIQueryToLog(Job encJob)\r
182         {\r
183             try\r
184             {\r
185                 string logDir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) +\r
186                                 "\\HandBrake\\logs";\r
187                 string logPath = Path.Combine(logDir, "last_encode_log.txt");\r
188 \r
189                 StreamReader reader =\r
190                     new StreamReader(File.Open(logPath, FileMode.Open, FileAccess.Read, FileShare.Read));\r
191                 String log = reader.ReadToEnd();\r
192                 reader.Close();\r
193 \r
194                 StreamWriter writer = new StreamWriter(File.Create(logPath));\r
195 \r
196                 writer.Write("### CLI Query: " + encJob.Query + "\n\n");\r
197                 writer.Write("### User Query: " + encJob.CustomQuery + "\n\n");\r
198                 writer.Write("#########################################\n\n");\r
199                 writer.WriteLine(log);\r
200                 writer.Flush();\r
201                 writer.Close();\r
202             } catch (Exception)\r
203             {\r
204                 return;\r
205             }\r
206         }\r
207 \r
208         /// <summary>\r
209         /// Save a copy of the log to the users desired location or a default location\r
210         /// if this feature is enabled in options.\r
211         /// </summary>\r
212         /// <param name="destination"></param>\r
213         protected void CopyLog(string destination)\r
214         {\r
215             try\r
216             {\r
217                 string logDir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\HandBrake\\logs";\r
218                 string tempLogFile = Path.Combine(logDir, "last_encode_log.txt");\r
219 \r
220                 string encodeDestinationPath = Path.GetDirectoryName(destination);\r
221                 String destinationFile = Path.GetFileName(destination);\r
222                 string encodeLogFile = destinationFile + " " + DateTime.Now.ToString().Replace("/", "-").Replace(":", "-") + ".txt";\r
223 \r
224                 // Make sure the log directory exists.\r
225                 if (!Directory.Exists(logDir))\r
226                     Directory.CreateDirectory(logDir);\r
227 \r
228                 // Copy the Log to HandBrakes log folder in the users applciation data folder.\r
229                 File.Copy(tempLogFile, Path.Combine(logDir, encodeLogFile));\r
230 \r
231                 // Save a copy of the log file in the same location as the enocde.\r
232                 if (Properties.Settings.Default.saveLogWithVideo)\r
233                     File.Copy(tempLogFile, Path.Combine(encodeDestinationPath, encodeLogFile));\r
234 \r
235                 // Save a copy of the log file to a user specified location\r
236                 if (Directory.Exists(Properties.Settings.Default.saveLogPath))\r
237                     if (Properties.Settings.Default.saveLogPath != String.Empty && Properties.Settings.Default.saveLogToSpecifiedPath)\r
238                         File.Copy(tempLogFile, Path.Combine(Properties.Settings.Default.saveLogPath, encodeLogFile));\r
239             }\r
240             catch (Exception exc)\r
241             {\r
242                 MessageBox.Show("Something went a bit wrong trying to copy your log file.\nError Information:\n\n" + exc, "Error",\r
243                                 MessageBoxButtons.OK, MessageBoxIcon.Error);\r
244             }\r
245         }\r
246     }\r
247 }