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
17 using Handbrake.Model;
\r
19 namespace Handbrake.Functions
\r
23 // Private Variables
\r
24 private static readonly XmlSerializer Ser = new XmlSerializer(typeof(List<Job>));
\r
27 /// Calculate the duration of the selected title and chapters
\r
29 public static TimeSpan CalculateDuration(int chapterStart, int chapterEnd, Parsing.Title selectedTitle)
\r
31 TimeSpan duration = TimeSpan.FromSeconds(0.0);
\r
32 chapterStart++; chapterEnd++;
\r
33 if (chapterStart != 0 && chapterEnd != 0 && chapterEnd <= selectedTitle.Chapters.Count)
\r
35 for (int i = chapterStart; i <= chapterEnd; i++)
\r
36 duration += selectedTitle.Chapters[i - 1].Duration;
\r
43 /// Select the longest title in the DVD title dropdown menu on frmMain
\r
45 public static Parsing.Title SelectLongestTitle(Parsing.DVD thisDvd)
\r
47 TimeSpan longestDurationFound = TimeSpan.FromSeconds(0.0);
\r
48 Parsing.Title returnTitle = null;
\r
50 foreach (Parsing.Title item in thisDvd.Titles)
\r
52 if (item.Duration > longestDurationFound)
\r
55 longestDurationFound = item.Duration;
\r
62 /// Set's up the DataGridView on the Chapters tab (frmMain)
\r
64 public static DataGridView ChapterNaming(DataGridView dataChpt, string chapterEnd)
\r
66 int i = 0, finish = 0;
\r
68 if (chapterEnd != "Auto")
\r
69 int.TryParse(chapterEnd, out finish);
\r
73 int n = dataChpt.Rows.Add();
\r
74 dataChpt.Rows[n].Cells[0].Value = (i + 1);
\r
75 dataChpt.Rows[n].Cells[1].Value = "Chapter " + (i + 1);
\r
76 dataChpt.Rows[n].Cells[0].ValueType = typeof(int);
\r
77 dataChpt.Rows[n].Cells[1].ValueType = typeof(string);
\r
85 /// Import a CSV file which contains Chapter Names
\r
87 /// <param name="dataChpt"></param>
\r
88 /// <param name="filename"></param>
\r
89 /// <returns></returns>
\r
90 public static DataGridView ImportChapterNames(DataGridView dataChpt, string filename)
\r
92 IDictionary<int, string> chapterMap = new Dictionary<int, string>();
\r
95 StreamReader sr = new StreamReader(filename);
\r
96 string csv = sr.ReadLine();
\r
99 if (csv.Trim() != "")
\r
101 csv = csv.Replace("\\,", "<!comma!>");
\r
102 string[] contents = csv.Split(',');
\r
104 int.TryParse(contents[0], out chapter);
\r
105 chapterMap.Add(chapter, contents[1].Replace("<!comma!>", ","));
\r
107 csv = sr.ReadLine();
\r
115 foreach (DataGridViewRow item in dataChpt.Rows)
\r
118 chapterMap.TryGetValue((int)item.Cells[0].Value, out name);
\r
119 item.Cells[1].Value = name ?? "Chapter " + item.Cells[0].Value;
\r
126 /// Function which generates the filename and path automatically based on
\r
127 /// the Source Name, DVD title and DVD Chapters
\r
129 public static string AutoName(frmMain mainWindow)
\r
131 string AutoNamePath = string.Empty;
\r
132 if (mainWindow.drp_dvdtitle.Text != "Automatic")
\r
134 // Get the Source Name
\r
135 string sourceName = mainWindow.SourceName;
\r
137 // Get the Selected Title Number
\r
138 string[] titlesplit = mainWindow.drp_dvdtitle.Text.Split(' ');
\r
139 string dvdTitle = titlesplit[0].Replace("Automatic", "");
\r
141 // Get the Chapter Start and Chapter End Numbers
\r
142 string chapterStart = mainWindow.drop_chapterStart.Text.Replace("Auto", "");
\r
143 string chapterFinish = mainWindow.drop_chapterFinish.Text.Replace("Auto", "");
\r
144 string combinedChapterTag = chapterStart;
\r
145 if (chapterFinish != chapterStart && chapterFinish != "")
\r
146 combinedChapterTag = chapterStart + "-" + chapterFinish;
\r
148 // Get the destination filename.
\r
149 string destinationFilename;
\r
150 if (Properties.Settings.Default.autoNameFormat != "")
\r
152 destinationFilename = Properties.Settings.Default.autoNameFormat;
\r
153 destinationFilename = destinationFilename.Replace("{source}", sourceName).Replace("{title}", dvdTitle).Replace("{chapters}", combinedChapterTag);
\r
156 destinationFilename = sourceName + "_T" + dvdTitle + "_C" + combinedChapterTag;
\r
158 // Add the appropriate file extension
\r
159 if (mainWindow.drop_format.SelectedIndex == 0)
\r
161 if (Properties.Settings.Default.useM4v || mainWindow.Check_ChapterMarkers.Checked || mainWindow.AudioSettings.RequiresM4V() || mainWindow.Subtitles.RequiresM4V())
\r
162 destinationFilename += ".m4v";
\r
164 destinationFilename += ".mp4";
\r
166 else if (mainWindow.drop_format.SelectedIndex == 1)
\r
167 destinationFilename += ".mkv";
\r
169 // Now work out the path where the file will be stored.
\r
170 // First case: If the destination box doesn't already contain a path, make one.
\r
171 if (!mainWindow.text_destination.Text.Contains(Path.DirectorySeparatorChar.ToString()))
\r
173 // If there is an auto name path, use it...
\r
174 if (Properties.Settings.Default.autoNamePath.Trim() != "" && Properties.Settings.Default.autoNamePath.Trim() != "Click 'Browse' to set the default location")
\r
175 AutoNamePath = Path.Combine(Properties.Settings.Default.autoNamePath, destinationFilename);
\r
176 else // ...otherwise, output to the source directory
\r
177 AutoNamePath = null;
\r
179 else // Otherwise, use the path that is already there.
\r
181 // Use the path and change the file extension to match the previous destination
\r
182 AutoNamePath = Path.Combine(Path.GetDirectoryName(mainWindow.text_destination.Text), destinationFilename);
\r
184 if (Path.HasExtension(mainWindow.text_destination.Text))
\r
185 AutoNamePath = Path.ChangeExtension(AutoNamePath, Path.GetExtension(mainWindow.text_destination.Text));
\r
189 return AutoNamePath;
\r
193 /// Get's HandBrakes version data from the CLI.
\r
195 /// <returns>Arraylist of Version Data. 0 = hb_version 1 = hb_build</returns>
\r
196 public static void SetCliVersionData()
\r
200 // 0 = SVN Build / Version
\r
203 DateTime lastModified = File.GetLastWriteTime("HandBrakeCLI.exe");
\r
206 if (Properties.Settings.Default.cliLastModified == lastModified && Properties.Settings.Default.hb_build != 0)
\r
209 Properties.Settings.Default.cliLastModified = lastModified;
\r
211 Process cliProcess = new Process();
\r
212 ProcessStartInfo handBrakeCLI = new ProcessStartInfo("HandBrakeCLI.exe", " -u -v0")
\r
214 UseShellExecute = false,
\r
215 RedirectStandardError = true,
\r
216 RedirectStandardOutput = true,
\r
217 CreateNoWindow = true
\r
219 cliProcess.StartInfo = handBrakeCLI;
\r
223 cliProcess.Start();
\r
224 // Retrieve standard output and report back to parent thread until the process is complete
\r
225 TextReader stdOutput = cliProcess.StandardError;
\r
227 while (!cliProcess.HasExited)
\r
229 line = stdOutput.ReadLine() ?? "";
\r
230 Match m = Regex.Match(line, @"HandBrake ([svnM0-9.]*) \([0-9]*\)");
\r
231 Match platform = Regex.Match(line, @"- ([A-Za-z0-9\s ]*) -");
\r
235 string data = line.Replace("(", "").Replace(")", "").Replace("HandBrake ", "");
\r
236 string[] arr = data.Split(' ');
\r
238 Properties.Settings.Default.hb_build = int.Parse(arr[1]);
\r
239 Properties.Settings.Default.hb_version = arr[0];
\r
241 if (platform.Success)
\r
242 Properties.Settings.Default.hb_platform = platform.Value.Replace("-", "").Trim();
\r
244 if (cliProcess.TotalProcessorTime.Seconds > 10) // Don't wait longer than 10 seconds.
\r
246 Process cli = Process.GetProcessById(cliProcess.Id);
\r
247 if (!cli.HasExited)
\r
251 Properties.Settings.Default.Save();
\r
253 catch (Exception e)
\r
255 MessageBox.Show("Unable to retrieve version information from the CLI. \nError:\n" + e);
\r
260 /// Check if the queue recovery file contains records.
\r
261 /// If it does, it means the last queue did not complete before HandBrake closed.
\r
262 /// So, return a boolean if true.
\r
264 public static Boolean CheckQueueRecovery()
\r
268 string tempPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), @"HandBrake\hb_queue_recovery.xml");
\r
269 if (File.Exists(tempPath))
\r
271 using (FileStream strm = new FileStream(tempPath, FileMode.Open, FileAccess.Read))
\r
273 List<Job> list = Ser.Deserialize(strm) as List<Job>;
\r
275 if (list.Count != 0)
\r
283 return false; // Keep quiet about the error.
\r
288 /// Get the Process ID of HandBrakeCLI for the current instance.
\r
290 /// <param name="before">List of processes before the new process was started</param>
\r
291 /// <returns>Int - Process ID</returns>
\r
292 public static int GetCliProcess(Process[] before)
\r
294 // This is a bit of a cludge. Maybe someone has a better idea on how to impliment this.
\r
295 // Since we used CMD to start HandBrakeCLI, we don't get the process ID from hbProc.
\r
296 // Instead we take the processes before and after, and get the ID of HandBrakeCLI.exe
\r
297 // avoiding any previous instances of HandBrakeCLI.exe in before.
\r
298 // Kill the current process.
\r
300 DateTime startTime = DateTime.Now;
\r
303 Process[] hbProcesses = Process.GetProcessesByName("HandBrakeCLI");
\r
304 while (hbProcesses.Length == 0)
\r
306 hbProcesses = Process.GetProcessesByName("HandBrakeCLI");
\r
307 duration = DateTime.Now - startTime;
\r
308 if (duration.Seconds > 5 && hbProcesses.Length == 0) // Make sure we don't wait forever if the process doesn't start
\r
312 Process hbProcess = null;
\r
313 foreach (Process process in hbProcesses)
\r
315 Boolean found = false;
\r
316 // Check if the current CLI instance was running before we started the current one
\r
317 foreach (Process bprocess in before)
\r
319 if (process.Id == bprocess.Id)
\r
323 // If it wasn't running before, we found the process we want.
\r
326 hbProcess = process;
\r
330 if (hbProcess != null)
\r
331 return hbProcess.Id;
\r
337 /// Clear all the encode log files.
\r
339 public static void ClearLogs()
\r
341 string logDir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\HandBrake\\logs";
\r
342 if (Directory.Exists(logDir))
\r
344 DirectoryInfo info = new DirectoryInfo(logDir);
\r
345 FileInfo[] logFiles = info.GetFiles("*.txt");
\r
346 foreach (FileInfo file in logFiles)
\r
348 if (!file.Name.Contains("last_scan_log") && !file.Name.Contains("last_encode_log") && !file.Name.Contains("tmp_appReadable_log.txt"))
\r
349 File.Delete(file.FullName);
\r
356 /// Clear old log files x days in the past
\r
358 public static void ClearOldLogs()
\r
360 string logDir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\HandBrake\\logs";
\r
361 if (Directory.Exists(logDir))
\r
363 DirectoryInfo info = new DirectoryInfo(logDir);
\r
364 FileInfo[] logFiles = info.GetFiles("*.txt");
\r
366 foreach (FileInfo file in logFiles)
\r
368 if (file.LastWriteTime < DateTime.Now.AddDays(-30))
\r
370 if (!file.Name.Contains("last_scan_log") && !file.Name.Contains("last_encode_log") && !file.Name.Contains("tmp_appReadable_log.txt"))
\r
371 File.Delete(file.FullName);
\r
379 /// Begins checking for an update to HandBrake.
\r
381 /// <param name="callback">The method that will be called when the check is finished.</param>
\r
382 /// <param name="debug">Whether or not to execute this in debug mode.</param>
\r
383 public static void BeginCheckForUpdates(AsyncCallback callback, bool debug)
\r
385 ThreadPool.QueueUserWorkItem(new WaitCallback(delegate
\r
389 // Is this a stable or unstable build?
\r
390 string url = Properties.Settings.Default.hb_build.ToString().EndsWith("1") ? Properties.Settings.Default.appcast_unstable : Properties.Settings.Default.appcast;
\r
392 // Initialize variables
\r
393 WebRequest request = WebRequest.Create(url);
\r
394 WebResponse response = request.GetResponse();
\r
395 AppcastReader reader = new AppcastReader();
\r
397 // Get the data, convert it to a string, and parse it into the AppcastReader
\r
398 reader.GetInfo(new StreamReader(response.GetResponseStream()).ReadToEnd());
\r
400 // Further parse the information
\r
401 string build = reader.Build;
\r
403 int latest = int.Parse(build);
\r
404 int current = Properties.Settings.Default.hb_build;
\r
405 int skip = Properties.Settings.Default.skipversion;
\r
407 // If the user wanted to skip this version, don't report the update
\r
408 if (latest == skip)
\r
410 UpdateCheckInformation info = new UpdateCheckInformation() { NewVersionAvailable = false, BuildInformation = null };
\r
411 callback(new UpdateCheckResult(debug, info));
\r
415 // Set when the last update was
\r
416 Properties.Settings.Default.lastUpdateCheckDate = DateTime.Now;
\r
417 Properties.Settings.Default.Save();
\r
419 UpdateCheckInformation info2 = new UpdateCheckInformation() { NewVersionAvailable = latest > current, BuildInformation = reader };
\r
420 callback(new UpdateCheckResult(debug, info2));
\r
422 catch (Exception exc)
\r
424 callback(new UpdateCheckResult(debug, new UpdateCheckInformation() { Error = exc }));
\r
432 /// <param name="result"></param>
\r
433 /// <returns></returns>
\r
434 public static UpdateCheckInformation EndCheckForUpdates(IAsyncResult result)
\r
436 UpdateCheckResult checkResult = (UpdateCheckResult)result;
\r
437 return checkResult.Result;
\r
441 /// Map languages and their iso639_2 value into a IDictionary
\r
443 /// <returns></returns>
\r
444 public static IDictionary<string, string> MapLanguages()
\r
446 IDictionary<string, string> languageMap = new Dictionary<string, string>
\r
450 {"Abkhazian", "abk"},
\r
451 {"Afrikaans", "afr"},
\r
453 {"Albanian", "sqi"},
\r
454 {"Amharic", "amh"},
\r
456 {"Aragonese", "arg"},
\r
457 {"Armenian", "hye"},
\r
458 {"Assamese", "asm"},
\r
460 {"Avestan", "ave"},
\r
462 {"Azerbaijani", "aze"},
\r
463 {"Bashkir", "bak"},
\r
464 {"Bambara", "bam"},
\r
466 {"Belarusian", "bel"},
\r
467 {"Bengali", "ben"},
\r
469 {"Bislama", "bis"},
\r
470 {"Bosnian", "bos"},
\r
472 {"Bulgarian", "bul"},
\r
473 {"Burmese", "mya"},
\r
474 {"Catalan", "cat"},
\r
475 {"Chamorro", "cha"},
\r
476 {"Chechen", "che"},
\r
477 {"Chinese", "zho"},
\r
478 {"Church Slavic", "chu"},
\r
479 {"Chuvash", "chv"},
\r
480 {"Cornish", "cor"},
\r
481 {"Corsican", "cos"},
\r
486 {"Nederlands", "nld"},
\r
487 {"Dzongkha", "dzo"},
\r
488 {"English", "eng"},
\r
489 {"Esperanto", "epo"},
\r
490 {"Estonian", "est"},
\r
492 {"Faroese", "fao"},
\r
495 {"Francais", "fra"},
\r
496 {"Western Frisian", "fry"},
\r
498 {"Georgian", "kat"},
\r
499 {"Deutsch", "deu"},
\r
500 {"Gaelic (Scots)", "gla"},
\r
502 {"Galician", "glg"},
\r
504 {"Greek Modern", "ell"},
\r
505 {"Guarani", "grn"},
\r
506 {"Gujarati", "guj"},
\r
507 {"Haitian", "hat"},
\r
512 {"Hiri Motu", "hmo"},
\r
515 {"Islenska", "isl"},
\r
517 {"Sichuan Yi", "iii"},
\r
518 {"Inuktitut", "iku"},
\r
519 {"Interlingue", "ile"},
\r
520 {"Interlingua", "ina"},
\r
521 {"Indonesian", "ind"},
\r
522 {"Inupiaq", "ipk"},
\r
523 {"Italiano", "ita"},
\r
524 {"Javanese", "jav"},
\r
525 {"Japanese", "jpn"},
\r
526 {"Kalaallisut", "kal"},
\r
527 {"Kannada", "kan"},
\r
528 {"Kashmiri", "kas"},
\r
531 {"Central Khmer", "khm"},
\r
533 {"Kinyarwanda", "kin"},
\r
534 {"Kirghiz", "kir"},
\r
538 {"Kuanyama", "kua"},
\r
539 {"Kurdish", "kur"},
\r
542 {"Latvian", "lav"},
\r
543 {"Limburgan", "lim"},
\r
544 {"Lingala", "lin"},
\r
545 {"Lithuanian", "lit"},
\r
546 {"Luxembourgish", "ltz"},
\r
547 {"Luba-Katanga", "lub"},
\r
549 {"Macedonian", "mkd"},
\r
550 {"Marshallese", "mah"},
\r
551 {"Malayalam", "mal"},
\r
553 {"Marathi", "mar"},
\r
555 {"Malagasy", "mlg"},
\r
556 {"Maltese", "mlt"},
\r
557 {"Moldavian", "mol"},
\r
558 {"Mongolian", "mon"},
\r
561 {"Ndebele, South", "nbl"},
\r
562 {"Ndebele, North", "nde"},
\r
565 {"Norwegian Nynorsk", "nno"},
\r
566 {"Norwegian Bokmål", "nob"},
\r
568 {"Chichewa; Nyanja", "nya"},
\r
569 {"Occitan", "oci"},
\r
573 {"Ossetian", "oss"},
\r
574 {"Panjabi", "pan"},
\r
575 {"Persian", "fas"},
\r
578 {"Portugues", "por"},
\r
580 {"Quechua", "que"},
\r
581 {"Romansh", "roh"},
\r
582 {"Romanian", "ron"},
\r
584 {"Russian", "rus"},
\r
586 {"Sanskrit", "san"},
\r
587 {"Serbian", "srp"},
\r
588 {"Hrvatski", "hrv"},
\r
589 {"Sinhala", "sin"},
\r
591 {"Slovenian", "slv"},
\r
592 {"Northern Sami", "sme"},
\r
597 {"Sotho Southern", "sot"},
\r
598 {"Espanol", "spa"},
\r
599 {"Sardinian", "srd"},
\r
601 {"Sundanese", "sun"},
\r
602 {"Swahili", "swa"},
\r
603 {"Svenska", "swe"},
\r
604 {"Tahitian", "tah"},
\r
609 {"Tagalog", "tgl"},
\r
611 {"Tibetan", "bod"},
\r
612 {"Tigrinya", "tir"},
\r
616 {"Turkmen", "tuk"},
\r
617 {"Turkish", "tur"},
\r
620 {"Ukrainian", "ukr"},
\r
624 {"Vietnamese", "vie"},
\r
625 {"Volapük", "vol"},
\r
627 {"Walloon", "wln"},
\r
630 {"Yiddish", "yid"},
\r
635 return languageMap;
\r
639 /// Get a list of available DVD drives which are ready and contain DVD content.
\r
641 /// <returns></returns>
\r
642 public static List<DriveInformation> GetDrives()
\r
644 List<DriveInformation> drives = new List<DriveInformation>();
\r
645 DriveInfo[] theCollectionOfDrives = DriveInfo.GetDrives();
\r
646 foreach (DriveInfo curDrive in theCollectionOfDrives)
\r
648 if (curDrive.DriveType == DriveType.CDRom && curDrive.IsReady && File.Exists(curDrive.RootDirectory + "VIDEO_TS\\VIDEO_TS.IFO"))
\r
650 drives.Add(new DriveInformation
\r
652 VolumeLabel = curDrive.VolumeLabel,
\r
653 RootDirectory = curDrive.RootDirectory + "VIDEO_TS"
\r