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 /// Set's up the DataGridView on the Chapters tab (frmMain)
\r
64 /// <param name="dataChpt">
\r
65 /// The DataGridView Control
\r
67 /// <param name="chapterEnd">
\r
68 /// The chapter End.
\r
71 /// The chapter naming.
\r
73 public static DataGridView ChapterNaming(DataGridView dataChpt, string chapterEnd)
\r
75 int i = 0, finish = 0;
\r
77 if (chapterEnd != "Auto")
\r
78 int.TryParse(chapterEnd, out finish);
\r
82 int n = dataChpt.Rows.Add();
\r
83 dataChpt.Rows[n].Cells[0].Value = i + 1;
\r
84 dataChpt.Rows[n].Cells[1].Value = "Chapter " + (i + 1);
\r
85 dataChpt.Rows[n].Cells[0].ValueType = typeof(int);
\r
86 dataChpt.Rows[n].Cells[1].ValueType = typeof(string);
\r
94 /// Import a CSV file which contains Chapter Names
\r
96 /// <param name="dataChpt">
\r
97 /// The DataGridView Control
\r
99 /// <param name="filename">
\r
100 /// The filepath and name
\r
102 /// <returns>A Populated DataGridView</returns>
\r
103 public static DataGridView ImportChapterNames(DataGridView dataChpt, string filename)
\r
105 IDictionary<int, string> chapterMap = new Dictionary<int, string>();
\r
108 StreamReader sr = new StreamReader(filename);
\r
109 string csv = sr.ReadLine();
\r
110 while (csv != null)
\r
112 if (csv.Trim() != string.Empty)
\r
114 csv = csv.Replace("\\,", "<!comma!>");
\r
115 string[] contents = csv.Split(',');
\r
117 int.TryParse(contents[0], out chapter);
\r
118 chapterMap.Add(chapter, contents[1].Replace("<!comma!>", ","));
\r
120 csv = sr.ReadLine();
\r
128 foreach (DataGridViewRow item in dataChpt.Rows)
\r
131 chapterMap.TryGetValue((int)item.Cells[0].Value, out name);
\r
132 item.Cells[1].Value = name ?? "Chapter " + item.Cells[0].Value;
\r
139 /// Function which generates the filename and path automatically based on
\r
140 /// the Source Name, DVD title and DVD Chapters
\r
142 /// <param name="mainWindow">
\r
143 /// The main Window.
\r
146 /// The Generated FileName
\r
148 public static string AutoName(frmMain mainWindow)
\r
150 string autoNamePath = string.Empty;
\r
151 if (mainWindow.drp_dvdtitle.Text != "Automatic")
\r
153 // Get the Source Name
\r
154 string sourceName = mainWindow.SourceName;
\r
156 if (Properties.Settings.Default.AutoNameRemoveUnderscore)
\r
157 sourceName = sourceName.Replace("_", " ");
\r
159 if (Properties.Settings.Default.AutoNameTitleCase)
\r
160 sourceName = TitleCase(sourceName);
\r
162 // Get the Selected Title Number
\r
163 string[] titlesplit = mainWindow.drp_dvdtitle.Text.Split(' ');
\r
164 string dvdTitle = titlesplit[0].Replace("Automatic", string.Empty);
\r
166 // Get the Chapter Start and Chapter End Numbers
\r
167 string chapterStart = mainWindow.drop_chapterStart.Text.Replace("Auto", string.Empty);
\r
168 string chapterFinish = mainWindow.drop_chapterFinish.Text.Replace("Auto", string.Empty);
\r
169 string combinedChapterTag = chapterStart;
\r
170 if (chapterFinish != chapterStart && chapterFinish != string.Empty)
\r
171 combinedChapterTag = chapterStart + "-" + chapterFinish;
\r
173 // Get the destination filename.
\r
174 string destinationFilename;
\r
175 if (Properties.Settings.Default.autoNameFormat != string.Empty)
\r
177 destinationFilename = Properties.Settings.Default.autoNameFormat;
\r
178 destinationFilename =
\r
179 destinationFilename.Replace("{source}", sourceName).Replace("{title}", dvdTitle).Replace(
\r
180 "{chapters}", combinedChapterTag);
\r
183 destinationFilename = sourceName + "_T" + dvdTitle + "_C" + combinedChapterTag;
\r
185 // Add the appropriate file extension
\r
186 if (mainWindow.drop_format.SelectedIndex == 0)
\r
188 if (Properties.Settings.Default.useM4v || mainWindow.Check_ChapterMarkers.Checked ||
\r
189 mainWindow.AudioSettings.RequiresM4V() || mainWindow.Subtitles.RequiresM4V())
\r
190 destinationFilename += ".m4v";
\r
192 destinationFilename += ".mp4";
\r
194 else if (mainWindow.drop_format.SelectedIndex == 1)
\r
195 destinationFilename += ".mkv";
\r
197 // Now work out the path where the file will be stored.
\r
198 // First case: If the destination box doesn't already contain a path, make one.
\r
199 if (!mainWindow.text_destination.Text.Contains(Path.DirectorySeparatorChar.ToString()))
\r
201 // If there is an auto name path, use it...
\r
202 if (Properties.Settings.Default.autoNamePath.Trim() != string.Empty &&
\r
203 Properties.Settings.Default.autoNamePath.Trim() != "Click 'Browse' to set the default location")
\r
204 autoNamePath = Path.Combine(Properties.Settings.Default.autoNamePath, destinationFilename);
\r
205 else // ...otherwise, output to the source directory
\r
206 autoNamePath = null;
\r
208 else // Otherwise, use the path that is already there.
\r
210 // Use the path and change the file extension to match the previous destination
\r
211 autoNamePath = Path.Combine(Path.GetDirectoryName(mainWindow.text_destination.Text), destinationFilename);
\r
213 if (Path.HasExtension(mainWindow.text_destination.Text))
\r
214 autoNamePath = Path.ChangeExtension(autoNamePath, Path.GetExtension(mainWindow.text_destination.Text));
\r
218 return autoNamePath;
\r
222 /// Get's HandBrakes version data from the CLI.
\r
224 public static void SetCliVersionData()
\r
228 // 0 = SVN Build / Version
\r
230 DateTime lastModified = File.GetLastWriteTime("HandBrakeCLI.exe");
\r
232 if (Properties.Settings.Default.cliLastModified == lastModified && Properties.Settings.Default.hb_build != 0)
\r
235 Properties.Settings.Default.cliLastModified = lastModified;
\r
237 Process cliProcess = new Process();
\r
238 ProcessStartInfo handBrakeCli = new ProcessStartInfo("HandBrakeCLI.exe", " -u -v0")
\r
240 UseShellExecute = false,
\r
241 RedirectStandardError = true,
\r
242 RedirectStandardOutput = true,
\r
243 CreateNoWindow = true
\r
245 cliProcess.StartInfo = handBrakeCli;
\r
249 cliProcess.Start();
\r
251 // Retrieve standard output and report back to parent thread until the process is complete
\r
252 TextReader stdOutput = cliProcess.StandardError;
\r
254 while (!cliProcess.HasExited)
\r
256 line = stdOutput.ReadLine() ?? string.Empty;
\r
257 Match m = Regex.Match(line, @"HandBrake ([svnM0-9.]*) \([0-9]*\)");
\r
258 Match platform = Regex.Match(line, @"- ([A-Za-z0-9\s ]*) -");
\r
262 string data = line.Replace("(", string.Empty).Replace(")", string.Empty).Replace("HandBrake ", string.Empty);
\r
263 string[] arr = data.Split(' ');
\r
265 Properties.Settings.Default.hb_build = int.Parse(arr[1]);
\r
266 Properties.Settings.Default.hb_version = arr[0];
\r
269 if (platform.Success)
\r
271 Properties.Settings.Default.hb_platform = platform.Value.Replace("-", string.Empty).Trim();
\r
274 if (cliProcess.TotalProcessorTime.Seconds > 10) // Don't wait longer than 10 seconds.
\r
276 Process cli = Process.GetProcessById(cliProcess.Id);
\r
277 if (!cli.HasExited)
\r
284 Properties.Settings.Default.Save();
\r
286 catch (Exception e)
\r
288 MessageBox.Show("Unable to retrieve version information from the CLI. \nError:\n" + e);
\r
293 /// Check to make sure that the user has an up to date version of the CLI installed.
\r
295 public static void CheckForValidCliVersion()
\r
297 // Make sure we have a recent version for svn builds
\r
298 string version = Properties.Settings.Default.hb_version;
\r
299 if (version.Contains("svn"))
\r
301 version = version.Replace("svn", string.Empty).Trim();
\r
303 int.TryParse(version, out build);
\r
304 if (build < Properties.Settings.Default.hb_min_cli)
\r
307 "It appears you are trying to use a CLI executable that is too old for this version of the HandBrake GUI.\n" +
\r
308 "Please update the HandBrakeCLI.exe to a newer build.\n\n" +
\r
309 "HandBrake Detected: " + Properties.Settings.Default.hb_version,
\r
311 MessageBoxButtons.OK,
\r
312 MessageBoxIcon.Error);
\r
319 /// Check if the queue recovery file contains records.
\r
320 /// If it does, it means the last queue did not complete before HandBrake closed.
\r
321 /// So, return a boolean if true.
\r
324 /// True if there is a queue to recover.
\r
326 public static bool CheckQueueRecovery()
\r
330 string tempPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), @"HandBrake\hb_queue_recovery.xml");
\r
331 if (File.Exists(tempPath))
\r
333 using (FileStream strm = new FileStream(tempPath, FileMode.Open, FileAccess.Read))
\r
335 List<Job> list = Ser.Deserialize(strm) as List<Job>;
\r
337 if (list.Count != 0)
\r
345 return false; // Keep quiet about the error.
\r
350 /// Get the Process ID of HandBrakeCLI for the current instance.
\r
352 /// <param name="before">List of processes before the new process was started</param>
\r
353 /// <returns>Int - Process ID</returns>
\r
354 public static int GetCliProcess(Process[] before)
\r
356 // This is a bit of a cludge. Maybe someone has a better idea on how to impliment this.
\r
357 // Since we used CMD to start HandBrakeCLI, we don't get the process ID from hbProc.
\r
358 // Instead we take the processes before and after, and get the ID of HandBrakeCLI.exe
\r
359 // avoiding any previous instances of HandBrakeCLI.exe in before.
\r
360 // Kill the current process.
\r
362 DateTime startTime = DateTime.Now;
\r
365 Process[] hbProcesses = Process.GetProcessesByName("HandBrakeCLI");
\r
366 while (hbProcesses.Length == 0)
\r
368 hbProcesses = Process.GetProcessesByName("HandBrakeCLI");
\r
369 duration = DateTime.Now - startTime;
\r
370 if (duration.Seconds > 5 && hbProcesses.Length == 0)
\r
371 // Make sure we don't wait forever if the process doesn't start
\r
375 Process hbProcess = null;
\r
376 foreach (Process process in hbProcesses)
\r
378 bool found = false;
\r
379 // Check if the current CLI instance was running before we started the current one
\r
380 foreach (Process bprocess in before)
\r
382 if (process.Id == bprocess.Id)
\r
386 // If it wasn't running before, we found the process we want.
\r
389 hbProcess = process;
\r
393 if (hbProcess != null)
\r
394 return hbProcess.Id;
\r
400 /// Clear all the encode log files.
\r
402 public static void ClearLogs()
\r
404 string logDir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\HandBrake\\logs";
\r
405 if (Directory.Exists(logDir))
\r
407 DirectoryInfo info = new DirectoryInfo(logDir);
\r
408 FileInfo[] logFiles = info.GetFiles("*.txt");
\r
409 foreach (FileInfo file in logFiles)
\r
411 if (!file.Name.Contains("last_scan_log") && !file.Name.Contains("last_encode_log") &&
\r
412 !file.Name.Contains("tmp_appReadable_log.txt"))
\r
413 File.Delete(file.FullName);
\r
419 /// Clear old log files x days in the past
\r
421 public static void ClearOldLogs()
\r
423 string logDir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\HandBrake\\logs";
\r
424 if (Directory.Exists(logDir))
\r
426 DirectoryInfo info = new DirectoryInfo(logDir);
\r
427 FileInfo[] logFiles = info.GetFiles("*.txt");
\r
429 foreach (FileInfo file in logFiles)
\r
431 if (file.LastWriteTime < DateTime.Now.AddDays(-30))
\r
433 if (!file.Name.Contains("last_scan_log") && !file.Name.Contains("last_encode_log") &&
\r
434 !file.Name.Contains("tmp_appReadable_log.txt"))
\r
435 File.Delete(file.FullName);
\r
442 /// Begins checking for an update to HandBrake.
\r
444 /// <param name="callback">The method that will be called when the check is finished.</param>
\r
445 /// <param name="debug">Whether or not to execute this in debug mode.</param>
\r
446 public static void BeginCheckForUpdates(AsyncCallback callback, bool debug)
\r
448 ThreadPool.QueueUserWorkItem(new WaitCallback(delegate
\r
452 // Is this a stable or unstable build?
\r
454 Properties.Settings.Default.hb_build.ToString()
\r
456 ? Properties.Settings.Default.
\r
458 : Properties.Settings.Default.appcast;
\r
460 // Initialize variables
\r
461 WebRequest request = WebRequest.Create(url);
\r
462 WebResponse response = request.GetResponse();
\r
463 AppcastReader reader = new AppcastReader();
\r
465 // Get the data, convert it to a string, and parse it into the AppcastReader
\r
467 new StreamReader(response.GetResponseStream())
\r
470 // Further parse the information
\r
471 string build = reader.Build;
\r
473 int latest = int.Parse(build);
\r
474 int current = Properties.Settings.Default.hb_build;
\r
475 int skip = Properties.Settings.Default.skipversion;
\r
477 // If the user wanted to skip this version, don't report the update
\r
478 if (latest == skip)
\r
480 UpdateCheckInformation info =
\r
481 new UpdateCheckInformation
\r
483 NewVersionAvailable = false,
\r
484 BuildInformation = null
\r
486 callback(new UpdateCheckResult(debug, info));
\r
490 // Set when the last update was
\r
491 Properties.Settings.Default.lastUpdateCheckDate =
\r
493 Properties.Settings.Default.Save();
\r
495 UpdateCheckInformation info2 =
\r
496 new UpdateCheckInformation
\r
498 NewVersionAvailable = latest > current,
\r
499 BuildInformation = reader
\r
501 callback(new UpdateCheckResult(debug, info2));
\r
503 catch (Exception exc)
\r
505 callback(new UpdateCheckResult(debug, new UpdateCheckInformation { Error = exc }));
\r
511 /// End Check for Updates
\r
513 /// <param name="result">
\r
517 /// Update Check information
\r
519 public static UpdateCheckInformation EndCheckForUpdates(IAsyncResult result)
\r
521 UpdateCheckResult checkResult = (UpdateCheckResult)result;
\r
522 return checkResult.Result;
\r
526 /// Map languages and their iso639_2 value into a IDictionary
\r
528 /// <returns>A Dictionary containing the language and iso code</returns>
\r
529 public static IDictionary<string, string> MapLanguages()
\r
531 IDictionary<string, string> languageMap = new Dictionary<string, string>
\r
535 {"Abkhazian", "abk"},
\r
536 {"Afrikaans", "afr"},
\r
538 {"Albanian", "sqi"},
\r
539 {"Amharic", "amh"},
\r
540 {"Arabic", "ara"},
\r
541 {"Aragonese", "arg"},
\r
542 {"Armenian", "hye"},
\r
543 {"Assamese", "asm"},
\r
544 {"Avaric", "ava"},
\r
545 {"Avestan", "ave"},
\r
546 {"Aymara", "aym"},
\r
547 {"Azerbaijani", "aze"},
\r
548 {"Bashkir", "bak"},
\r
549 {"Bambara", "bam"},
\r
550 {"Basque", "eus"},
\r
551 {"Belarusian", "bel"},
\r
552 {"Bengali", "ben"},
\r
553 {"Bihari", "bih"},
\r
554 {"Bislama", "bis"},
\r
555 {"Bosnian", "bos"},
\r
556 {"Breton", "bre"},
\r
557 {"Bulgarian", "bul"},
\r
558 {"Burmese", "mya"},
\r
559 {"Catalan", "cat"},
\r
560 {"Chamorro", "cha"},
\r
561 {"Chechen", "che"},
\r
562 {"Chinese", "zho"},
\r
563 {"Church Slavic", "chu"},
\r
564 {"Chuvash", "chv"},
\r
565 {"Cornish", "cor"},
\r
566 {"Corsican", "cos"},
\r
570 {"Divehi", "div"},
\r
571 {"Nederlands", "nld"},
\r
572 {"Dzongkha", "dzo"},
\r
573 {"English", "eng"},
\r
574 {"Esperanto", "epo"},
\r
575 {"Estonian", "est"},
\r
577 {"Faroese", "fao"},
\r
578 {"Fijian", "fij"},
\r
580 {"Francais", "fra"},
\r
581 {"Western Frisian", "fry"},
\r
583 {"Georgian", "kat"},
\r
584 {"Deutsch", "deu"},
\r
585 {"Gaelic (Scots)", "gla"},
\r
587 {"Galician", "glg"},
\r
589 {"Greek Modern", "ell"},
\r
590 {"Guarani", "grn"},
\r
591 {"Gujarati", "guj"},
\r
592 {"Haitian", "hat"},
\r
594 {"Hebrew", "heb"},
\r
595 {"Herero", "her"},
\r
597 {"Hiri Motu", "hmo"},
\r
598 {"Magyar", "hun"},
\r
600 {"Islenska", "isl"},
\r
602 {"Sichuan Yi", "iii"},
\r
603 {"Inuktitut", "iku"},
\r
604 {"Interlingue", "ile"},
\r
605 {"Interlingua", "ina"},
\r
606 {"Indonesian", "ind"},
\r
607 {"Inupiaq", "ipk"},
\r
608 {"Italiano", "ita"},
\r
609 {"Javanese", "jav"},
\r
610 {"Japanese", "jpn"},
\r
611 {"Kalaallisut", "kal"},
\r
612 {"Kannada", "kan"},
\r
613 {"Kashmiri", "kas"},
\r
614 {"Kanuri", "kau"},
\r
615 {"Kazakh", "kaz"},
\r
616 {"Central Khmer", "khm"},
\r
617 {"Kikuyu", "kik"},
\r
618 {"Kinyarwanda", "kin"},
\r
619 {"Kirghiz", "kir"},
\r
622 {"Korean", "kor"},
\r
623 {"Kuanyama", "kua"},
\r
624 {"Kurdish", "kur"},
\r
627 {"Latvian", "lav"},
\r
628 {"Limburgan", "lim"},
\r
629 {"Lingala", "lin"},
\r
630 {"Lithuanian", "lit"},
\r
631 {"Luxembourgish", "ltz"},
\r
632 {"Luba-Katanga", "lub"},
\r
634 {"Macedonian", "mkd"},
\r
635 {"Marshallese", "mah"},
\r
636 {"Malayalam", "mal"},
\r
638 {"Marathi", "mar"},
\r
640 {"Malagasy", "mlg"},
\r
641 {"Maltese", "mlt"},
\r
642 {"Moldavian", "mol"},
\r
643 {"Mongolian", "mon"},
\r
645 {"Navajo", "nav"},
\r
646 {"Ndebele, South", "nbl"},
\r
647 {"Ndebele, North", "nde"},
\r
648 {"Ndonga", "ndo"},
\r
649 {"Nepali", "nep"},
\r
650 {"Norwegian Nynorsk", "nno"},
\r
651 {"Norwegian Bokmål", "nob"},
\r
653 {"Chichewa; Nyanja", "nya"},
\r
654 {"Occitan", "oci"},
\r
655 {"Ojibwa", "oji"},
\r
658 {"Ossetian", "oss"},
\r
659 {"Panjabi", "pan"},
\r
660 {"Persian", "fas"},
\r
662 {"Polish", "pol"},
\r
663 {"Portugues", "por"},
\r
664 {"Pushto", "pus"},
\r
665 {"Quechua", "que"},
\r
666 {"Romansh", "roh"},
\r
667 {"Romanian", "ron"},
\r
669 {"Russian", "rus"},
\r
671 {"Sanskrit", "san"},
\r
672 {"Serbian", "srp"},
\r
673 {"Hrvatski", "hrv"},
\r
674 {"Sinhala", "sin"},
\r
675 {"Slovak", "slk"},
\r
676 {"Slovenian", "slv"},
\r
677 {"Northern Sami", "sme"},
\r
678 {"Samoan", "smo"},
\r
680 {"Sindhi", "snd"},
\r
681 {"Somali", "som"},
\r
682 {"Sotho Southern", "sot"},
\r
683 {"Espanol", "spa"},
\r
684 {"Sardinian", "srd"},
\r
686 {"Sundanese", "sun"},
\r
687 {"Swahili", "swa"},
\r
688 {"Svenska", "swe"},
\r
689 {"Tahitian", "tah"},
\r
692 {"Telugu", "tel"},
\r
694 {"Tagalog", "tgl"},
\r
696 {"Tibetan", "bod"},
\r
697 {"Tigrinya", "tir"},
\r
699 {"Tswana", "tsn"},
\r
700 {"Tsonga", "tso"},
\r
701 {"Turkmen", "tuk"},
\r
702 {"Turkish", "tur"},
\r
704 {"Uighur", "uig"},
\r
705 {"Ukrainian", "ukr"},
\r
709 {"Vietnamese", "vie"},
\r
710 {"Volapük", "vol"},
\r
712 {"Walloon", "wln"},
\r
715 {"Yiddish", "yid"},
\r
716 {"Yoruba", "yor"},
\r
717 {"Zhuang", "zha"},
\r
720 return languageMap;
\r
724 /// Get a list of available DVD drives which are ready and contain DVD content.
\r
726 /// <returns>A List of Drives with their details</returns>
\r
727 public static List<DriveInformation> GetDrives()
\r
729 List<DriveInformation> drives = new List<DriveInformation>();
\r
730 DriveInfo[] theCollectionOfDrives = DriveInfo.GetDrives();
\r
732 foreach (DriveInfo curDrive in theCollectionOfDrives)
\r
734 if (curDrive.DriveType == DriveType.CDRom && curDrive.IsReady &&
\r
735 File.Exists(curDrive.RootDirectory + "VIDEO_TS\\VIDEO_TS.IFO"))
\r
737 drives.Add(new DriveInformation
\r
740 VolumeLabel = curDrive.VolumeLabel,
\r
741 RootDirectory = curDrive.RootDirectory + "VIDEO_TS"
\r
750 /// Change a string to Title Case/
\r
752 /// <param name="input">
\r
756 /// A string in title case.
\r
758 public static string TitleCase(string input)
\r
760 string[] tokens = input.Split(' ');
\r
761 StringBuilder sb = new StringBuilder(input.Length);
\r
762 foreach (string s in tokens)
\r
764 sb.Append(s[0].ToString().ToUpper());
\r
765 sb.Append(s.Substring(1).ToLower());
\r
769 return sb.ToString().Trim();
\r