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, Parsing.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 Parsing.Title SelectLongestTitle(Parsing.DVD source)
\r
70 TimeSpan longestDurationFound = TimeSpan.FromSeconds(0.0);
\r
71 Parsing.Title returnTitle = null;
\r
73 foreach (Parsing.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 = destinationFilename.Replace("{source}", sourceName).Replace("{title}", dvdTitle).Replace("{chapters}", combinedChapterTag);
\r
198 destinationFilename = sourceName + "_T" + dvdTitle + "_C" + combinedChapterTag;
\r
200 // Add the appropriate file extension
\r
201 if (mainWindow.drop_format.SelectedIndex == 0)
\r
203 if (Properties.Settings.Default.useM4v || mainWindow.Check_ChapterMarkers.Checked || mainWindow.AudioSettings.RequiresM4V() || mainWindow.Subtitles.RequiresM4V())
\r
204 destinationFilename += ".m4v";
\r
206 destinationFilename += ".mp4";
\r
208 else if (mainWindow.drop_format.SelectedIndex == 1)
\r
209 destinationFilename += ".mkv";
\r
211 // Now work out the path where the file will be stored.
\r
212 // First case: If the destination box doesn't already contain a path, make one.
\r
213 if (!mainWindow.text_destination.Text.Contains(Path.DirectorySeparatorChar.ToString()))
\r
215 // If there is an auto name path, use it...
\r
216 if (Properties.Settings.Default.autoNamePath.Trim() != string.Empty && Properties.Settings.Default.autoNamePath.Trim() != "Click 'Browse' to set the default location")
\r
217 autoNamePath = Path.Combine(Properties.Settings.Default.autoNamePath, destinationFilename);
\r
218 else // ...otherwise, output to the source directory
\r
219 autoNamePath = null;
\r
221 else // Otherwise, use the path that is already there.
\r
223 // Use the path and change the file extension to match the previous destination
\r
224 autoNamePath = Path.Combine(Path.GetDirectoryName(mainWindow.text_destination.Text), destinationFilename);
\r
226 if (Path.HasExtension(mainWindow.text_destination.Text))
\r
227 autoNamePath = Path.ChangeExtension(autoNamePath, Path.GetExtension(mainWindow.text_destination.Text));
\r
231 return autoNamePath;
\r
235 /// Get's HandBrakes version data from the CLI.
\r
237 public static void SetCliVersionData()
\r
241 // 0 = SVN Build / Version
\r
243 DateTime lastModified = File.GetLastWriteTime("HandBrakeCLI.exe");
\r
245 if (Properties.Settings.Default.cliLastModified == lastModified && Properties.Settings.Default.hb_build != 0)
\r
248 Properties.Settings.Default.cliLastModified = lastModified;
\r
250 Process cliProcess = new Process();
\r
251 ProcessStartInfo handBrakeCli = new ProcessStartInfo("HandBrakeCLI.exe", " -u -v0")
\r
253 UseShellExecute = false,
\r
254 RedirectStandardError = true,
\r
255 RedirectStandardOutput = true,
\r
256 CreateNoWindow = true
\r
258 cliProcess.StartInfo = handBrakeCli;
\r
262 cliProcess.Start();
\r
264 // Retrieve standard output and report back to parent thread until the process is complete
\r
265 TextReader stdOutput = cliProcess.StandardError;
\r
267 while (!cliProcess.HasExited)
\r
269 line = stdOutput.ReadLine() ?? string.Empty;
\r
270 Match m = Regex.Match(line, @"HandBrake ([svnM0-9.]*) \([0-9]*\)");
\r
271 Match platform = Regex.Match(line, @"- ([A-Za-z0-9\s ]*) -");
\r
275 string data = line.Replace("(", string.Empty).Replace(")", string.Empty).Replace("HandBrake ", string.Empty);
\r
276 string[] arr = data.Split(' ');
\r
278 Properties.Settings.Default.hb_build = int.Parse(arr[1]);
\r
279 Properties.Settings.Default.hb_version = arr[0];
\r
282 if (platform.Success)
\r
284 Properties.Settings.Default.hb_platform = platform.Value.Replace("-", string.Empty).Trim();
\r
287 if (cliProcess.TotalProcessorTime.Seconds > 10) // Don't wait longer than 10 seconds.
\r
289 Process cli = Process.GetProcessById(cliProcess.Id);
\r
290 if (!cli.HasExited)
\r
297 Properties.Settings.Default.Save();
\r
299 catch (Exception e)
\r
301 MessageBox.Show("Unable to retrieve version information from the CLI. \nError:\n" + e);
\r
306 /// Check if the queue recovery file contains records.
\r
307 /// If it does, it means the last queue did not complete before HandBrake closed.
\r
308 /// So, return a boolean if true.
\r
311 /// True if there is a queue to recover.
\r
313 public static bool CheckQueueRecovery()
\r
317 string tempPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), @"HandBrake\hb_queue_recovery.xml");
\r
318 if (File.Exists(tempPath))
\r
320 using (FileStream strm = new FileStream(tempPath, FileMode.Open, FileAccess.Read))
\r
322 List<Job> list = Ser.Deserialize(strm) as List<Job>;
\r
324 if (list.Count != 0)
\r
332 return false; // Keep quiet about the error.
\r
337 /// Get the Process ID of HandBrakeCLI for the current instance.
\r
339 /// <param name="before">List of processes before the new process was started</param>
\r
340 /// <returns>Int - Process ID</returns>
\r
341 public static int GetCliProcess(Process[] before)
\r
343 // This is a bit of a cludge. Maybe someone has a better idea on how to impliment this.
\r
344 // Since we used CMD to start HandBrakeCLI, we don't get the process ID from hbProc.
\r
345 // Instead we take the processes before and after, and get the ID of HandBrakeCLI.exe
\r
346 // avoiding any previous instances of HandBrakeCLI.exe in before.
\r
347 // Kill the current process.
\r
349 DateTime startTime = DateTime.Now;
\r
352 Process[] hbProcesses = Process.GetProcessesByName("HandBrakeCLI");
\r
353 while (hbProcesses.Length == 0)
\r
355 hbProcesses = Process.GetProcessesByName("HandBrakeCLI");
\r
356 duration = DateTime.Now - startTime;
\r
357 if (duration.Seconds > 5 && hbProcesses.Length == 0) // Make sure we don't wait forever if the process doesn't start
\r
361 Process hbProcess = null;
\r
362 foreach (Process process in hbProcesses)
\r
364 bool found = false;
\r
365 // Check if the current CLI instance was running before we started the current one
\r
366 foreach (Process bprocess in before)
\r
368 if (process.Id == bprocess.Id)
\r
372 // If it wasn't running before, we found the process we want.
\r
375 hbProcess = process;
\r
379 if (hbProcess != null)
\r
380 return hbProcess.Id;
\r
386 /// Clear all the encode log files.
\r
388 public static void ClearLogs()
\r
390 string logDir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\HandBrake\\logs";
\r
391 if (Directory.Exists(logDir))
\r
393 DirectoryInfo info = new DirectoryInfo(logDir);
\r
394 FileInfo[] logFiles = info.GetFiles("*.txt");
\r
395 foreach (FileInfo file in logFiles)
\r
397 if (!file.Name.Contains("last_scan_log") && !file.Name.Contains("last_encode_log") && !file.Name.Contains("tmp_appReadable_log.txt"))
\r
398 File.Delete(file.FullName);
\r
404 /// Clear old log files x days in the past
\r
406 public static void ClearOldLogs()
\r
408 string logDir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\HandBrake\\logs";
\r
409 if (Directory.Exists(logDir))
\r
411 DirectoryInfo info = new DirectoryInfo(logDir);
\r
412 FileInfo[] logFiles = info.GetFiles("*.txt");
\r
414 foreach (FileInfo file in logFiles)
\r
416 if (file.LastWriteTime < DateTime.Now.AddDays(-30))
\r
418 if (!file.Name.Contains("last_scan_log") && !file.Name.Contains("last_encode_log") && !file.Name.Contains("tmp_appReadable_log.txt"))
\r
419 File.Delete(file.FullName);
\r
426 /// Begins checking for an update to HandBrake.
\r
428 /// <param name="callback">The method that will be called when the check is finished.</param>
\r
429 /// <param name="debug">Whether or not to execute this in debug mode.</param>
\r
430 public static void BeginCheckForUpdates(AsyncCallback callback, bool debug)
\r
432 ThreadPool.QueueUserWorkItem(new WaitCallback(delegate
\r
436 // Is this a stable or unstable build?
\r
438 Properties.Settings.Default.hb_build.ToString()
\r
440 ? Properties.Settings.Default.
\r
442 : Properties.Settings.Default.appcast;
\r
444 // Initialize variables
\r
445 WebRequest request = WebRequest.Create(url);
\r
446 WebResponse response = request.GetResponse();
\r
447 AppcastReader reader = new AppcastReader();
\r
449 // Get the data, convert it to a string, and parse it into the AppcastReader
\r
451 new StreamReader(response.GetResponseStream())
\r
454 // Further parse the information
\r
455 string build = reader.Build;
\r
457 int latest = int.Parse(build);
\r
458 int current = Properties.Settings.Default.hb_build;
\r
459 int skip = Properties.Settings.Default.skipversion;
\r
461 // If the user wanted to skip this version, don't report the update
\r
462 if (latest == skip)
\r
464 UpdateCheckInformation info =
\r
465 new UpdateCheckInformation
\r
467 NewVersionAvailable = false,
\r
468 BuildInformation = null
\r
470 callback(new UpdateCheckResult(debug, info));
\r
474 // Set when the last update was
\r
475 Properties.Settings.Default.lastUpdateCheckDate =
\r
477 Properties.Settings.Default.Save();
\r
479 UpdateCheckInformation info2 =
\r
480 new UpdateCheckInformation
\r
482 NewVersionAvailable = latest > current,
\r
483 BuildInformation = reader
\r
485 callback(new UpdateCheckResult(debug, info2));
\r
487 catch (Exception exc)
\r
489 callback(new UpdateCheckResult(debug, new UpdateCheckInformation{Error = exc}));
\r
495 /// End Check for Updates
\r
497 /// <param name="result">
\r
501 /// Update Check information
\r
503 public static UpdateCheckInformation EndCheckForUpdates(IAsyncResult result)
\r
505 UpdateCheckResult checkResult = (UpdateCheckResult)result;
\r
506 return checkResult.Result;
\r
510 /// Map languages and their iso639_2 value into a IDictionary
\r
512 /// <returns>A Dictionary containing the language and iso code</returns>
\r
513 public static IDictionary<string, string> MapLanguages()
\r
515 IDictionary<string, string> languageMap = new Dictionary<string, string>
\r
519 {"Abkhazian", "abk"},
\r
520 {"Afrikaans", "afr"},
\r
522 {"Albanian", "sqi"},
\r
523 {"Amharic", "amh"},
\r
525 {"Aragonese", "arg"},
\r
526 {"Armenian", "hye"},
\r
527 {"Assamese", "asm"},
\r
529 {"Avestan", "ave"},
\r
531 {"Azerbaijani", "aze"},
\r
532 {"Bashkir", "bak"},
\r
533 {"Bambara", "bam"},
\r
535 {"Belarusian", "bel"},
\r
536 {"Bengali", "ben"},
\r
538 {"Bislama", "bis"},
\r
539 {"Bosnian", "bos"},
\r
541 {"Bulgarian", "bul"},
\r
542 {"Burmese", "mya"},
\r
543 {"Catalan", "cat"},
\r
544 {"Chamorro", "cha"},
\r
545 {"Chechen", "che"},
\r
546 {"Chinese", "zho"},
\r
547 {"Church Slavic", "chu"},
\r
548 {"Chuvash", "chv"},
\r
549 {"Cornish", "cor"},
\r
550 {"Corsican", "cos"},
\r
555 {"Nederlands", "nld"},
\r
556 {"Dzongkha", "dzo"},
\r
557 {"English", "eng"},
\r
558 {"Esperanto", "epo"},
\r
559 {"Estonian", "est"},
\r
561 {"Faroese", "fao"},
\r
564 {"Francais", "fra"},
\r
565 {"Western Frisian", "fry"},
\r
567 {"Georgian", "kat"},
\r
568 {"Deutsch", "deu"},
\r
569 {"Gaelic (Scots)", "gla"},
\r
571 {"Galician", "glg"},
\r
573 {"Greek Modern", "ell"},
\r
574 {"Guarani", "grn"},
\r
575 {"Gujarati", "guj"},
\r
576 {"Haitian", "hat"},
\r
581 {"Hiri Motu", "hmo"},
\r
584 {"Islenska", "isl"},
\r
586 {"Sichuan Yi", "iii"},
\r
587 {"Inuktitut", "iku"},
\r
588 {"Interlingue", "ile"},
\r
589 {"Interlingua", "ina"},
\r
590 {"Indonesian", "ind"},
\r
591 {"Inupiaq", "ipk"},
\r
592 {"Italiano", "ita"},
\r
593 {"Javanese", "jav"},
\r
594 {"Japanese", "jpn"},
\r
595 {"Kalaallisut", "kal"},
\r
596 {"Kannada", "kan"},
\r
597 {"Kashmiri", "kas"},
\r
600 {"Central Khmer", "khm"},
\r
602 {"Kinyarwanda", "kin"},
\r
603 {"Kirghiz", "kir"},
\r
607 {"Kuanyama", "kua"},
\r
608 {"Kurdish", "kur"},
\r
611 {"Latvian", "lav"},
\r
612 {"Limburgan", "lim"},
\r
613 {"Lingala", "lin"},
\r
614 {"Lithuanian", "lit"},
\r
615 {"Luxembourgish", "ltz"},
\r
616 {"Luba-Katanga", "lub"},
\r
618 {"Macedonian", "mkd"},
\r
619 {"Marshallese", "mah"},
\r
620 {"Malayalam", "mal"},
\r
622 {"Marathi", "mar"},
\r
624 {"Malagasy", "mlg"},
\r
625 {"Maltese", "mlt"},
\r
626 {"Moldavian", "mol"},
\r
627 {"Mongolian", "mon"},
\r
630 {"Ndebele, South", "nbl"},
\r
631 {"Ndebele, North", "nde"},
\r
634 {"Norwegian Nynorsk", "nno"},
\r
635 {"Norwegian Bokmål", "nob"},
\r
637 {"Chichewa; Nyanja", "nya"},
\r
638 {"Occitan", "oci"},
\r
642 {"Ossetian", "oss"},
\r
643 {"Panjabi", "pan"},
\r
644 {"Persian", "fas"},
\r
647 {"Portugues", "por"},
\r
649 {"Quechua", "que"},
\r
650 {"Romansh", "roh"},
\r
651 {"Romanian", "ron"},
\r
653 {"Russian", "rus"},
\r
655 {"Sanskrit", "san"},
\r
656 {"Serbian", "srp"},
\r
657 {"Hrvatski", "hrv"},
\r
658 {"Sinhala", "sin"},
\r
660 {"Slovenian", "slv"},
\r
661 {"Northern Sami", "sme"},
\r
666 {"Sotho Southern", "sot"},
\r
667 {"Espanol", "spa"},
\r
668 {"Sardinian", "srd"},
\r
670 {"Sundanese", "sun"},
\r
671 {"Swahili", "swa"},
\r
672 {"Svenska", "swe"},
\r
673 {"Tahitian", "tah"},
\r
678 {"Tagalog", "tgl"},
\r
680 {"Tibetan", "bod"},
\r
681 {"Tigrinya", "tir"},
\r
685 {"Turkmen", "tuk"},
\r
686 {"Turkish", "tur"},
\r
689 {"Ukrainian", "ukr"},
\r
693 {"Vietnamese", "vie"},
\r
694 {"Volapük", "vol"},
\r
696 {"Walloon", "wln"},
\r
699 {"Yiddish", "yid"},
\r
704 return languageMap;
\r
708 /// Get a list of available DVD drives which are ready and contain DVD content.
\r
710 /// <returns>A List of Drives with their details</returns>
\r
711 public static List<DriveInformation> GetDrives()
\r
713 List<DriveInformation> drives = new List<DriveInformation>();
\r
714 DriveInfo[] theCollectionOfDrives = DriveInfo.GetDrives();
\r
715 foreach (DriveInfo curDrive in theCollectionOfDrives)
\r
717 if (curDrive.DriveType == DriveType.CDRom && curDrive.IsReady && File.Exists(curDrive.RootDirectory + "VIDEO_TS\\VIDEO_TS.IFO"))
\r
719 drives.Add(new DriveInformation
\r
721 VolumeLabel = curDrive.VolumeLabel,
\r
722 RootDirectory = curDrive.RootDirectory + "VIDEO_TS"
\r