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
18 namespace Handbrake.Functions
\r
22 // Private Variables
\r
23 private static readonly XmlSerializer ser = new XmlSerializer(typeof(List<Job>));
\r
26 /// Calculate the duration of the selected title and chapters
\r
28 public static TimeSpan calculateDuration(int chapterStart, int chapterEnd, Parsing.Title selectedTitle)
\r
30 TimeSpan duration = TimeSpan.FromSeconds(0.0);
\r
31 chapterStart++; chapterEnd++;
\r
32 if (chapterStart != 0 && chapterEnd != 0 && chapterEnd <= selectedTitle.Chapters.Count)
\r
34 for (int i = chapterStart; i <= chapterEnd; i++)
\r
35 duration += selectedTitle.Chapters[i - 1].Duration;
\r
42 /// Select the longest title in the DVD title dropdown menu on frmMain
\r
44 public static Parsing.Title selectLongestTitle(Parsing.DVD thisDvd)
\r
46 TimeSpan longestDurationFound = TimeSpan.FromSeconds(0.0);
\r
47 Parsing.Title returnTitle = null;
\r
49 foreach (Parsing.Title item in thisDvd.Titles)
\r
51 if (item.Duration > longestDurationFound)
\r
54 longestDurationFound = item.Duration;
\r
61 /// Set's up the DataGridView on the Chapters tab (frmMain)
\r
63 public static DataGridView chapterNaming(DataGridView dataChpt, string chapterEnd)
\r
65 int i = 0, finish = 0;
\r
67 if (chapterEnd != "Auto")
\r
68 int.TryParse(chapterEnd, out finish);
\r
72 int n = dataChpt.Rows.Add();
\r
73 dataChpt.Rows[n].Cells[0].Value = (i + 1);
\r
74 dataChpt.Rows[n].Cells[1].Value = "Chapter " + (i + 1);
\r
75 dataChpt.Rows[n].Cells[0].ValueType = typeof(int);
\r
76 dataChpt.Rows[n].Cells[1].ValueType = typeof(string);
\r
84 /// Import a CSV file which contains Chapter Names
\r
86 /// <param name="dataChpt"></param>
\r
87 /// <param name="filename"></param>
\r
88 /// <returns></returns>
\r
89 public static DataGridView importChapterNames(DataGridView dataChpt, string filename)
\r
91 IDictionary<int, string> chapterMap = new Dictionary<int, string>();
\r
94 StreamReader sr = new StreamReader(filename);
\r
95 string csv = sr.ReadLine();
\r
98 if (csv.Trim() != "")
\r
100 string[] contents = csv.Split(',');
\r
102 int.TryParse(contents[0], out chapter);
\r
103 chapterMap.Add(chapter, contents[1]);
\r
105 csv = sr.ReadLine();
\r
113 foreach (DataGridViewRow item in dataChpt.Rows)
\r
116 chapterMap.TryGetValue((int)item.Cells[0].Value, out name);
\r
117 item.Cells[1].Value = name ?? "Chapter " + item.Cells[0].Value;
\r
124 /// Function which generates the filename and path automatically based on
\r
125 /// the Source Name, DVD title and DVD Chapters
\r
127 public static string autoName(frmMain mainWindow) //ComboBox drpDvdtitle, string chapter_start, string chatper_end, string source, string dest, int format, Boolean chapters)
\r
129 string AutoNamePath = string.Empty;
\r
130 if (mainWindow.drp_dvdtitle.Text != "Automatic")
\r
132 // Get the Source Name
\r
133 string sourceName = mainWindow.SourceName;
\r
135 // Get the Selected Title Number
\r
136 string[] titlesplit = mainWindow.drp_dvdtitle.Text.Split(' ');
\r
137 string dvdTitle = titlesplit[0].Replace("Automatic", "");
\r
139 // Get the Chapter Start and Chapter End Numbers
\r
140 string chapterStart = mainWindow.drop_chapterStart.Text.Replace("Auto", "");
\r
141 string chapterFinish = mainWindow.drop_chapterFinish.Text.Replace("Auto", "");
\r
142 string combinedChapterTag = chapterStart;
\r
143 if (chapterFinish != chapterStart && chapterFinish != "")
\r
144 combinedChapterTag = chapterStart + "-" + chapterFinish;
\r
146 // Get the destination filename.
\r
147 string destinationFilename;
\r
148 if (Properties.Settings.Default.autoNameFormat != "")
\r
150 destinationFilename = Properties.Settings.Default.autoNameFormat;
\r
151 destinationFilename = destinationFilename.Replace("{source}", sourceName).Replace("{title}", dvdTitle).Replace("{chapters}", combinedChapterTag);
\r
154 destinationFilename = sourceName + "_T" + dvdTitle + "_C" + combinedChapterTag;
\r
156 // Add the appropriate file extension
\r
157 if (mainWindow.drop_format.SelectedIndex == 0)
\r
159 if (Properties.Settings.Default.useM4v || mainWindow.Check_ChapterMarkers.Checked || mainWindow.AudioSettings.RequiresM4V() || mainWindow.Subtitles.RequiresM4V())
\r
160 destinationFilename += ".m4v";
\r
162 destinationFilename += ".mp4";
\r
164 else if (mainWindow.drop_format.SelectedIndex == 1)
\r
165 destinationFilename += ".mkv";
\r
167 // Now work out the path where the file will be stored.
\r
168 // First case: If the destination box doesn't already contain a path, make one.
\r
169 if (!mainWindow.text_destination.Text.Contains(Path.DirectorySeparatorChar.ToString()))
\r
171 // If there is an auto name path, use it...
\r
172 if (Properties.Settings.Default.autoNamePath.Trim() != "" && Properties.Settings.Default.autoNamePath.Trim() != "Click 'Browse' to set the default location")
\r
173 AutoNamePath = Path.Combine(Properties.Settings.Default.autoNamePath, destinationFilename);
\r
174 else // ...otherwise, output to the source directory
\r
175 AutoNamePath = null;
\r
177 else // Otherwise, use the path that is already there.
\r
179 // Use the path and change the file extension to match the previous destination
\r
180 AutoNamePath = Path.Combine(Path.GetDirectoryName(mainWindow.text_destination.Text), destinationFilename);
\r
182 if (Path.HasExtension(mainWindow.text_destination.Text))
\r
183 AutoNamePath = Path.ChangeExtension(AutoNamePath, Path.GetExtension(mainWindow.text_destination.Text));
\r
187 return AutoNamePath;
\r
191 /// Get's HandBrakes version data from the CLI.
\r
193 /// <returns>Arraylist of Version Data. 0 = hb_version 1 = hb_build</returns>
\r
194 public static void setCliVersionData()
\r
198 // 0 = SVN Build / Version
\r
201 DateTime lastModified = File.GetLastWriteTime("HandBrakeCLI.exe");
\r
204 if (Properties.Settings.Default.cliLastModified == lastModified && Properties.Settings.Default.hb_build != 0)
\r
207 Properties.Settings.Default.cliLastModified = lastModified;
\r
209 Process cliProcess = new Process();
\r
210 ProcessStartInfo handBrakeCLI = new ProcessStartInfo("HandBrakeCLI.exe", " -u -v0")
\r
212 UseShellExecute = false,
\r
213 RedirectStandardError = true,
\r
214 RedirectStandardOutput = true,
\r
215 CreateNoWindow = true
\r
217 cliProcess.StartInfo = handBrakeCLI;
\r
221 cliProcess.Start();
\r
222 // Retrieve standard output and report back to parent thread until the process is complete
\r
223 TextReader stdOutput = cliProcess.StandardError;
\r
225 while (!cliProcess.HasExited)
\r
227 line = stdOutput.ReadLine() ?? "";
\r
228 Match m = Regex.Match(line, @"HandBrake ([svnM0-9.]*) \([0-9]*\)");
\r
229 Match platform = Regex.Match(line, @"- ([A-Za-z0-9\s ]*) -");
\r
233 string data = line.Replace("(", "").Replace(")", "").Replace("HandBrake ", "");
\r
234 string[] arr = data.Split(' ');
\r
236 Properties.Settings.Default.hb_build = int.Parse(arr[1]);
\r
237 Properties.Settings.Default.hb_version = arr[0];
\r
239 if (platform.Success)
\r
240 Properties.Settings.Default.hb_platform = platform.Value.Replace("-", "").Trim();
\r
242 if (cliProcess.TotalProcessorTime.Seconds > 10) // Don't wait longer than 10 seconds.
\r
244 Process cli = Process.GetProcessById(cliProcess.Id);
\r
245 if (!cli.HasExited)
\r
249 Properties.Settings.Default.Save();
\r
251 catch (Exception e)
\r
253 MessageBox.Show("Unable to retrieve version information from the CLI. \nError:\n" + e);
\r
258 /// Check if the queue recovery file contains records.
\r
259 /// If it does, it means the last queue did not complete before HandBrake closed.
\r
260 /// So, return a boolean if true.
\r
262 public static Boolean checkQueueRecovery()
\r
266 string tempPath = Path.Combine(Path.GetTempPath(), "hb_queue_recovery.xml");
\r
267 if (File.Exists(tempPath))
\r
269 using (FileStream strm = new FileStream(tempPath, FileMode.Open, FileAccess.Read))
\r
271 List<Job> list = ser.Deserialize(strm) as List<Job>;
\r
273 if (list.Count != 0)
\r
281 return false; // Keep quiet about the error.
\r
286 /// Get the Process ID of HandBrakeCLI for the current instance.
\r
288 /// <param name="before">List of processes before the new process was started</param>
\r
289 /// <returns>Int - Process ID</returns>
\r
290 public static int getCliProcess(Process[] before)
\r
292 // This is a bit of a cludge. Maybe someone has a better idea on how to impliment this.
\r
293 // Since we used CMD to start HandBrakeCLI, we don't get the process ID from hbProc.
\r
294 // Instead we take the processes before and after, and get the ID of HandBrakeCLI.exe
\r
295 // avoiding any previous instances of HandBrakeCLI.exe in before.
\r
296 // Kill the current process.
\r
298 DateTime startTime = DateTime.Now;
\r
301 Process[] hbProcesses = Process.GetProcessesByName("HandBrakeCLI");
\r
302 while (hbProcesses.Length == 0)
\r
304 hbProcesses = Process.GetProcessesByName("HandBrakeCLI");
\r
305 duration = DateTime.Now - startTime;
\r
306 if (duration.Seconds > 5 && hbProcesses.Length == 0) // Make sure we don't wait forever if the process doesn't start
\r
310 Process hbProcess = null;
\r
311 foreach (Process process in hbProcesses)
\r
313 Boolean found = false;
\r
314 // Check if the current CLI instance was running before we started the current one
\r
315 foreach (Process bprocess in before)
\r
317 if (process.Id == bprocess.Id)
\r
321 // If it wasn't running before, we found the process we want.
\r
324 hbProcess = process;
\r
328 if (hbProcess != null)
\r
329 return hbProcess.Id;
\r
335 /// Clear all the encode log files.
\r
337 public static void clearLogs()
\r
339 string logDir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\HandBrake\\logs";
\r
340 if (Directory.Exists(logDir))
\r
342 DirectoryInfo info = new DirectoryInfo(logDir);
\r
343 FileInfo[] logFiles = info.GetFiles("*.txt");
\r
344 foreach (FileInfo file in logFiles)
\r
346 if (!file.Name.Contains("last_scan_log") && !file.Name.Contains("last_encode_log") && !file.Name.Contains("tmp_appReadable_log.txt"))
\r
347 File.Delete(file.FullName);
\r
353 /// Begins checking for an update to HandBrake.
\r
355 /// <param name="callback">The method that will be called when the check is finished.</param>
\r
356 /// <param name="debug">Whether or not to execute this in debug mode.</param>
\r
357 public static void BeginCheckForUpdates(AsyncCallback callback, bool debug)
\r
359 ThreadPool.QueueUserWorkItem(new WaitCallback(delegate
\r
363 // Is this a stable or unstable build?
\r
364 string url = Properties.Settings.Default.hb_build.ToString().EndsWith("1") ? Properties.Settings.Default.appcast_unstable : Properties.Settings.Default.appcast;
\r
366 // Initialize variables
\r
367 WebRequest request = WebRequest.Create(url);
\r
368 WebResponse response = request.GetResponse();
\r
369 AppcastReader reader = new AppcastReader();
\r
371 // Get the data, convert it to a string, and parse it into the AppcastReader
\r
372 reader.getInfo(new StreamReader(response.GetResponseStream()).ReadToEnd());
\r
374 // Further parse the information
\r
375 string build = reader.build;
\r
377 int latest = int.Parse(build);
\r
378 int current = Properties.Settings.Default.hb_build;
\r
379 int skip = Properties.Settings.Default.skipversion;
\r
381 // If the user wanted to skip this version, don't report the update
\r
382 if (latest == skip)
\r
384 UpdateCheckInformation info = new UpdateCheckInformation() { NewVersionAvailable = false, BuildInformation = null };
\r
385 callback(new UpdateCheckResult(debug, info));
\r
389 // Set when the last update was
\r
390 Properties.Settings.Default.lastUpdateCheckDate = DateTime.Now;
\r
391 Properties.Settings.Default.Save();
\r
393 UpdateCheckInformation info2 = new UpdateCheckInformation() { NewVersionAvailable = latest > current, BuildInformation = reader };
\r
394 callback(new UpdateCheckResult(debug, info2));
\r
396 catch (Exception exc)
\r
398 callback(new UpdateCheckResult(debug, new UpdateCheckInformation() { Error = exc }));
\r
406 /// <param name="result"></param>
\r
407 /// <returns></returns>
\r
408 public static UpdateCheckInformation EndCheckForUpdates(IAsyncResult result)
\r
410 UpdateCheckResult checkResult = (UpdateCheckResult)result;
\r
411 return checkResult.Result;
\r
415 /// Used in EndUpdateCheck() for update checking and the IAsyncResult design pattern.
\r
417 private class UpdateCheckResult : IAsyncResult
\r
419 public UpdateCheckResult(object asyncState, UpdateCheckInformation info)
\r
421 AsyncState = asyncState;
\r
426 /// Gets whether the check was executed in debug mode.
\r
428 public object AsyncState { get; private set; }
\r
431 /// Gets the result of the update check.
\r
433 public UpdateCheckInformation Result { get; private set; }
\r
435 public WaitHandle AsyncWaitHandle { get { throw new NotImplementedException(); } }
\r
436 public bool CompletedSynchronously { get { throw new NotImplementedException(); } }
\r
437 public bool IsCompleted { get { throw new NotImplementedException(); } }
\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