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
8 using System.Windows.Forms;
\r
10 using System.Diagnostics;
\r
11 using System.Text.RegularExpressions;
\r
12 using System.Collections.Generic;
\r
13 using System.Xml.Serialization;
\r
14 using System.Threading;
\r
15 using Handbrake.EncodeQueue;
\r
18 namespace Handbrake.Functions
\r
22 // Private Variables
\r
23 private static readonly XmlSerializer ser = new XmlSerializer(typeof(List<Job>));
\r
26 /// Calculate the duration of the selected title and chapters
\r
28 public static TimeSpan calculateDuration(int chapterStart, int chapterEnd, Parsing.Title selectedTitle)
\r
30 TimeSpan duration = TimeSpan.FromSeconds(0.0);
\r
31 chapterStart++; chapterEnd++;
\r
32 if (chapterStart != 0 && chapterEnd != 0 && chapterEnd <= selectedTitle.Chapters.Count)
\r
34 for (int i = chapterStart; i <= chapterEnd; i++)
\r
35 duration += selectedTitle.Chapters[i - 1].Duration;
\r
42 /// Select the longest title in the DVD title dropdown menu on frmMain
\r
44 public static Parsing.Title selectLongestTitle(Parsing.DVD thisDvd)
\r
46 TimeSpan longestDurationFound = TimeSpan.FromSeconds(0.0);
\r
47 Parsing.Title returnTitle = null;
\r
49 foreach (Parsing.Title item in thisDvd.Titles)
\r
51 if (item.Duration > longestDurationFound)
\r
54 longestDurationFound = item.Duration;
\r
61 /// Set's up the DataGridView on the Chapters tab (frmMain)
\r
63 public static DataGridView chapterNaming(DataGridView dataChpt, string chapterEnd)
\r
65 int i = 0, finish = 0;
\r
67 if (chapterEnd != "Auto")
\r
68 int.TryParse(chapterEnd, out finish);
\r
72 int n = dataChpt.Rows.Add();
\r
73 dataChpt.Rows[n].Cells[0].Value = (i + 1);
\r
74 dataChpt.Rows[n].Cells[1].Value = "Chapter " + (i + 1);
\r
75 dataChpt.Rows[n].Cells[0].ValueType = typeof(int);
\r
76 dataChpt.Rows[n].Cells[1].ValueType = typeof(string);
\r
84 /// Function which generates the filename and path automatically based on
\r
85 /// the Source Name, DVD title and DVD Chapters
\r
87 public static string autoName(ComboBox drpDvdtitle, string chapter_start, string chatper_end, string source, string dest, int format)
\r
89 string AutoNamePath = string.Empty;
\r
90 if (drpDvdtitle.Text != "Automatic")
\r
92 // Get the Source Name
\r
93 string sourceName = Path.GetFileNameWithoutExtension(source);
\r
95 // Get the Selected Title Number
\r
96 string[] titlesplit = drpDvdtitle.Text.Split(' ');
\r
97 string dvdTitle = titlesplit[0].Replace("Automatic", "");
\r
99 // Get the Chapter Start and Chapter End Numbers
\r
100 string chapterStart = chapter_start.Replace("Auto", "");
\r
101 string chapterFinish = chatper_end.Replace("Auto", "");
\r
102 string combinedChapterTag = chapterStart;
\r
103 if (chapterFinish != chapterStart && chapterFinish != "")
\r
104 combinedChapterTag = chapterStart + "-" + chapterFinish;
\r
106 // Get the destination filename.
\r
107 string destinationFilename;
\r
108 if (Properties.Settings.Default.autoNameFormat != "")
\r
110 destinationFilename = Properties.Settings.Default.autoNameFormat;
\r
111 destinationFilename = destinationFilename.Replace("{source}", sourceName).Replace("{title}", dvdTitle).Replace("{chapters}", combinedChapterTag);
\r
114 destinationFilename = sourceName + "_T" + dvdTitle + "_C" + combinedChapterTag;
\r
116 // Add the appropriate file extension
\r
119 if (Properties.Settings.Default.useM4v)
\r
120 destinationFilename += ".m4v";
\r
122 destinationFilename += ".mp4";
\r
124 else if (format == 1)
\r
125 destinationFilename += ".mkv";
\r
127 // Now work out the path where the file will be stored.
\r
128 // First case: If the destination box doesn't already contain a path, make one.
\r
129 if (!dest.Contains(Path.DirectorySeparatorChar.ToString()))
\r
131 // If there is an auto name path, use it...
\r
132 if (Properties.Settings.Default.autoNamePath.Trim() != "" && Properties.Settings.Default.autoNamePath.Trim() != "Click 'Browse' to set the default location")
\r
133 AutoNamePath = Path.Combine(Properties.Settings.Default.autoNamePath, destinationFilename);
\r
134 else // ...otherwise, output to the source directory
\r
135 AutoNamePath = null;
\r
137 else // Otherwise, use the path that is already there.
\r
139 // Use the path and change the file extension to match the previous destination
\r
140 AutoNamePath = Path.Combine(Path.GetDirectoryName(dest), destinationFilename);
\r
141 AutoNamePath = Path.ChangeExtension(AutoNamePath, Path.GetExtension(dest));
\r
145 return AutoNamePath;
\r
149 /// Get's HandBrakes version data from the CLI.
\r
151 /// <returns>Arraylist of Version Data. 0 = hb_version 1 = hb_build</returns>
\r
152 public static void setCliVersionData()
\r
156 // 0 = SVN Build / Version
\r
158 Process cliProcess = new Process();
\r
159 ProcessStartInfo handBrakeCLI = new ProcessStartInfo("HandBrakeCLI.exe", " -u")
\r
161 UseShellExecute = false,
\r
162 RedirectStandardError = true,
\r
163 RedirectStandardOutput = true,
\r
164 CreateNoWindow = true
\r
166 cliProcess.StartInfo = handBrakeCLI;
\r
170 cliProcess.Start();
\r
171 // Retrieve standard output and report back to parent thread until the process is complete
\r
172 TextReader stdOutput = cliProcess.StandardError;
\r
174 while (!cliProcess.HasExited)
\r
176 line = stdOutput.ReadLine() ?? "";
\r
177 Match m = Regex.Match(line, @"HandBrake ([0-9.]*)(svn[0-9M]*) \([0-9]*\)");
\r
178 Match platform = Regex.Match(line, @"- ([A-Za-z0-9\s ]*) -");
\r
182 string data = line.Replace("(", "").Replace(")", "").Replace("HandBrake ", "");
\r
183 string[] arr = data.Split(' ');
\r
185 Properties.Settings.Default.hb_build = int.Parse(arr[1]);
\r
186 Properties.Settings.Default.hb_version = arr[0];
\r
188 if (platform.Success)
\r
189 Properties.Settings.Default.hb_platform = platform.Value.Replace("-", "").Trim();
\r
191 if (cliProcess.TotalProcessorTime.Seconds > 10) // Don't wait longer than 10 seconds.
\r
193 Process cli = Process.GetProcessById(cliProcess.Id);
\r
194 if (!cli.HasExited)
\r
199 catch (Exception e)
\r
201 MessageBox.Show("Unable to retrieve version information from the CLI. \nError:\n" + e);
\r
206 /// Check if the queue recovery file contains records.
\r
207 /// If it does, it means the last queue did not complete before HandBrake closed.
\r
208 /// So, return a boolean if true.
\r
210 public static Boolean check_queue_recovery()
\r
214 string tempPath = Path.Combine(Path.GetTempPath(), "hb_queue_recovery.xml");
\r
215 if (File.Exists(tempPath))
\r
217 using (FileStream strm = new FileStream(tempPath, FileMode.Open, FileAccess.Read))
\r
219 List<Job> list = ser.Deserialize(strm) as List<Job>;
\r
221 if (list.Count != 0)
\r
229 return false; // Keep quiet about the error.
\r
234 /// Get the Process ID of HandBrakeCLI for the current instance.
\r
236 /// <param name="before">List of processes before the new process was started</param>
\r
237 /// <returns>Int - Process ID</returns>
\r
238 public static int getCliProcess(Process[] before)
\r
240 // This is a bit of a cludge. Maybe someone has a better idea on how to impliment this.
\r
241 // Since we used CMD to start HandBrakeCLI, we don't get the process ID from hbProc.
\r
242 // Instead we take the processes before and after, and get the ID of HandBrakeCLI.exe
\r
243 // avoiding any previous instances of HandBrakeCLI.exe in before.
\r
244 // Kill the current process.
\r
246 DateTime startTime = DateTime.Now;
\r
249 Process[] hbProcesses = Process.GetProcessesByName("HandBrakeCLI");
\r
250 while (hbProcesses.Length == 0)
\r
252 hbProcesses = Process.GetProcessesByName("HandBrakeCLI");
\r
253 duration = DateTime.Now - startTime;
\r
254 if (duration.Seconds > 5 && hbProcesses.Length == 0) // Make sure we don't wait forever if the process doesn't start
\r
258 Process hbProcess = null;
\r
259 foreach (Process process in hbProcesses)
\r
261 Boolean found = false;
\r
262 // Check if the current CLI instance was running before we started the current one
\r
263 foreach (Process bprocess in before)
\r
265 if (process.Id == bprocess.Id)
\r
269 // If it wasn't running before, we found the process we want.
\r
272 hbProcess = process;
\r
276 if (hbProcess != null)
\r
277 return hbProcess.Id;
\r
283 /// Clear all the encode log files.
\r
285 public static void clearLogs()
\r
287 string logDir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\HandBrake\\logs";
\r
288 if (Directory.Exists(logDir))
\r
290 DirectoryInfo info = new DirectoryInfo(logDir);
\r
291 FileInfo[] logFiles = info.GetFiles("*.txt");
\r
292 foreach (FileInfo file in logFiles)
\r
294 if (!file.Name.Contains("last_scan_log") && !file.Name.Contains("last_encode_log") && !file.Name.Contains("tmp_appReadable_log.txt"))
\r
295 File.Delete(file.FullName);
\r
301 /// Begins checking for an update to HandBrake.
\r
303 /// <param name="callback">The method that will be called when the check is finished.</param>
\r
304 /// <param name="debug">Whether or not to execute this in debug mode.</param>
\r
305 public static void BeginCheckForUpdates(AsyncCallback callback, bool debug)
\r
307 ThreadPool.QueueUserWorkItem(new WaitCallback(delegate
\r
311 // Is this a stable or unstable build?
\r
312 string url = Properties.Settings.Default.hb_build.ToString().EndsWith("1") ? Properties.Settings.Default.appcast_unstable : Properties.Settings.Default.appcast;
\r
314 // Initialize variables
\r
315 WebRequest request = WebRequest.Create(url);
\r
316 WebResponse response = request.GetResponse();
\r
317 AppcastReader reader = new AppcastReader();
\r
319 // Get the data, convert it to a string, and parse it into the AppcastReader
\r
320 reader.getInfo(new StreamReader(response.GetResponseStream()).ReadToEnd());
\r
322 // Further parse the information
\r
323 string build = reader.build;
\r
325 int latest = int.Parse(build);
\r
326 int current = Properties.Settings.Default.hb_build;
\r
327 int skip = Properties.Settings.Default.skipversion;
\r
329 // If the user wanted to skip this version, don't report the update
\r
330 if (latest == skip)
\r
332 UpdateCheckInformation info = new UpdateCheckInformation() { NewVersionAvailable = false, BuildInformation = null };
\r
333 callback(new UpdateCheckResult(debug, info));
\r
337 // Set when the last update was
\r
338 Properties.Settings.Default.lastUpdateCheckDate = DateTime.Now;
\r
339 Properties.Settings.Default.Save();
\r
341 UpdateCheckInformation info2 = new UpdateCheckInformation() { NewVersionAvailable = latest > current, BuildInformation = reader };
\r
342 callback(new UpdateCheckResult(debug, info2));
\r
344 catch (Exception exc)
\r
346 callback(new UpdateCheckResult(debug, new UpdateCheckInformation() { Error = exc }));
\r
354 /// <param name="result"></param>
\r
355 /// <returns></returns>
\r
356 public static UpdateCheckInformation EndCheckForUpdates(IAsyncResult result)
\r
358 UpdateCheckResult checkResult = (UpdateCheckResult)result;
\r
359 return checkResult.Result;
\r
363 /// Used in EndUpdateCheck() for update checking and the IAsyncResult design pattern.
\r
365 private class UpdateCheckResult : IAsyncResult
\r
367 public UpdateCheckResult(object asyncState, UpdateCheckInformation info)
\r
369 AsyncState = asyncState;
\r
374 /// Gets whether the check was executed in debug mode.
\r
376 public object AsyncState { get; private set; }
\r
379 /// Gets the result of the update check.
\r
381 public UpdateCheckInformation Result { get; private set; }
\r
383 public WaitHandle AsyncWaitHandle { get { throw new NotImplementedException(); } }
\r
384 public bool CompletedSynchronously { get { throw new NotImplementedException(); } }
\r
385 public bool IsCompleted { get { throw new NotImplementedException(); } }
\r
389 /// Map languages and their iso639_2 value into a IDictionary
\r
391 /// <returns></returns>
\r
392 public static IDictionary<string, string> mapLanguages()
\r
394 IDictionary<string, string> languageMap = new Dictionary<string, string>
\r
398 {"Abkhazian", "abk"},
\r
399 {"Afrikaans", "afr"},
\r
401 {"Albanian", "sqi"},
\r
402 {"Amharic", "amh"},
\r
404 {"Aragonese", "arg"},
\r
405 {"Armenian", "hye"},
\r
406 {"Assamese", "asm"},
\r
408 {"Avestan", "ave"},
\r
410 {"Azerbaijani", "aze"},
\r
411 {"Bashkir", "bak"},
\r
412 {"Bambara", "bam"},
\r
414 {"Belarusian", "bel"},
\r
415 {"Bengali", "ben"},
\r
417 {"Bislama", "bis"},
\r
418 {"Bosnian", "bos"},
\r
420 {"Bulgarian", "bul"},
\r
421 {"Burmese", "mya"},
\r
422 {"Catalan", "cat"},
\r
423 {"Chamorro", "cha"},
\r
424 {"Chechen", "che"},
\r
425 {"Chinese", "zho"},
\r
426 {"Church Slavic", "chu"},
\r
427 {"Chuvash", "chv"},
\r
428 {"Cornish", "cor"},
\r
429 {"Corsican", "cos"},
\r
434 {"Nederlands", "nld"},
\r
435 {"Dzongkha", "dzo"},
\r
436 {"English", "eng"},
\r
437 {"Esperanto", "epo"},
\r
438 {"Estonian", "est"},
\r
440 {"Faroese", "fao"},
\r
443 {"Francais", "fra"},
\r
444 {"Western Frisian", "fry"},
\r
446 {"Georgian", "kat"},
\r
447 {"Deutsch", "deu"},
\r
448 {"Gaelic (Scots)", "gla"},
\r
450 {"Galician", "glg"},
\r
452 {"Greek Modern", "ell"},
\r
453 {"Guarani", "grn"},
\r
454 {"Gujarati", "guj"},
\r
455 {"Haitian", "hat"},
\r
460 {"Hiri Motu", "hmo"},
\r
463 {"Islenska", "isl"},
\r
465 {"Sichuan Yi", "iii"},
\r
466 {"Inuktitut", "iku"},
\r
467 {"Interlingue", "ile"},
\r
468 {"Interlingua", "ina"},
\r
469 {"Indonesian", "ind"},
\r
470 {"Inupiaq", "ipk"},
\r
471 {"Italiano", "ita"},
\r
472 {"Javanese", "jav"},
\r
473 {"Japanese", "jpn"},
\r
474 {"Kalaallisut", "kal"},
\r
475 {"Kannada", "kan"},
\r
476 {"Kashmiri", "kas"},
\r
479 {"Central Khmer", "khm"},
\r
481 {"Kinyarwanda", "kin"},
\r
482 {"Kirghiz", "kir"},
\r
486 {"Kuanyama", "kua"},
\r
487 {"Kurdish", "kur"},
\r
490 {"Latvian", "lav"},
\r
491 {"Limburgan", "lim"},
\r
492 {"Lingala", "lin"},
\r
493 {"Lithuanian", "lit"},
\r
494 {"Luxembourgish", "ltz"},
\r
495 {"Luba-Katanga", "lub"},
\r
497 {"Macedonian", "mkd"},
\r
498 {"Marshallese", "mah"},
\r
499 {"Malayalam", "mal"},
\r
501 {"Marathi", "mar"},
\r
503 {"Malagasy", "mlg"},
\r
504 {"Maltese", "mlt"},
\r
505 {"Moldavian", "mol"},
\r
506 {"Mongolian", "mon"},
\r
509 {"Ndebele, South", "nbl"},
\r
510 {"Ndebele, North", "nde"},
\r
513 {"Norwegian Nynorsk", "nno"},
\r
514 {"Norwegian Bokmål", "nob"},
\r
516 {"Chichewa; Nyanja", "nya"},
\r
517 {"Occitan", "oci"},
\r
521 {"Ossetian", "oss"},
\r
522 {"Panjabi", "pan"},
\r
523 {"Persian", "fas"},
\r
526 {"Portugues", "por"},
\r
528 {"Quechua", "que"},
\r
529 {"Romansh", "roh"},
\r
530 {"Romanian", "ron"},
\r
532 {"Russian", "rus"},
\r
534 {"Sanskrit", "san"},
\r
535 {"Serbian", "srp"},
\r
536 {"Hrvatski", "hrv"},
\r
537 {"Sinhala", "sin"},
\r
539 {"Slovenian", "slv"},
\r
540 {"Northern Sami", "sme"},
\r
545 {"Sotho Southern", "sot"},
\r
546 {"Espanol", "spa"},
\r
547 {"Sardinian", "srd"},
\r
549 {"Sundanese", "sun"},
\r
550 {"Swahili", "swa"},
\r
551 {"Svenska", "swe"},
\r
552 {"Tahitian", "tah"},
\r
557 {"Tagalog", "tgl"},
\r
559 {"Tibetan", "bod"},
\r
560 {"Tigrinya", "tir"},
\r
564 {"Turkmen", "tuk"},
\r
565 {"Turkish", "tur"},
\r
568 {"Ukrainian", "ukr"},
\r
572 {"Vietnamese", "vie"},
\r
573 {"Volapük", "vol"},
\r
575 {"Walloon", "wln"},
\r
578 {"Yiddish", "yid"},
\r
583 return languageMap;
\r