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
83 public static DataGridView importChapterNames(DataGridView dataChpt, string filename)
\r
85 IDictionary<int, string> chapterMap = new Dictionary<int, string>();
\r
88 StreamReader sr = new StreamReader(filename);
\r
89 string csv = sr.ReadLine();
\r
92 if (csv.Trim() != "")
\r
94 string[] contents = csv.Split(',');
\r
96 int.TryParse(contents[0], out chapter);
\r
97 chapterMap.Add(chapter, contents[1]);
\r
99 csv = sr.ReadLine();
\r
107 foreach (DataGridViewRow item in dataChpt.Rows)
\r
110 chapterMap.TryGetValue((int)item.Cells[0].Value, out name);
\r
111 item.Cells[1].Value = name ?? "Chapter " + item.Cells[0].Value;
\r
118 /// Function which generates the filename and path automatically based on
\r
119 /// the Source Name, DVD title and DVD Chapters
\r
121 public static string autoName(ComboBox drpDvdtitle, string chapter_start, string chatper_end, string source, string dest, int format)
\r
123 string AutoNamePath = string.Empty;
\r
124 if (drpDvdtitle.Text != "Automatic")
\r
126 // Get the Source Name
\r
127 string sourceName = Path.GetFileNameWithoutExtension(source);
\r
129 // Get the Selected Title Number
\r
130 string[] titlesplit = drpDvdtitle.Text.Split(' ');
\r
131 string dvdTitle = titlesplit[0].Replace("Automatic", "");
\r
133 // Get the Chapter Start and Chapter End Numbers
\r
134 string chapterStart = chapter_start.Replace("Auto", "");
\r
135 string chapterFinish = chatper_end.Replace("Auto", "");
\r
136 string combinedChapterTag = chapterStart;
\r
137 if (chapterFinish != chapterStart && chapterFinish != "")
\r
138 combinedChapterTag = chapterStart + "-" + chapterFinish;
\r
140 // Get the destination filename.
\r
141 string destinationFilename;
\r
142 if (Properties.Settings.Default.autoNameFormat != "")
\r
144 destinationFilename = Properties.Settings.Default.autoNameFormat;
\r
145 destinationFilename = destinationFilename.Replace("{source}", sourceName).Replace("{title}", dvdTitle).Replace("{chapters}", combinedChapterTag);
\r
148 destinationFilename = sourceName + "_T" + dvdTitle + "_C" + combinedChapterTag;
\r
150 // Add the appropriate file extension
\r
153 if (Properties.Settings.Default.useM4v)
\r
154 destinationFilename += ".m4v";
\r
156 destinationFilename += ".mp4";
\r
158 else if (format == 1)
\r
159 destinationFilename += ".mkv";
\r
161 // Now work out the path where the file will be stored.
\r
162 // First case: If the destination box doesn't already contain a path, make one.
\r
163 if (!dest.Contains(Path.DirectorySeparatorChar.ToString()))
\r
165 // If there is an auto name path, use it...
\r
166 if (Properties.Settings.Default.autoNamePath.Trim() != "" && Properties.Settings.Default.autoNamePath.Trim() != "Click 'Browse' to set the default location")
\r
167 AutoNamePath = Path.Combine(Properties.Settings.Default.autoNamePath, destinationFilename);
\r
168 else // ...otherwise, output to the source directory
\r
169 AutoNamePath = null;
\r
171 else // Otherwise, use the path that is already there.
\r
173 // Use the path and change the file extension to match the previous destination
\r
174 AutoNamePath = Path.Combine(Path.GetDirectoryName(dest), destinationFilename);
\r
175 AutoNamePath = Path.ChangeExtension(AutoNamePath, Path.GetExtension(dest));
\r
179 return AutoNamePath;
\r
183 /// Get's HandBrakes version data from the CLI.
\r
185 /// <returns>Arraylist of Version Data. 0 = hb_version 1 = hb_build</returns>
\r
186 public static void setCliVersionData()
\r
190 // 0 = SVN Build / Version
\r
192 Process cliProcess = new Process();
\r
193 ProcessStartInfo handBrakeCLI = new ProcessStartInfo("HandBrakeCLI.exe", " -u")
\r
195 UseShellExecute = false,
\r
196 RedirectStandardError = true,
\r
197 RedirectStandardOutput = true,
\r
198 CreateNoWindow = true
\r
200 cliProcess.StartInfo = handBrakeCLI;
\r
204 cliProcess.Start();
\r
205 // Retrieve standard output and report back to parent thread until the process is complete
\r
206 TextReader stdOutput = cliProcess.StandardError;
\r
208 while (!cliProcess.HasExited)
\r
210 line = stdOutput.ReadLine() ?? "";
\r
211 Match m = Regex.Match(line, @"HandBrake ([0-9.]*)(svn[0-9M]*) \([0-9]*\)");
\r
212 Match platform = Regex.Match(line, @"- ([A-Za-z0-9\s ]*) -");
\r
216 string data = line.Replace("(", "").Replace(")", "").Replace("HandBrake ", "");
\r
217 string[] arr = data.Split(' ');
\r
219 Properties.Settings.Default.hb_build = int.Parse(arr[1]);
\r
220 Properties.Settings.Default.hb_version = arr[0];
\r
222 if (platform.Success)
\r
223 Properties.Settings.Default.hb_platform = platform.Value.Replace("-", "").Trim();
\r
225 if (cliProcess.TotalProcessorTime.Seconds > 10) // Don't wait longer than 10 seconds.
\r
227 Process cli = Process.GetProcessById(cliProcess.Id);
\r
228 if (!cli.HasExited)
\r
233 catch (Exception e)
\r
235 MessageBox.Show("Unable to retrieve version information from the CLI. \nError:\n" + e);
\r
240 /// Check if the queue recovery file contains records.
\r
241 /// If it does, it means the last queue did not complete before HandBrake closed.
\r
242 /// So, return a boolean if true.
\r
244 public static Boolean check_queue_recovery()
\r
248 string tempPath = Path.Combine(Path.GetTempPath(), "hb_queue_recovery.xml");
\r
249 if (File.Exists(tempPath))
\r
251 using (FileStream strm = new FileStream(tempPath, FileMode.Open, FileAccess.Read))
\r
253 List<Job> list = ser.Deserialize(strm) as List<Job>;
\r
255 if (list.Count != 0)
\r
263 return false; // Keep quiet about the error.
\r
268 /// Get the Process ID of HandBrakeCLI for the current instance.
\r
270 /// <param name="before">List of processes before the new process was started</param>
\r
271 /// <returns>Int - Process ID</returns>
\r
272 public static int getCliProcess(Process[] before)
\r
274 // This is a bit of a cludge. Maybe someone has a better idea on how to impliment this.
\r
275 // Since we used CMD to start HandBrakeCLI, we don't get the process ID from hbProc.
\r
276 // Instead we take the processes before and after, and get the ID of HandBrakeCLI.exe
\r
277 // avoiding any previous instances of HandBrakeCLI.exe in before.
\r
278 // Kill the current process.
\r
280 DateTime startTime = DateTime.Now;
\r
283 Process[] hbProcesses = Process.GetProcessesByName("HandBrakeCLI");
\r
284 while (hbProcesses.Length == 0)
\r
286 hbProcesses = Process.GetProcessesByName("HandBrakeCLI");
\r
287 duration = DateTime.Now - startTime;
\r
288 if (duration.Seconds > 5 && hbProcesses.Length == 0) // Make sure we don't wait forever if the process doesn't start
\r
292 Process hbProcess = null;
\r
293 foreach (Process process in hbProcesses)
\r
295 Boolean found = false;
\r
296 // Check if the current CLI instance was running before we started the current one
\r
297 foreach (Process bprocess in before)
\r
299 if (process.Id == bprocess.Id)
\r
303 // If it wasn't running before, we found the process we want.
\r
306 hbProcess = process;
\r
310 if (hbProcess != null)
\r
311 return hbProcess.Id;
\r
317 /// Clear all the encode log files.
\r
319 public static void clearLogs()
\r
321 string logDir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\HandBrake\\logs";
\r
322 if (Directory.Exists(logDir))
\r
324 DirectoryInfo info = new DirectoryInfo(logDir);
\r
325 FileInfo[] logFiles = info.GetFiles("*.txt");
\r
326 foreach (FileInfo file in logFiles)
\r
328 if (!file.Name.Contains("last_scan_log") && !file.Name.Contains("last_encode_log") && !file.Name.Contains("tmp_appReadable_log.txt"))
\r
329 File.Delete(file.FullName);
\r
335 /// Begins checking for an update to HandBrake.
\r
337 /// <param name="callback">The method that will be called when the check is finished.</param>
\r
338 /// <param name="debug">Whether or not to execute this in debug mode.</param>
\r
339 public static void BeginCheckForUpdates(AsyncCallback callback, bool debug)
\r
341 ThreadPool.QueueUserWorkItem(new WaitCallback(delegate
\r
345 // Is this a stable or unstable build?
\r
346 string url = Properties.Settings.Default.hb_build.ToString().EndsWith("1") ? Properties.Settings.Default.appcast_unstable : Properties.Settings.Default.appcast;
\r
348 // Initialize variables
\r
349 WebRequest request = WebRequest.Create(url);
\r
350 WebResponse response = request.GetResponse();
\r
351 AppcastReader reader = new AppcastReader();
\r
353 // Get the data, convert it to a string, and parse it into the AppcastReader
\r
354 reader.getInfo(new StreamReader(response.GetResponseStream()).ReadToEnd());
\r
356 // Further parse the information
\r
357 string build = reader.build;
\r
359 int latest = int.Parse(build);
\r
360 int current = Properties.Settings.Default.hb_build;
\r
361 int skip = Properties.Settings.Default.skipversion;
\r
363 // If the user wanted to skip this version, don't report the update
\r
364 if (latest == skip)
\r
366 UpdateCheckInformation info = new UpdateCheckInformation() { NewVersionAvailable = false, BuildInformation = null };
\r
367 callback(new UpdateCheckResult(debug, info));
\r
371 // Set when the last update was
\r
372 Properties.Settings.Default.lastUpdateCheckDate = DateTime.Now;
\r
373 Properties.Settings.Default.Save();
\r
375 UpdateCheckInformation info2 = new UpdateCheckInformation() { NewVersionAvailable = latest > current, BuildInformation = reader };
\r
376 callback(new UpdateCheckResult(debug, info2));
\r
378 catch (Exception exc)
\r
380 callback(new UpdateCheckResult(debug, new UpdateCheckInformation() { Error = exc }));
\r
388 /// <param name="result"></param>
\r
389 /// <returns></returns>
\r
390 public static UpdateCheckInformation EndCheckForUpdates(IAsyncResult result)
\r
392 UpdateCheckResult checkResult = (UpdateCheckResult)result;
\r
393 return checkResult.Result;
\r
397 /// Used in EndUpdateCheck() for update checking and the IAsyncResult design pattern.
\r
399 private class UpdateCheckResult : IAsyncResult
\r
401 public UpdateCheckResult(object asyncState, UpdateCheckInformation info)
\r
403 AsyncState = asyncState;
\r
408 /// Gets whether the check was executed in debug mode.
\r
410 public object AsyncState { get; private set; }
\r
413 /// Gets the result of the update check.
\r
415 public UpdateCheckInformation Result { get; private set; }
\r
417 public WaitHandle AsyncWaitHandle { get { throw new NotImplementedException(); } }
\r
418 public bool CompletedSynchronously { get { throw new NotImplementedException(); } }
\r
419 public bool IsCompleted { get { throw new NotImplementedException(); } }
\r
423 /// Map languages and their iso639_2 value into a IDictionary
\r
425 /// <returns></returns>
\r
426 public static IDictionary<string, string> mapLanguages()
\r
428 IDictionary<string, string> languageMap = new Dictionary<string, string>
\r
432 {"Abkhazian", "abk"},
\r
433 {"Afrikaans", "afr"},
\r
435 {"Albanian", "sqi"},
\r
436 {"Amharic", "amh"},
\r
438 {"Aragonese", "arg"},
\r
439 {"Armenian", "hye"},
\r
440 {"Assamese", "asm"},
\r
442 {"Avestan", "ave"},
\r
444 {"Azerbaijani", "aze"},
\r
445 {"Bashkir", "bak"},
\r
446 {"Bambara", "bam"},
\r
448 {"Belarusian", "bel"},
\r
449 {"Bengali", "ben"},
\r
451 {"Bislama", "bis"},
\r
452 {"Bosnian", "bos"},
\r
454 {"Bulgarian", "bul"},
\r
455 {"Burmese", "mya"},
\r
456 {"Catalan", "cat"},
\r
457 {"Chamorro", "cha"},
\r
458 {"Chechen", "che"},
\r
459 {"Chinese", "zho"},
\r
460 {"Church Slavic", "chu"},
\r
461 {"Chuvash", "chv"},
\r
462 {"Cornish", "cor"},
\r
463 {"Corsican", "cos"},
\r
468 {"Nederlands", "nld"},
\r
469 {"Dzongkha", "dzo"},
\r
470 {"English", "eng"},
\r
471 {"Esperanto", "epo"},
\r
472 {"Estonian", "est"},
\r
474 {"Faroese", "fao"},
\r
477 {"Francais", "fra"},
\r
478 {"Western Frisian", "fry"},
\r
480 {"Georgian", "kat"},
\r
481 {"Deutsch", "deu"},
\r
482 {"Gaelic (Scots)", "gla"},
\r
484 {"Galician", "glg"},
\r
486 {"Greek Modern", "ell"},
\r
487 {"Guarani", "grn"},
\r
488 {"Gujarati", "guj"},
\r
489 {"Haitian", "hat"},
\r
494 {"Hiri Motu", "hmo"},
\r
497 {"Islenska", "isl"},
\r
499 {"Sichuan Yi", "iii"},
\r
500 {"Inuktitut", "iku"},
\r
501 {"Interlingue", "ile"},
\r
502 {"Interlingua", "ina"},
\r
503 {"Indonesian", "ind"},
\r
504 {"Inupiaq", "ipk"},
\r
505 {"Italiano", "ita"},
\r
506 {"Javanese", "jav"},
\r
507 {"Japanese", "jpn"},
\r
508 {"Kalaallisut", "kal"},
\r
509 {"Kannada", "kan"},
\r
510 {"Kashmiri", "kas"},
\r
513 {"Central Khmer", "khm"},
\r
515 {"Kinyarwanda", "kin"},
\r
516 {"Kirghiz", "kir"},
\r
520 {"Kuanyama", "kua"},
\r
521 {"Kurdish", "kur"},
\r
524 {"Latvian", "lav"},
\r
525 {"Limburgan", "lim"},
\r
526 {"Lingala", "lin"},
\r
527 {"Lithuanian", "lit"},
\r
528 {"Luxembourgish", "ltz"},
\r
529 {"Luba-Katanga", "lub"},
\r
531 {"Macedonian", "mkd"},
\r
532 {"Marshallese", "mah"},
\r
533 {"Malayalam", "mal"},
\r
535 {"Marathi", "mar"},
\r
537 {"Malagasy", "mlg"},
\r
538 {"Maltese", "mlt"},
\r
539 {"Moldavian", "mol"},
\r
540 {"Mongolian", "mon"},
\r
543 {"Ndebele, South", "nbl"},
\r
544 {"Ndebele, North", "nde"},
\r
547 {"Norwegian Nynorsk", "nno"},
\r
548 {"Norwegian Bokmål", "nob"},
\r
550 {"Chichewa; Nyanja", "nya"},
\r
551 {"Occitan", "oci"},
\r
555 {"Ossetian", "oss"},
\r
556 {"Panjabi", "pan"},
\r
557 {"Persian", "fas"},
\r
560 {"Portugues", "por"},
\r
562 {"Quechua", "que"},
\r
563 {"Romansh", "roh"},
\r
564 {"Romanian", "ron"},
\r
566 {"Russian", "rus"},
\r
568 {"Sanskrit", "san"},
\r
569 {"Serbian", "srp"},
\r
570 {"Hrvatski", "hrv"},
\r
571 {"Sinhala", "sin"},
\r
573 {"Slovenian", "slv"},
\r
574 {"Northern Sami", "sme"},
\r
579 {"Sotho Southern", "sot"},
\r
580 {"Espanol", "spa"},
\r
581 {"Sardinian", "srd"},
\r
583 {"Sundanese", "sun"},
\r
584 {"Swahili", "swa"},
\r
585 {"Svenska", "swe"},
\r
586 {"Tahitian", "tah"},
\r
591 {"Tagalog", "tgl"},
\r
593 {"Tibetan", "bod"},
\r
594 {"Tigrinya", "tir"},
\r
598 {"Turkmen", "tuk"},
\r
599 {"Turkish", "tur"},
\r
602 {"Ukrainian", "ukr"},
\r
606 {"Vietnamese", "vie"},
\r
607 {"Volapük", "vol"},
\r
609 {"Walloon", "wln"},
\r
612 {"Yiddish", "yid"},
\r
617 return languageMap;
\r