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 /// Import a CSV file which contains Chapter Names
\r
86 /// <param name="dataChpt"></param>
\r
87 /// <param name="filename"></param>
\r
88 /// <returns></returns>
\r
89 public static DataGridView ImportChapterNames(DataGridView dataChpt, string filename)
\r
91 IDictionary<int, string> chapterMap = new Dictionary<int, string>();
\r
94 StreamReader sr = new StreamReader(filename);
\r
95 string csv = sr.ReadLine();
\r
98 if (csv.Trim() != "")
\r
100 csv = csv.Replace("\\,", "<!comma!>");
\r
101 string[] contents = csv.Split(',');
\r
103 int.TryParse(contents[0], out chapter);
\r
104 chapterMap.Add(chapter, contents[1].Replace("<!comma!>", ","));
\r
106 csv = sr.ReadLine();
\r
114 foreach (DataGridViewRow item in dataChpt.Rows)
\r
117 chapterMap.TryGetValue((int)item.Cells[0].Value, out name);
\r
118 item.Cells[1].Value = name ?? "Chapter " + item.Cells[0].Value;
\r
125 /// Function which generates the filename and path automatically based on
\r
126 /// the Source Name, DVD title and DVD Chapters
\r
128 public static string AutoName(frmMain mainWindow)
\r
130 string AutoNamePath = string.Empty;
\r
131 if (mainWindow.drp_dvdtitle.Text != "Automatic")
\r
133 // Get the Source Name
\r
134 string sourceName = mainWindow.SourceName;
\r
136 // Get the Selected Title Number
\r
137 string[] titlesplit = mainWindow.drp_dvdtitle.Text.Split(' ');
\r
138 string dvdTitle = titlesplit[0].Replace("Automatic", "");
\r
140 // Get the Chapter Start and Chapter End Numbers
\r
141 string chapterStart = mainWindow.drop_chapterStart.Text.Replace("Auto", "");
\r
142 string chapterFinish = mainWindow.drop_chapterFinish.Text.Replace("Auto", "");
\r
143 string combinedChapterTag = chapterStart;
\r
144 if (chapterFinish != chapterStart && chapterFinish != "")
\r
145 combinedChapterTag = chapterStart + "-" + chapterFinish;
\r
147 // Get the destination filename.
\r
148 string destinationFilename;
\r
149 if (Properties.Settings.Default.autoNameFormat != "")
\r
151 destinationFilename = Properties.Settings.Default.autoNameFormat;
\r
152 destinationFilename = destinationFilename.Replace("{source}", sourceName).Replace("{title}", dvdTitle).Replace("{chapters}", combinedChapterTag);
\r
155 destinationFilename = sourceName + "_T" + dvdTitle + "_C" + combinedChapterTag;
\r
157 // Add the appropriate file extension
\r
158 if (mainWindow.drop_format.SelectedIndex == 0)
\r
160 if (Properties.Settings.Default.useM4v || mainWindow.Check_ChapterMarkers.Checked || mainWindow.AudioSettings.RequiresM4V() || mainWindow.Subtitles.RequiresM4V())
\r
161 destinationFilename += ".m4v";
\r
163 destinationFilename += ".mp4";
\r
165 else if (mainWindow.drop_format.SelectedIndex == 1)
\r
166 destinationFilename += ".mkv";
\r
168 // Now work out the path where the file will be stored.
\r
169 // First case: If the destination box doesn't already contain a path, make one.
\r
170 if (!mainWindow.text_destination.Text.Contains(Path.DirectorySeparatorChar.ToString()))
\r
172 // If there is an auto name path, use it...
\r
173 if (Properties.Settings.Default.autoNamePath.Trim() != "" && Properties.Settings.Default.autoNamePath.Trim() != "Click 'Browse' to set the default location")
\r
174 AutoNamePath = Path.Combine(Properties.Settings.Default.autoNamePath, destinationFilename);
\r
175 else // ...otherwise, output to the source directory
\r
176 AutoNamePath = null;
\r
178 else // Otherwise, use the path that is already there.
\r
180 // Use the path and change the file extension to match the previous destination
\r
181 AutoNamePath = Path.Combine(Path.GetDirectoryName(mainWindow.text_destination.Text), destinationFilename);
\r
183 if (Path.HasExtension(mainWindow.text_destination.Text))
\r
184 AutoNamePath = Path.ChangeExtension(AutoNamePath, Path.GetExtension(mainWindow.text_destination.Text));
\r
188 return AutoNamePath;
\r
192 /// Get's HandBrakes version data from the CLI.
\r
194 /// <returns>Arraylist of Version Data. 0 = hb_version 1 = hb_build</returns>
\r
195 public static void SetCliVersionData()
\r
199 // 0 = SVN Build / Version
\r
202 DateTime lastModified = File.GetLastWriteTime("HandBrakeCLI.exe");
\r
205 if (Properties.Settings.Default.cliLastModified == lastModified && Properties.Settings.Default.hb_build != 0)
\r
208 Properties.Settings.Default.cliLastModified = lastModified;
\r
210 Process cliProcess = new Process();
\r
211 ProcessStartInfo handBrakeCLI = new ProcessStartInfo("HandBrakeCLI.exe", " -u -v0")
\r
213 UseShellExecute = false,
\r
214 RedirectStandardError = true,
\r
215 RedirectStandardOutput = true,
\r
216 CreateNoWindow = true
\r
218 cliProcess.StartInfo = handBrakeCLI;
\r
222 cliProcess.Start();
\r
223 // Retrieve standard output and report back to parent thread until the process is complete
\r
224 TextReader stdOutput = cliProcess.StandardError;
\r
226 while (!cliProcess.HasExited)
\r
228 line = stdOutput.ReadLine() ?? "";
\r
229 Match m = Regex.Match(line, @"HandBrake ([svnM0-9.]*) \([0-9]*\)");
\r
230 Match platform = Regex.Match(line, @"- ([A-Za-z0-9\s ]*) -");
\r
234 string data = line.Replace("(", "").Replace(")", "").Replace("HandBrake ", "");
\r
235 string[] arr = data.Split(' ');
\r
237 Properties.Settings.Default.hb_build = int.Parse(arr[1]);
\r
238 Properties.Settings.Default.hb_version = arr[0];
\r
240 if (platform.Success)
\r
241 Properties.Settings.Default.hb_platform = platform.Value.Replace("-", "").Trim();
\r
243 if (cliProcess.TotalProcessorTime.Seconds > 10) // Don't wait longer than 10 seconds.
\r
245 Process cli = Process.GetProcessById(cliProcess.Id);
\r
246 if (!cli.HasExited)
\r
250 Properties.Settings.Default.Save();
\r
252 catch (Exception e)
\r
254 MessageBox.Show("Unable to retrieve version information from the CLI. \nError:\n" + e);
\r
259 /// Check if the queue recovery file contains records.
\r
260 /// If it does, it means the last queue did not complete before HandBrake closed.
\r
261 /// So, return a boolean if true.
\r
263 public static Boolean CheckQueueRecovery()
\r
267 string tempPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), @"HandBrake\hb_queue_recovery.xml");
\r
268 if (File.Exists(tempPath))
\r
270 using (FileStream strm = new FileStream(tempPath, FileMode.Open, FileAccess.Read))
\r
272 List<Job> list = Ser.Deserialize(strm) as List<Job>;
\r
274 if (list.Count != 0)
\r
282 return false; // Keep quiet about the error.
\r
287 /// Get the Process ID of HandBrakeCLI for the current instance.
\r
289 /// <param name="before">List of processes before the new process was started</param>
\r
290 /// <returns>Int - Process ID</returns>
\r
291 public static int GetCliProcess(Process[] before)
\r
293 // This is a bit of a cludge. Maybe someone has a better idea on how to impliment this.
\r
294 // Since we used CMD to start HandBrakeCLI, we don't get the process ID from hbProc.
\r
295 // Instead we take the processes before and after, and get the ID of HandBrakeCLI.exe
\r
296 // avoiding any previous instances of HandBrakeCLI.exe in before.
\r
297 // Kill the current process.
\r
299 DateTime startTime = DateTime.Now;
\r
302 Process[] hbProcesses = Process.GetProcessesByName("HandBrakeCLI");
\r
303 while (hbProcesses.Length == 0)
\r
305 hbProcesses = Process.GetProcessesByName("HandBrakeCLI");
\r
306 duration = DateTime.Now - startTime;
\r
307 if (duration.Seconds > 5 && hbProcesses.Length == 0) // Make sure we don't wait forever if the process doesn't start
\r
311 Process hbProcess = null;
\r
312 foreach (Process process in hbProcesses)
\r
314 Boolean found = false;
\r
315 // Check if the current CLI instance was running before we started the current one
\r
316 foreach (Process bprocess in before)
\r
318 if (process.Id == bprocess.Id)
\r
322 // If it wasn't running before, we found the process we want.
\r
325 hbProcess = process;
\r
329 if (hbProcess != null)
\r
330 return hbProcess.Id;
\r
336 /// Clear all the encode log files.
\r
338 public static void ClearLogs()
\r
340 string logDir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\HandBrake\\logs";
\r
341 if (Directory.Exists(logDir))
\r
343 DirectoryInfo info = new DirectoryInfo(logDir);
\r
344 FileInfo[] logFiles = info.GetFiles("*.txt");
\r
345 foreach (FileInfo file in logFiles)
\r
347 if (!file.Name.Contains("last_scan_log") && !file.Name.Contains("last_encode_log") && !file.Name.Contains("tmp_appReadable_log.txt"))
\r
348 File.Delete(file.FullName);
\r
355 /// Clear old log files x days in the past
\r
357 public static void ClearOldLogs()
\r
359 string logDir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\HandBrake\\logs";
\r
360 if (Directory.Exists(logDir))
\r
362 DirectoryInfo info = new DirectoryInfo(logDir);
\r
363 FileInfo[] logFiles = info.GetFiles("*.txt");
\r
365 foreach (FileInfo file in logFiles)
\r
367 if (file.LastWriteTime < DateTime.Now.AddDays(-30))
\r
369 if (!file.Name.Contains("last_scan_log") && !file.Name.Contains("last_encode_log") && !file.Name.Contains("tmp_appReadable_log.txt"))
\r
370 File.Delete(file.FullName);
\r
378 /// Begins checking for an update to HandBrake.
\r
380 /// <param name="callback">The method that will be called when the check is finished.</param>
\r
381 /// <param name="debug">Whether or not to execute this in debug mode.</param>
\r
382 public static void BeginCheckForUpdates(AsyncCallback callback, bool debug)
\r
384 ThreadPool.QueueUserWorkItem(new WaitCallback(delegate
\r
388 // Is this a stable or unstable build?
\r
389 string url = Properties.Settings.Default.hb_build.ToString().EndsWith("1") ? Properties.Settings.Default.appcast_unstable : Properties.Settings.Default.appcast;
\r
391 // Initialize variables
\r
392 WebRequest request = WebRequest.Create(url);
\r
393 WebResponse response = request.GetResponse();
\r
394 AppcastReader reader = new AppcastReader();
\r
396 // Get the data, convert it to a string, and parse it into the AppcastReader
\r
397 reader.GetInfo(new StreamReader(response.GetResponseStream()).ReadToEnd());
\r
399 // Further parse the information
\r
400 string build = reader.Build;
\r
402 int latest = int.Parse(build);
\r
403 int current = Properties.Settings.Default.hb_build;
\r
404 int skip = Properties.Settings.Default.skipversion;
\r
406 // If the user wanted to skip this version, don't report the update
\r
407 if (latest == skip)
\r
409 UpdateCheckInformation info = new UpdateCheckInformation() { NewVersionAvailable = false, BuildInformation = null };
\r
410 callback(new UpdateCheckResult(debug, info));
\r
414 // Set when the last update was
\r
415 Properties.Settings.Default.lastUpdateCheckDate = DateTime.Now;
\r
416 Properties.Settings.Default.Save();
\r
418 UpdateCheckInformation info2 = new UpdateCheckInformation() { NewVersionAvailable = latest > current, BuildInformation = reader };
\r
419 callback(new UpdateCheckResult(debug, info2));
\r
421 catch (Exception exc)
\r
423 callback(new UpdateCheckResult(debug, new UpdateCheckInformation() { Error = exc }));
\r
431 /// <param name="result"></param>
\r
432 /// <returns></returns>
\r
433 public static UpdateCheckInformation EndCheckForUpdates(IAsyncResult result)
\r
435 UpdateCheckResult checkResult = (UpdateCheckResult)result;
\r
436 return checkResult.Result;
\r
440 /// Map languages and their iso639_2 value into a IDictionary
\r
442 /// <returns></returns>
\r
443 public static IDictionary<string, string> MapLanguages()
\r
445 IDictionary<string, string> languageMap = new Dictionary<string, string>
\r
449 {"Abkhazian", "abk"},
\r
450 {"Afrikaans", "afr"},
\r
452 {"Albanian", "sqi"},
\r
453 {"Amharic", "amh"},
\r
455 {"Aragonese", "arg"},
\r
456 {"Armenian", "hye"},
\r
457 {"Assamese", "asm"},
\r
459 {"Avestan", "ave"},
\r
461 {"Azerbaijani", "aze"},
\r
462 {"Bashkir", "bak"},
\r
463 {"Bambara", "bam"},
\r
465 {"Belarusian", "bel"},
\r
466 {"Bengali", "ben"},
\r
468 {"Bislama", "bis"},
\r
469 {"Bosnian", "bos"},
\r
471 {"Bulgarian", "bul"},
\r
472 {"Burmese", "mya"},
\r
473 {"Catalan", "cat"},
\r
474 {"Chamorro", "cha"},
\r
475 {"Chechen", "che"},
\r
476 {"Chinese", "zho"},
\r
477 {"Church Slavic", "chu"},
\r
478 {"Chuvash", "chv"},
\r
479 {"Cornish", "cor"},
\r
480 {"Corsican", "cos"},
\r
485 {"Nederlands", "nld"},
\r
486 {"Dzongkha", "dzo"},
\r
487 {"English", "eng"},
\r
488 {"Esperanto", "epo"},
\r
489 {"Estonian", "est"},
\r
491 {"Faroese", "fao"},
\r
494 {"Francais", "fra"},
\r
495 {"Western Frisian", "fry"},
\r
497 {"Georgian", "kat"},
\r
498 {"Deutsch", "deu"},
\r
499 {"Gaelic (Scots)", "gla"},
\r
501 {"Galician", "glg"},
\r
503 {"Greek Modern", "ell"},
\r
504 {"Guarani", "grn"},
\r
505 {"Gujarati", "guj"},
\r
506 {"Haitian", "hat"},
\r
511 {"Hiri Motu", "hmo"},
\r
514 {"Islenska", "isl"},
\r
516 {"Sichuan Yi", "iii"},
\r
517 {"Inuktitut", "iku"},
\r
518 {"Interlingue", "ile"},
\r
519 {"Interlingua", "ina"},
\r
520 {"Indonesian", "ind"},
\r
521 {"Inupiaq", "ipk"},
\r
522 {"Italiano", "ita"},
\r
523 {"Javanese", "jav"},
\r
524 {"Japanese", "jpn"},
\r
525 {"Kalaallisut", "kal"},
\r
526 {"Kannada", "kan"},
\r
527 {"Kashmiri", "kas"},
\r
530 {"Central Khmer", "khm"},
\r
532 {"Kinyarwanda", "kin"},
\r
533 {"Kirghiz", "kir"},
\r
537 {"Kuanyama", "kua"},
\r
538 {"Kurdish", "kur"},
\r
541 {"Latvian", "lav"},
\r
542 {"Limburgan", "lim"},
\r
543 {"Lingala", "lin"},
\r
544 {"Lithuanian", "lit"},
\r
545 {"Luxembourgish", "ltz"},
\r
546 {"Luba-Katanga", "lub"},
\r
548 {"Macedonian", "mkd"},
\r
549 {"Marshallese", "mah"},
\r
550 {"Malayalam", "mal"},
\r
552 {"Marathi", "mar"},
\r
554 {"Malagasy", "mlg"},
\r
555 {"Maltese", "mlt"},
\r
556 {"Moldavian", "mol"},
\r
557 {"Mongolian", "mon"},
\r
560 {"Ndebele, South", "nbl"},
\r
561 {"Ndebele, North", "nde"},
\r
564 {"Norwegian Nynorsk", "nno"},
\r
565 {"Norwegian Bokmål", "nob"},
\r
567 {"Chichewa; Nyanja", "nya"},
\r
568 {"Occitan", "oci"},
\r
572 {"Ossetian", "oss"},
\r
573 {"Panjabi", "pan"},
\r
574 {"Persian", "fas"},
\r
577 {"Portugues", "por"},
\r
579 {"Quechua", "que"},
\r
580 {"Romansh", "roh"},
\r
581 {"Romanian", "ron"},
\r
583 {"Russian", "rus"},
\r
585 {"Sanskrit", "san"},
\r
586 {"Serbian", "srp"},
\r
587 {"Hrvatski", "hrv"},
\r
588 {"Sinhala", "sin"},
\r
590 {"Slovenian", "slv"},
\r
591 {"Northern Sami", "sme"},
\r
596 {"Sotho Southern", "sot"},
\r
597 {"Espanol", "spa"},
\r
598 {"Sardinian", "srd"},
\r
600 {"Sundanese", "sun"},
\r
601 {"Swahili", "swa"},
\r
602 {"Svenska", "swe"},
\r
603 {"Tahitian", "tah"},
\r
608 {"Tagalog", "tgl"},
\r
610 {"Tibetan", "bod"},
\r
611 {"Tigrinya", "tir"},
\r
615 {"Turkmen", "tuk"},
\r
616 {"Turkish", "tur"},
\r
619 {"Ukrainian", "ukr"},
\r
623 {"Vietnamese", "vie"},
\r
624 {"Volapük", "vol"},
\r
626 {"Walloon", "wln"},
\r
629 {"Yiddish", "yid"},
\r
634 return languageMap;
\r