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
13 using System.Text.RegularExpressions;
\r
14 using System.Threading;
\r
15 using System.Windows.Forms;
\r
16 using System.Xml.Serialization;
\r
21 /// Useful functions which various screens can use.
\r
23 public static class Main
\r
26 /// The XML Serializer
\r
28 private static readonly XmlSerializer Ser = new XmlSerializer(typeof(List<Job>));
\r
31 /// Calculate the duration of the selected title and chapters
\r
33 /// <param name="chapterStart">
\r
34 /// The chapter Start.
\r
36 /// <param name="chapterEnd">
\r
37 /// The chapter End.
\r
39 /// <param name="selectedTitle">
\r
40 /// The selected Title.
\r
43 /// The calculated duration.
\r
45 public static TimeSpan CalculateDuration(int chapterStart, int chapterEnd, Title selectedTitle)
\r
47 TimeSpan duration = TimeSpan.FromSeconds(0.0);
\r
50 if (chapterStart != 0 && chapterEnd != 0 && chapterEnd <= selectedTitle.Chapters.Count)
\r
52 for (int i = chapterStart; i <= chapterEnd; i++)
\r
53 duration += selectedTitle.Chapters[i - 1].Duration;
\r
60 /// Select the longest title in the DVD title dropdown menu on frmMain
\r
62 /// <param name="source">
\r
66 /// The longest title.
\r
68 public static Title SelectLongestTitle(DVD source)
\r
70 TimeSpan longestDurationFound = TimeSpan.FromSeconds(0.0);
\r
71 Title returnTitle = null;
\r
73 foreach (Title item in source.Titles)
\r
75 if (item.Duration > longestDurationFound)
\r
78 longestDurationFound = item.Duration;
\r
85 /// Set's up the DataGridView on the Chapters tab (frmMain)
\r
87 /// <param name="dataChpt">
\r
88 /// The DataGridView Control
\r
90 /// <param name="chapterEnd">
\r
91 /// The chapter End.
\r
94 /// The chapter naming.
\r
96 public static DataGridView ChapterNaming(DataGridView dataChpt, string chapterEnd)
\r
98 int i = 0, finish = 0;
\r
100 if (chapterEnd != "Auto")
\r
101 int.TryParse(chapterEnd, out finish);
\r
105 int n = dataChpt.Rows.Add();
\r
106 dataChpt.Rows[n].Cells[0].Value = i + 1;
\r
107 dataChpt.Rows[n].Cells[1].Value = "Chapter " + (i + 1);
\r
108 dataChpt.Rows[n].Cells[0].ValueType = typeof(int);
\r
109 dataChpt.Rows[n].Cells[1].ValueType = typeof(string);
\r
117 /// Import a CSV file which contains Chapter Names
\r
119 /// <param name="dataChpt">
\r
120 /// The DataGridView Control
\r
122 /// <param name="filename">
\r
123 /// The filepath and name
\r
125 /// <returns>A Populated DataGridView</returns>
\r
126 public static DataGridView ImportChapterNames(DataGridView dataChpt, string filename)
\r
128 IDictionary<int, string> chapterMap = new Dictionary<int, string>();
\r
131 StreamReader sr = new StreamReader(filename);
\r
132 string csv = sr.ReadLine();
\r
133 while (csv != null)
\r
135 if (csv.Trim() != string.Empty)
\r
137 csv = csv.Replace("\\,", "<!comma!>");
\r
138 string[] contents = csv.Split(',');
\r
140 int.TryParse(contents[0], out chapter);
\r
141 chapterMap.Add(chapter, contents[1].Replace("<!comma!>", ","));
\r
143 csv = sr.ReadLine();
\r
151 foreach (DataGridViewRow item in dataChpt.Rows)
\r
154 chapterMap.TryGetValue((int) item.Cells[0].Value, out name);
\r
155 item.Cells[1].Value = name ?? "Chapter " + item.Cells[0].Value;
\r
162 /// Function which generates the filename and path automatically based on
\r
163 /// the Source Name, DVD title and DVD Chapters
\r
165 /// <param name="mainWindow">
\r
166 /// The main Window.
\r
169 /// The Generated FileName
\r
171 public static string AutoName(frmMain mainWindow)
\r
173 string autoNamePath = string.Empty;
\r
174 if (mainWindow.drp_dvdtitle.Text != "Automatic")
\r
176 // Get the Source Name
\r
177 string sourceName = mainWindow.SourceName;
\r
179 // Get the Selected Title Number
\r
180 string[] titlesplit = mainWindow.drp_dvdtitle.Text.Split(' ');
\r
181 string dvdTitle = titlesplit[0].Replace("Automatic", string.Empty);
\r
183 // Get the Chapter Start and Chapter End Numbers
\r
184 string chapterStart = mainWindow.drop_chapterStart.Text.Replace("Auto", string.Empty);
\r
185 string chapterFinish = mainWindow.drop_chapterFinish.Text.Replace("Auto", string.Empty);
\r
186 string combinedChapterTag = chapterStart;
\r
187 if (chapterFinish != chapterStart && chapterFinish != string.Empty)
\r
188 combinedChapterTag = chapterStart + "-" + chapterFinish;
\r
190 // Get the destination filename.
\r
191 string destinationFilename;
\r
192 if (Properties.Settings.Default.autoNameFormat != string.Empty)
\r
194 destinationFilename = Properties.Settings.Default.autoNameFormat;
\r
195 destinationFilename =
\r
196 destinationFilename.Replace("{source}", sourceName).Replace("{title}", dvdTitle).Replace(
\r
197 "{chapters}", combinedChapterTag);
\r
200 destinationFilename = sourceName + "_T" + dvdTitle + "_C" + combinedChapterTag;
\r
202 // Add the appropriate file extension
\r
203 if (mainWindow.drop_format.SelectedIndex == 0)
\r
205 if (Properties.Settings.Default.useM4v || mainWindow.Check_ChapterMarkers.Checked ||
\r
206 mainWindow.AudioSettings.RequiresM4V() || mainWindow.Subtitles.RequiresM4V())
\r
207 destinationFilename += ".m4v";
\r
209 destinationFilename += ".mp4";
\r
211 else if (mainWindow.drop_format.SelectedIndex == 1)
\r
212 destinationFilename += ".mkv";
\r
214 // Now work out the path where the file will be stored.
\r
215 // First case: If the destination box doesn't already contain a path, make one.
\r
216 if (!mainWindow.text_destination.Text.Contains(Path.DirectorySeparatorChar.ToString()))
\r
218 // If there is an auto name path, use it...
\r
219 if (Properties.Settings.Default.autoNamePath.Trim() != string.Empty &&
\r
220 Properties.Settings.Default.autoNamePath.Trim() != "Click 'Browse' to set the default location")
\r
221 autoNamePath = Path.Combine(Properties.Settings.Default.autoNamePath, destinationFilename);
\r
222 else // ...otherwise, output to the source directory
\r
223 autoNamePath = null;
\r
225 else // Otherwise, use the path that is already there.
\r
227 // Use the path and change the file extension to match the previous destination
\r
228 autoNamePath = Path.Combine(Path.GetDirectoryName(mainWindow.text_destination.Text), destinationFilename);
\r
230 if (Path.HasExtension(mainWindow.text_destination.Text))
\r
231 autoNamePath = Path.ChangeExtension(autoNamePath, Path.GetExtension(mainWindow.text_destination.Text));
\r
235 return autoNamePath;
\r
239 /// Get's HandBrakes version data from the CLI.
\r
241 public static void SetCliVersionData()
\r
245 // 0 = SVN Build / Version
\r
247 DateTime lastModified = File.GetLastWriteTime("HandBrakeCLI.exe");
\r
249 if (Properties.Settings.Default.cliLastModified == lastModified && Properties.Settings.Default.hb_build != 0)
\r
252 Properties.Settings.Default.cliLastModified = lastModified;
\r
254 Process cliProcess = new Process();
\r
255 ProcessStartInfo handBrakeCli = new ProcessStartInfo("HandBrakeCLI.exe", " -u -v0")
\r
257 UseShellExecute = false,
\r
258 RedirectStandardError = true,
\r
259 RedirectStandardOutput = true,
\r
260 CreateNoWindow = true
\r
262 cliProcess.StartInfo = handBrakeCli;
\r
266 cliProcess.Start();
\r
268 // Retrieve standard output and report back to parent thread until the process is complete
\r
269 TextReader stdOutput = cliProcess.StandardError;
\r
271 while (!cliProcess.HasExited)
\r
273 line = stdOutput.ReadLine() ?? string.Empty;
\r
274 Match m = Regex.Match(line, @"HandBrake ([svnM0-9.]*) \([0-9]*\)");
\r
275 Match platform = Regex.Match(line, @"- ([A-Za-z0-9\s ]*) -");
\r
279 string data = line.Replace("(", string.Empty).Replace(")", string.Empty).Replace("HandBrake ", string.Empty);
\r
280 string[] arr = data.Split(' ');
\r
282 Properties.Settings.Default.hb_build = int.Parse(arr[1]);
\r
283 Properties.Settings.Default.hb_version = arr[0];
\r
286 if (platform.Success)
\r
288 Properties.Settings.Default.hb_platform = platform.Value.Replace("-", string.Empty).Trim();
\r
291 if (cliProcess.TotalProcessorTime.Seconds > 10) // Don't wait longer than 10 seconds.
\r
293 Process cli = Process.GetProcessById(cliProcess.Id);
\r
294 if (!cli.HasExited)
\r
301 Properties.Settings.Default.Save();
\r
303 catch (Exception e)
\r
305 MessageBox.Show("Unable to retrieve version information from the CLI. \nError:\n" + e);
\r
310 /// Check if the queue recovery file contains records.
\r
311 /// If it does, it means the last queue did not complete before HandBrake closed.
\r
312 /// So, return a boolean if true.
\r
315 /// True if there is a queue to recover.
\r
317 public static bool CheckQueueRecovery()
\r
321 string tempPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), @"HandBrake\hb_queue_recovery.xml");
\r
322 if (File.Exists(tempPath))
\r
324 using (FileStream strm = new FileStream(tempPath, FileMode.Open, FileAccess.Read))
\r
326 List<Job> list = Ser.Deserialize(strm) as List<Job>;
\r
328 if (list.Count != 0)
\r
336 return false; // Keep quiet about the error.
\r
341 /// Get the Process ID of HandBrakeCLI for the current instance.
\r
343 /// <param name="before">List of processes before the new process was started</param>
\r
344 /// <returns>Int - Process ID</returns>
\r
345 public static int GetCliProcess(Process[] before)
\r
347 // This is a bit of a cludge. Maybe someone has a better idea on how to impliment this.
\r
348 // Since we used CMD to start HandBrakeCLI, we don't get the process ID from hbProc.
\r
349 // Instead we take the processes before and after, and get the ID of HandBrakeCLI.exe
\r
350 // avoiding any previous instances of HandBrakeCLI.exe in before.
\r
351 // Kill the current process.
\r
353 DateTime startTime = DateTime.Now;
\r
356 Process[] hbProcesses = Process.GetProcessesByName("HandBrakeCLI");
\r
357 while (hbProcesses.Length == 0)
\r
359 hbProcesses = Process.GetProcessesByName("HandBrakeCLI");
\r
360 duration = DateTime.Now - startTime;
\r
361 if (duration.Seconds > 5 && hbProcesses.Length == 0)
\r
362 // Make sure we don't wait forever if the process doesn't start
\r
366 Process hbProcess = null;
\r
367 foreach (Process process in hbProcesses)
\r
369 bool found = false;
\r
370 // Check if the current CLI instance was running before we started the current one
\r
371 foreach (Process bprocess in before)
\r
373 if (process.Id == bprocess.Id)
\r
377 // If it wasn't running before, we found the process we want.
\r
380 hbProcess = process;
\r
384 if (hbProcess != null)
\r
385 return hbProcess.Id;
\r
391 /// Clear all the encode log files.
\r
393 public static void ClearLogs()
\r
395 string logDir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\HandBrake\\logs";
\r
396 if (Directory.Exists(logDir))
\r
398 DirectoryInfo info = new DirectoryInfo(logDir);
\r
399 FileInfo[] logFiles = info.GetFiles("*.txt");
\r
400 foreach (FileInfo file in logFiles)
\r
402 if (!file.Name.Contains("last_scan_log") && !file.Name.Contains("last_encode_log") &&
\r
403 !file.Name.Contains("tmp_appReadable_log.txt"))
\r
404 File.Delete(file.FullName);
\r
410 /// Clear old log files x days in the past
\r
412 public static void ClearOldLogs()
\r
414 string logDir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\HandBrake\\logs";
\r
415 if (Directory.Exists(logDir))
\r
417 DirectoryInfo info = new DirectoryInfo(logDir);
\r
418 FileInfo[] logFiles = info.GetFiles("*.txt");
\r
420 foreach (FileInfo file in logFiles)
\r
422 if (file.LastWriteTime < DateTime.Now.AddDays(-30))
\r
424 if (!file.Name.Contains("last_scan_log") && !file.Name.Contains("last_encode_log") &&
\r
425 !file.Name.Contains("tmp_appReadable_log.txt"))
\r
426 File.Delete(file.FullName);
\r
433 /// Begins checking for an update to HandBrake.
\r
435 /// <param name="callback">The method that will be called when the check is finished.</param>
\r
436 /// <param name="debug">Whether or not to execute this in debug mode.</param>
\r
437 public static void BeginCheckForUpdates(AsyncCallback callback, bool debug)
\r
439 ThreadPool.QueueUserWorkItem(new WaitCallback(delegate
\r
443 // Is this a stable or unstable build?
\r
445 Properties.Settings.Default.hb_build.ToString()
\r
447 ? Properties.Settings.Default.
\r
449 : Properties.Settings.Default.appcast;
\r
451 // Initialize variables
\r
452 WebRequest request = WebRequest.Create(url);
\r
453 WebResponse response = request.GetResponse();
\r
454 AppcastReader reader = new AppcastReader();
\r
456 // Get the data, convert it to a string, and parse it into the AppcastReader
\r
458 new StreamReader(response.GetResponseStream())
\r
461 // Further parse the information
\r
462 string build = reader.Build;
\r
464 int latest = int.Parse(build);
\r
465 int current = Properties.Settings.Default.hb_build;
\r
466 int skip = Properties.Settings.Default.skipversion;
\r
468 // If the user wanted to skip this version, don't report the update
\r
469 if (latest == skip)
\r
471 UpdateCheckInformation info =
\r
472 new UpdateCheckInformation
\r
474 NewVersionAvailable = false,
\r
475 BuildInformation = null
\r
477 callback(new UpdateCheckResult(debug, info));
\r
481 // Set when the last update was
\r
482 Properties.Settings.Default.lastUpdateCheckDate =
\r
484 Properties.Settings.Default.Save();
\r
486 UpdateCheckInformation info2 =
\r
487 new UpdateCheckInformation
\r
489 NewVersionAvailable = latest > current,
\r
490 BuildInformation = reader
\r
492 callback(new UpdateCheckResult(debug, info2));
\r
494 catch (Exception exc)
\r
496 callback(new UpdateCheckResult(debug, new UpdateCheckInformation { Error = exc }));
\r
502 /// End Check for Updates
\r
504 /// <param name="result">
\r
508 /// Update Check information
\r
510 public static UpdateCheckInformation EndCheckForUpdates(IAsyncResult result)
\r
512 UpdateCheckResult checkResult = (UpdateCheckResult) result;
\r
513 return checkResult.Result;
\r
517 /// Map languages and their iso639_2 value into a IDictionary
\r
519 /// <returns>A Dictionary containing the language and iso code</returns>
\r
520 public static IDictionary<string, string> MapLanguages()
\r
522 IDictionary<string, string> languageMap = new Dictionary<string, string>
\r
526 {"Abkhazian", "abk"},
\r
527 {"Afrikaans", "afr"},
\r
529 {"Albanian", "sqi"},
\r
530 {"Amharic", "amh"},
\r
531 {"Arabic", "ara"},
\r
532 {"Aragonese", "arg"},
\r
533 {"Armenian", "hye"},
\r
534 {"Assamese", "asm"},
\r
535 {"Avaric", "ava"},
\r
536 {"Avestan", "ave"},
\r
537 {"Aymara", "aym"},
\r
538 {"Azerbaijani", "aze"},
\r
539 {"Bashkir", "bak"},
\r
540 {"Bambara", "bam"},
\r
541 {"Basque", "eus"},
\r
542 {"Belarusian", "bel"},
\r
543 {"Bengali", "ben"},
\r
544 {"Bihari", "bih"},
\r
545 {"Bislama", "bis"},
\r
546 {"Bosnian", "bos"},
\r
547 {"Breton", "bre"},
\r
548 {"Bulgarian", "bul"},
\r
549 {"Burmese", "mya"},
\r
550 {"Catalan", "cat"},
\r
551 {"Chamorro", "cha"},
\r
552 {"Chechen", "che"},
\r
553 {"Chinese", "zho"},
\r
554 {"Church Slavic", "chu"},
\r
555 {"Chuvash", "chv"},
\r
556 {"Cornish", "cor"},
\r
557 {"Corsican", "cos"},
\r
561 {"Divehi", "div"},
\r
562 {"Nederlands", "nld"},
\r
563 {"Dzongkha", "dzo"},
\r
564 {"English", "eng"},
\r
565 {"Esperanto", "epo"},
\r
566 {"Estonian", "est"},
\r
568 {"Faroese", "fao"},
\r
569 {"Fijian", "fij"},
\r
571 {"Francais", "fra"},
\r
572 {"Western Frisian", "fry"},
\r
574 {"Georgian", "kat"},
\r
575 {"Deutsch", "deu"},
\r
576 {"Gaelic (Scots)", "gla"},
\r
578 {"Galician", "glg"},
\r
580 {"Greek Modern", "ell"},
\r
581 {"Guarani", "grn"},
\r
582 {"Gujarati", "guj"},
\r
583 {"Haitian", "hat"},
\r
585 {"Hebrew", "heb"},
\r
586 {"Herero", "her"},
\r
588 {"Hiri Motu", "hmo"},
\r
589 {"Magyar", "hun"},
\r
591 {"Islenska", "isl"},
\r
593 {"Sichuan Yi", "iii"},
\r
594 {"Inuktitut", "iku"},
\r
595 {"Interlingue", "ile"},
\r
596 {"Interlingua", "ina"},
\r
597 {"Indonesian", "ind"},
\r
598 {"Inupiaq", "ipk"},
\r
599 {"Italiano", "ita"},
\r
600 {"Javanese", "jav"},
\r
601 {"Japanese", "jpn"},
\r
602 {"Kalaallisut", "kal"},
\r
603 {"Kannada", "kan"},
\r
604 {"Kashmiri", "kas"},
\r
605 {"Kanuri", "kau"},
\r
606 {"Kazakh", "kaz"},
\r
607 {"Central Khmer", "khm"},
\r
608 {"Kikuyu", "kik"},
\r
609 {"Kinyarwanda", "kin"},
\r
610 {"Kirghiz", "kir"},
\r
613 {"Korean", "kor"},
\r
614 {"Kuanyama", "kua"},
\r
615 {"Kurdish", "kur"},
\r
618 {"Latvian", "lav"},
\r
619 {"Limburgan", "lim"},
\r
620 {"Lingala", "lin"},
\r
621 {"Lithuanian", "lit"},
\r
622 {"Luxembourgish", "ltz"},
\r
623 {"Luba-Katanga", "lub"},
\r
625 {"Macedonian", "mkd"},
\r
626 {"Marshallese", "mah"},
\r
627 {"Malayalam", "mal"},
\r
629 {"Marathi", "mar"},
\r
631 {"Malagasy", "mlg"},
\r
632 {"Maltese", "mlt"},
\r
633 {"Moldavian", "mol"},
\r
634 {"Mongolian", "mon"},
\r
636 {"Navajo", "nav"},
\r
637 {"Ndebele, South", "nbl"},
\r
638 {"Ndebele, North", "nde"},
\r
639 {"Ndonga", "ndo"},
\r
640 {"Nepali", "nep"},
\r
641 {"Norwegian Nynorsk", "nno"},
\r
642 {"Norwegian Bokmål", "nob"},
\r
644 {"Chichewa; Nyanja", "nya"},
\r
645 {"Occitan", "oci"},
\r
646 {"Ojibwa", "oji"},
\r
649 {"Ossetian", "oss"},
\r
650 {"Panjabi", "pan"},
\r
651 {"Persian", "fas"},
\r
653 {"Polish", "pol"},
\r
654 {"Portugues", "por"},
\r
655 {"Pushto", "pus"},
\r
656 {"Quechua", "que"},
\r
657 {"Romansh", "roh"},
\r
658 {"Romanian", "ron"},
\r
660 {"Russian", "rus"},
\r
662 {"Sanskrit", "san"},
\r
663 {"Serbian", "srp"},
\r
664 {"Hrvatski", "hrv"},
\r
665 {"Sinhala", "sin"},
\r
666 {"Slovak", "slk"},
\r
667 {"Slovenian", "slv"},
\r
668 {"Northern Sami", "sme"},
\r
669 {"Samoan", "smo"},
\r
671 {"Sindhi", "snd"},
\r
672 {"Somali", "som"},
\r
673 {"Sotho Southern", "sot"},
\r
674 {"Espanol", "spa"},
\r
675 {"Sardinian", "srd"},
\r
677 {"Sundanese", "sun"},
\r
678 {"Swahili", "swa"},
\r
679 {"Svenska", "swe"},
\r
680 {"Tahitian", "tah"},
\r
683 {"Telugu", "tel"},
\r
685 {"Tagalog", "tgl"},
\r
687 {"Tibetan", "bod"},
\r
688 {"Tigrinya", "tir"},
\r
690 {"Tswana", "tsn"},
\r
691 {"Tsonga", "tso"},
\r
692 {"Turkmen", "tuk"},
\r
693 {"Turkish", "tur"},
\r
695 {"Uighur", "uig"},
\r
696 {"Ukrainian", "ukr"},
\r
700 {"Vietnamese", "vie"},
\r
701 {"Volapük", "vol"},
\r
703 {"Walloon", "wln"},
\r
706 {"Yiddish", "yid"},
\r
707 {"Yoruba", "yor"},
\r
708 {"Zhuang", "zha"},
\r
711 return languageMap;
\r
715 /// Get a list of available DVD drives which are ready and contain DVD content.
\r
717 /// <returns>A List of Drives with their details</returns>
\r
718 public static List<DriveInformation> GetDrives()
\r
720 List<DriveInformation> drives = new List<DriveInformation>();
\r
721 DriveInfo[] theCollectionOfDrives = DriveInfo.GetDrives();
\r
722 foreach (DriveInfo curDrive in theCollectionOfDrives)
\r
724 if (curDrive.DriveType == DriveType.CDRom && curDrive.IsReady &&
\r
725 File.Exists(curDrive.RootDirectory + "VIDEO_TS\\VIDEO_TS.IFO"))
\r
727 drives.Add(new DriveInformation
\r
729 VolumeLabel = curDrive.VolumeLabel,
\r
730 RootDirectory = curDrive.RootDirectory + "VIDEO_TS"
\r