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.Functions
\r
9 using System.Collections.Generic;
\r
10 using System.Diagnostics;
\r
11 using System.Globalization;
\r
15 using System.Text.RegularExpressions;
\r
16 using System.Threading;
\r
17 using System.Windows.Forms;
\r
18 using System.Xml.Serialization;
\r
23 /// Useful functions which various screens can use.
\r
25 public static class Main
\r
28 /// The XML Serializer
\r
30 private static readonly XmlSerializer Ser = new XmlSerializer(typeof(List<Job>));
\r
33 /// Calculate the duration of the selected title and chapters
\r
35 /// <param name="chapterStart">
\r
36 /// The chapter Start.
\r
38 /// <param name="chapterEnd">
\r
39 /// The chapter End.
\r
41 /// <param name="selectedTitle">
\r
42 /// The selected Title.
\r
45 /// The calculated duration.
\r
47 public static TimeSpan CalculateDuration(int chapterStart, int chapterEnd, Title selectedTitle)
\r
49 TimeSpan duration = TimeSpan.FromSeconds(0.0);
\r
52 if (chapterStart != 0 && chapterEnd != 0 && chapterEnd <= selectedTitle.Chapters.Count)
\r
54 for (int i = chapterStart; i <= chapterEnd; i++)
\r
55 duration += selectedTitle.Chapters[i - 1].Duration;
\r
62 /// Select the longest title in the DVD title dropdown menu on frmMain
\r
64 /// <param name="source">
\r
68 /// The longest title.
\r
70 public static Title SelectLongestTitle(DVD source)
\r
72 TimeSpan longestDurationFound = TimeSpan.FromSeconds(0.0);
\r
73 Title returnTitle = null;
\r
75 foreach (Title item in source.Titles)
\r
77 if (item.Duration > longestDurationFound)
\r
80 longestDurationFound = item.Duration;
\r
87 /// Set's up the DataGridView on the Chapters tab (frmMain)
\r
89 /// <param name="dataChpt">
\r
90 /// The DataGridView Control
\r
92 /// <param name="chapterEnd">
\r
93 /// The chapter End.
\r
96 /// The chapter naming.
\r
98 public static DataGridView ChapterNaming(DataGridView dataChpt, string chapterEnd)
\r
100 int i = 0, finish = 0;
\r
102 if (chapterEnd != "Auto")
\r
103 int.TryParse(chapterEnd, out finish);
\r
107 int n = dataChpt.Rows.Add();
\r
108 dataChpt.Rows[n].Cells[0].Value = i + 1;
\r
109 dataChpt.Rows[n].Cells[1].Value = "Chapter " + (i + 1);
\r
110 dataChpt.Rows[n].Cells[0].ValueType = typeof(int);
\r
111 dataChpt.Rows[n].Cells[1].ValueType = typeof(string);
\r
119 /// Import a CSV file which contains Chapter Names
\r
121 /// <param name="dataChpt">
\r
122 /// The DataGridView Control
\r
124 /// <param name="filename">
\r
125 /// The filepath and name
\r
127 /// <returns>A Populated DataGridView</returns>
\r
128 public static DataGridView ImportChapterNames(DataGridView dataChpt, string filename)
\r
130 IDictionary<int, string> chapterMap = new Dictionary<int, string>();
\r
133 StreamReader sr = new StreamReader(filename);
\r
134 string csv = sr.ReadLine();
\r
135 while (csv != null)
\r
137 if (csv.Trim() != string.Empty)
\r
139 csv = csv.Replace("\\,", "<!comma!>");
\r
140 string[] contents = csv.Split(',');
\r
142 int.TryParse(contents[0], out chapter);
\r
143 chapterMap.Add(chapter, contents[1].Replace("<!comma!>", ","));
\r
145 csv = sr.ReadLine();
\r
153 foreach (DataGridViewRow item in dataChpt.Rows)
\r
156 chapterMap.TryGetValue((int)item.Cells[0].Value, out name);
\r
157 item.Cells[1].Value = name ?? "Chapter " + item.Cells[0].Value;
\r
164 /// Function which generates the filename and path automatically based on
\r
165 /// the Source Name, DVD title and DVD Chapters
\r
167 /// <param name="mainWindow">
\r
168 /// The main Window.
\r
171 /// The Generated FileName
\r
173 public static string AutoName(frmMain mainWindow)
\r
175 string autoNamePath = string.Empty;
\r
176 if (mainWindow.drp_dvdtitle.Text != "Automatic")
\r
178 // Get the Source Name
\r
179 string sourceName = mainWindow.SourceName;
\r
181 if (Properties.Settings.Default.AutoNameRemoveUnderscore)
\r
182 sourceName = sourceName.Replace("_", " ");
\r
184 if (Properties.Settings.Default.AutoNameTitleCase)
\r
185 sourceName = TitleCase(sourceName);
\r
187 // Get the Selected Title Number
\r
188 string[] titlesplit = mainWindow.drp_dvdtitle.Text.Split(' ');
\r
189 string dvdTitle = titlesplit[0].Replace("Automatic", string.Empty);
\r
191 // Get the Chapter Start and Chapter End Numbers
\r
192 string chapterStart = mainWindow.drop_chapterStart.Text.Replace("Auto", string.Empty);
\r
193 string chapterFinish = mainWindow.drop_chapterFinish.Text.Replace("Auto", string.Empty);
\r
194 string combinedChapterTag = chapterStart;
\r
195 if (chapterFinish != chapterStart && chapterFinish != string.Empty)
\r
196 combinedChapterTag = chapterStart + "-" + chapterFinish;
\r
198 // Get the destination filename.
\r
199 string destinationFilename;
\r
200 if (Properties.Settings.Default.autoNameFormat != string.Empty)
\r
202 destinationFilename = Properties.Settings.Default.autoNameFormat;
\r
203 destinationFilename =
\r
204 destinationFilename.Replace("{source}", sourceName).Replace("{title}", dvdTitle).Replace(
\r
205 "{chapters}", combinedChapterTag);
\r
208 destinationFilename = sourceName + "_T" + dvdTitle + "_C" + combinedChapterTag;
\r
210 // Add the appropriate file extension
\r
211 if (mainWindow.drop_format.SelectedIndex == 0)
\r
213 if (Properties.Settings.Default.useM4v || mainWindow.Check_ChapterMarkers.Checked ||
\r
214 mainWindow.AudioSettings.RequiresM4V() || mainWindow.Subtitles.RequiresM4V())
\r
215 destinationFilename += ".m4v";
\r
217 destinationFilename += ".mp4";
\r
219 else if (mainWindow.drop_format.SelectedIndex == 1)
\r
220 destinationFilename += ".mkv";
\r
222 // Now work out the path where the file will be stored.
\r
223 // First case: If the destination box doesn't already contain a path, make one.
\r
224 if (!mainWindow.text_destination.Text.Contains(Path.DirectorySeparatorChar.ToString()))
\r
226 // If there is an auto name path, use it...
\r
227 if (Properties.Settings.Default.autoNamePath.Trim() != string.Empty &&
\r
228 Properties.Settings.Default.autoNamePath.Trim() != "Click 'Browse' to set the default location")
\r
229 autoNamePath = Path.Combine(Properties.Settings.Default.autoNamePath, destinationFilename);
\r
230 else // ...otherwise, output to the source directory
\r
231 autoNamePath = null;
\r
233 else // Otherwise, use the path that is already there.
\r
235 // Use the path and change the file extension to match the previous destination
\r
236 autoNamePath = Path.Combine(Path.GetDirectoryName(mainWindow.text_destination.Text), destinationFilename);
\r
238 if (Path.HasExtension(mainWindow.text_destination.Text))
\r
239 autoNamePath = Path.ChangeExtension(autoNamePath, Path.GetExtension(mainWindow.text_destination.Text));
\r
243 return autoNamePath;
\r
247 /// Get's HandBrakes version data from the CLI.
\r
249 public static void SetCliVersionData()
\r
253 // 0 = SVN Build / Version
\r
255 DateTime lastModified = File.GetLastWriteTime("HandBrakeCLI.exe");
\r
257 if (Properties.Settings.Default.cliLastModified == lastModified && Properties.Settings.Default.hb_build != 0)
\r
260 Properties.Settings.Default.cliLastModified = lastModified;
\r
262 Process cliProcess = new Process();
\r
263 ProcessStartInfo handBrakeCli = new ProcessStartInfo("HandBrakeCLI.exe", " -u -v0")
\r
265 UseShellExecute = false,
\r
266 RedirectStandardError = true,
\r
267 RedirectStandardOutput = true,
\r
268 CreateNoWindow = true
\r
270 cliProcess.StartInfo = handBrakeCli;
\r
274 cliProcess.Start();
\r
276 // Retrieve standard output and report back to parent thread until the process is complete
\r
277 TextReader stdOutput = cliProcess.StandardError;
\r
279 while (!cliProcess.HasExited)
\r
281 line = stdOutput.ReadLine() ?? string.Empty;
\r
282 Match m = Regex.Match(line, @"HandBrake ([svnM0-9.]*) \([0-9]*\)");
\r
283 Match platform = Regex.Match(line, @"- ([A-Za-z0-9\s ]*) -");
\r
287 string data = line.Replace("(", string.Empty).Replace(")", string.Empty).Replace("HandBrake ", string.Empty);
\r
288 string[] arr = data.Split(' ');
\r
290 Properties.Settings.Default.hb_build = int.Parse(arr[1]);
\r
291 Properties.Settings.Default.hb_version = arr[0];
\r
294 if (platform.Success)
\r
296 Properties.Settings.Default.hb_platform = platform.Value.Replace("-", string.Empty).Trim();
\r
299 if (cliProcess.TotalProcessorTime.Seconds > 10) // Don't wait longer than 10 seconds.
\r
301 Process cli = Process.GetProcessById(cliProcess.Id);
\r
302 if (!cli.HasExited)
\r
309 Properties.Settings.Default.Save();
\r
311 catch (Exception e)
\r
313 MessageBox.Show("Unable to retrieve version information from the CLI. \nError:\n" + e);
\r
318 /// Check if the queue recovery file contains records.
\r
319 /// If it does, it means the last queue did not complete before HandBrake closed.
\r
320 /// So, return a boolean if true.
\r
323 /// True if there is a queue to recover.
\r
325 public static bool CheckQueueRecovery()
\r
329 string tempPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), @"HandBrake\hb_queue_recovery.xml");
\r
330 if (File.Exists(tempPath))
\r
332 using (FileStream strm = new FileStream(tempPath, FileMode.Open, FileAccess.Read))
\r
334 List<Job> list = Ser.Deserialize(strm) as List<Job>;
\r
336 if (list.Count != 0)
\r
344 return false; // Keep quiet about the error.
\r
349 /// Get the Process ID of HandBrakeCLI for the current instance.
\r
351 /// <param name="before">List of processes before the new process was started</param>
\r
352 /// <returns>Int - Process ID</returns>
\r
353 public static int GetCliProcess(Process[] before)
\r
355 // This is a bit of a cludge. Maybe someone has a better idea on how to impliment this.
\r
356 // Since we used CMD to start HandBrakeCLI, we don't get the process ID from hbProc.
\r
357 // Instead we take the processes before and after, and get the ID of HandBrakeCLI.exe
\r
358 // avoiding any previous instances of HandBrakeCLI.exe in before.
\r
359 // Kill the current process.
\r
361 DateTime startTime = DateTime.Now;
\r
364 Process[] hbProcesses = Process.GetProcessesByName("HandBrakeCLI");
\r
365 while (hbProcesses.Length == 0)
\r
367 hbProcesses = Process.GetProcessesByName("HandBrakeCLI");
\r
368 duration = DateTime.Now - startTime;
\r
369 if (duration.Seconds > 5 && hbProcesses.Length == 0)
\r
370 // Make sure we don't wait forever if the process doesn't start
\r
374 Process hbProcess = null;
\r
375 foreach (Process process in hbProcesses)
\r
377 bool found = false;
\r
378 // Check if the current CLI instance was running before we started the current one
\r
379 foreach (Process bprocess in before)
\r
381 if (process.Id == bprocess.Id)
\r
385 // If it wasn't running before, we found the process we want.
\r
388 hbProcess = process;
\r
392 if (hbProcess != null)
\r
393 return hbProcess.Id;
\r
399 /// Clear all the encode log files.
\r
401 public static void ClearLogs()
\r
403 string logDir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\HandBrake\\logs";
\r
404 if (Directory.Exists(logDir))
\r
406 DirectoryInfo info = new DirectoryInfo(logDir);
\r
407 FileInfo[] logFiles = info.GetFiles("*.txt");
\r
408 foreach (FileInfo file in logFiles)
\r
410 if (!file.Name.Contains("last_scan_log") && !file.Name.Contains("last_encode_log") &&
\r
411 !file.Name.Contains("tmp_appReadable_log.txt"))
\r
412 File.Delete(file.FullName);
\r
418 /// Clear old log files x days in the past
\r
420 public static void ClearOldLogs()
\r
422 string logDir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\HandBrake\\logs";
\r
423 if (Directory.Exists(logDir))
\r
425 DirectoryInfo info = new DirectoryInfo(logDir);
\r
426 FileInfo[] logFiles = info.GetFiles("*.txt");
\r
428 foreach (FileInfo file in logFiles)
\r
430 if (file.LastWriteTime < DateTime.Now.AddDays(-30))
\r
432 if (!file.Name.Contains("last_scan_log") && !file.Name.Contains("last_encode_log") &&
\r
433 !file.Name.Contains("tmp_appReadable_log.txt"))
\r
434 File.Delete(file.FullName);
\r
441 /// Begins checking for an update to HandBrake.
\r
443 /// <param name="callback">The method that will be called when the check is finished.</param>
\r
444 /// <param name="debug">Whether or not to execute this in debug mode.</param>
\r
445 public static void BeginCheckForUpdates(AsyncCallback callback, bool debug)
\r
447 ThreadPool.QueueUserWorkItem(new WaitCallback(delegate
\r
451 // Is this a stable or unstable build?
\r
453 Properties.Settings.Default.hb_build.ToString()
\r
455 ? Properties.Settings.Default.
\r
457 : Properties.Settings.Default.appcast;
\r
459 // Initialize variables
\r
460 WebRequest request = WebRequest.Create(url);
\r
461 WebResponse response = request.GetResponse();
\r
462 AppcastReader reader = new AppcastReader();
\r
464 // Get the data, convert it to a string, and parse it into the AppcastReader
\r
466 new StreamReader(response.GetResponseStream())
\r
469 // Further parse the information
\r
470 string build = reader.Build;
\r
472 int latest = int.Parse(build);
\r
473 int current = Properties.Settings.Default.hb_build;
\r
474 int skip = Properties.Settings.Default.skipversion;
\r
476 // If the user wanted to skip this version, don't report the update
\r
477 if (latest == skip)
\r
479 UpdateCheckInformation info =
\r
480 new UpdateCheckInformation
\r
482 NewVersionAvailable = false,
\r
483 BuildInformation = null
\r
485 callback(new UpdateCheckResult(debug, info));
\r
489 // Set when the last update was
\r
490 Properties.Settings.Default.lastUpdateCheckDate =
\r
492 Properties.Settings.Default.Save();
\r
494 UpdateCheckInformation info2 =
\r
495 new UpdateCheckInformation
\r
497 NewVersionAvailable = latest > current,
\r
498 BuildInformation = reader
\r
500 callback(new UpdateCheckResult(debug, info2));
\r
502 catch (Exception exc)
\r
504 callback(new UpdateCheckResult(debug, new UpdateCheckInformation { Error = exc }));
\r
510 /// End Check for Updates
\r
512 /// <param name="result">
\r
516 /// Update Check information
\r
518 public static UpdateCheckInformation EndCheckForUpdates(IAsyncResult result)
\r
520 UpdateCheckResult checkResult = (UpdateCheckResult)result;
\r
521 return checkResult.Result;
\r
525 /// Map languages and their iso639_2 value into a IDictionary
\r
527 /// <returns>A Dictionary containing the language and iso code</returns>
\r
528 public static IDictionary<string, string> MapLanguages()
\r
530 IDictionary<string, string> languageMap = new Dictionary<string, string>
\r
534 {"Abkhazian", "abk"},
\r
535 {"Afrikaans", "afr"},
\r
537 {"Albanian", "sqi"},
\r
538 {"Amharic", "amh"},
\r
539 {"Arabic", "ara"},
\r
540 {"Aragonese", "arg"},
\r
541 {"Armenian", "hye"},
\r
542 {"Assamese", "asm"},
\r
543 {"Avaric", "ava"},
\r
544 {"Avestan", "ave"},
\r
545 {"Aymara", "aym"},
\r
546 {"Azerbaijani", "aze"},
\r
547 {"Bashkir", "bak"},
\r
548 {"Bambara", "bam"},
\r
549 {"Basque", "eus"},
\r
550 {"Belarusian", "bel"},
\r
551 {"Bengali", "ben"},
\r
552 {"Bihari", "bih"},
\r
553 {"Bislama", "bis"},
\r
554 {"Bosnian", "bos"},
\r
555 {"Breton", "bre"},
\r
556 {"Bulgarian", "bul"},
\r
557 {"Burmese", "mya"},
\r
558 {"Catalan", "cat"},
\r
559 {"Chamorro", "cha"},
\r
560 {"Chechen", "che"},
\r
561 {"Chinese", "zho"},
\r
562 {"Church Slavic", "chu"},
\r
563 {"Chuvash", "chv"},
\r
564 {"Cornish", "cor"},
\r
565 {"Corsican", "cos"},
\r
569 {"Divehi", "div"},
\r
570 {"Nederlands", "nld"},
\r
571 {"Dzongkha", "dzo"},
\r
572 {"English", "eng"},
\r
573 {"Esperanto", "epo"},
\r
574 {"Estonian", "est"},
\r
576 {"Faroese", "fao"},
\r
577 {"Fijian", "fij"},
\r
579 {"Francais", "fra"},
\r
580 {"Western Frisian", "fry"},
\r
582 {"Georgian", "kat"},
\r
583 {"Deutsch", "deu"},
\r
584 {"Gaelic (Scots)", "gla"},
\r
586 {"Galician", "glg"},
\r
588 {"Greek Modern", "ell"},
\r
589 {"Guarani", "grn"},
\r
590 {"Gujarati", "guj"},
\r
591 {"Haitian", "hat"},
\r
593 {"Hebrew", "heb"},
\r
594 {"Herero", "her"},
\r
596 {"Hiri Motu", "hmo"},
\r
597 {"Magyar", "hun"},
\r
599 {"Islenska", "isl"},
\r
601 {"Sichuan Yi", "iii"},
\r
602 {"Inuktitut", "iku"},
\r
603 {"Interlingue", "ile"},
\r
604 {"Interlingua", "ina"},
\r
605 {"Indonesian", "ind"},
\r
606 {"Inupiaq", "ipk"},
\r
607 {"Italiano", "ita"},
\r
608 {"Javanese", "jav"},
\r
609 {"Japanese", "jpn"},
\r
610 {"Kalaallisut", "kal"},
\r
611 {"Kannada", "kan"},
\r
612 {"Kashmiri", "kas"},
\r
613 {"Kanuri", "kau"},
\r
614 {"Kazakh", "kaz"},
\r
615 {"Central Khmer", "khm"},
\r
616 {"Kikuyu", "kik"},
\r
617 {"Kinyarwanda", "kin"},
\r
618 {"Kirghiz", "kir"},
\r
621 {"Korean", "kor"},
\r
622 {"Kuanyama", "kua"},
\r
623 {"Kurdish", "kur"},
\r
626 {"Latvian", "lav"},
\r
627 {"Limburgan", "lim"},
\r
628 {"Lingala", "lin"},
\r
629 {"Lithuanian", "lit"},
\r
630 {"Luxembourgish", "ltz"},
\r
631 {"Luba-Katanga", "lub"},
\r
633 {"Macedonian", "mkd"},
\r
634 {"Marshallese", "mah"},
\r
635 {"Malayalam", "mal"},
\r
637 {"Marathi", "mar"},
\r
639 {"Malagasy", "mlg"},
\r
640 {"Maltese", "mlt"},
\r
641 {"Moldavian", "mol"},
\r
642 {"Mongolian", "mon"},
\r
644 {"Navajo", "nav"},
\r
645 {"Ndebele, South", "nbl"},
\r
646 {"Ndebele, North", "nde"},
\r
647 {"Ndonga", "ndo"},
\r
648 {"Nepali", "nep"},
\r
649 {"Norwegian Nynorsk", "nno"},
\r
650 {"Norwegian Bokmål", "nob"},
\r
652 {"Chichewa; Nyanja", "nya"},
\r
653 {"Occitan", "oci"},
\r
654 {"Ojibwa", "oji"},
\r
657 {"Ossetian", "oss"},
\r
658 {"Panjabi", "pan"},
\r
659 {"Persian", "fas"},
\r
661 {"Polish", "pol"},
\r
662 {"Portugues", "por"},
\r
663 {"Pushto", "pus"},
\r
664 {"Quechua", "que"},
\r
665 {"Romansh", "roh"},
\r
666 {"Romanian", "ron"},
\r
668 {"Russian", "rus"},
\r
670 {"Sanskrit", "san"},
\r
671 {"Serbian", "srp"},
\r
672 {"Hrvatski", "hrv"},
\r
673 {"Sinhala", "sin"},
\r
674 {"Slovak", "slk"},
\r
675 {"Slovenian", "slv"},
\r
676 {"Northern Sami", "sme"},
\r
677 {"Samoan", "smo"},
\r
679 {"Sindhi", "snd"},
\r
680 {"Somali", "som"},
\r
681 {"Sotho Southern", "sot"},
\r
682 {"Espanol", "spa"},
\r
683 {"Sardinian", "srd"},
\r
685 {"Sundanese", "sun"},
\r
686 {"Swahili", "swa"},
\r
687 {"Svenska", "swe"},
\r
688 {"Tahitian", "tah"},
\r
691 {"Telugu", "tel"},
\r
693 {"Tagalog", "tgl"},
\r
695 {"Tibetan", "bod"},
\r
696 {"Tigrinya", "tir"},
\r
698 {"Tswana", "tsn"},
\r
699 {"Tsonga", "tso"},
\r
700 {"Turkmen", "tuk"},
\r
701 {"Turkish", "tur"},
\r
703 {"Uighur", "uig"},
\r
704 {"Ukrainian", "ukr"},
\r
708 {"Vietnamese", "vie"},
\r
709 {"Volapük", "vol"},
\r
711 {"Walloon", "wln"},
\r
714 {"Yiddish", "yid"},
\r
715 {"Yoruba", "yor"},
\r
716 {"Zhuang", "zha"},
\r
719 return languageMap;
\r
723 /// Get a list of available DVD drives which are ready and contain DVD content.
\r
725 /// <returns>A List of Drives with their details</returns>
\r
726 public static List<DriveInformation> GetDrives()
\r
728 List<DriveInformation> drives = new List<DriveInformation>();
\r
729 DriveInfo[] theCollectionOfDrives = DriveInfo.GetDrives();
\r
731 foreach (DriveInfo curDrive in theCollectionOfDrives)
\r
733 if (curDrive.DriveType == DriveType.CDRom && curDrive.IsReady &&
\r
734 File.Exists(curDrive.RootDirectory + "VIDEO_TS\\VIDEO_TS.IFO"))
\r
736 drives.Add(new DriveInformation
\r
739 VolumeLabel = curDrive.VolumeLabel,
\r
740 RootDirectory = curDrive.RootDirectory + "VIDEO_TS"
\r
749 /// Change a string to Title Case/
\r
751 /// <param name="input">
\r
755 /// A string in title case.
\r
757 public static string TitleCase(string input)
\r
759 string[] tokens = input.Split(' ');
\r
760 StringBuilder sb = new StringBuilder(input.Length);
\r
761 foreach (string s in tokens)
\r
763 sb.Append(s[0].ToString().ToUpper());
\r
764 sb.Append(s.Substring(1).ToLower());
\r
768 return sb.ToString().Trim();
\r