SubtitleEncoder.cs 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739
  1. using MediaBrowser.Common.Configuration;
  2. using MediaBrowser.Common.Extensions;
  3. using MediaBrowser.Common.IO;
  4. using MediaBrowser.Controller.Entities;
  5. using MediaBrowser.Controller.Library;
  6. using MediaBrowser.Controller.MediaEncoding;
  7. using MediaBrowser.Model.Entities;
  8. using MediaBrowser.Model.Logging;
  9. using MediaBrowser.Model.MediaInfo;
  10. using System;
  11. using System.Collections.Concurrent;
  12. using System.Diagnostics;
  13. using System.Globalization;
  14. using System.IO;
  15. using System.Linq;
  16. using System.Text;
  17. using System.Threading;
  18. using System.Threading.Tasks;
  19. namespace MediaBrowser.MediaEncoding.Subtitles
  20. {
  21. public class SubtitleEncoder : ISubtitleEncoder
  22. {
  23. private readonly ILibraryManager _libraryManager;
  24. private readonly ILogger _logger;
  25. private readonly IApplicationPaths _appPaths;
  26. private readonly IFileSystem _fileSystem;
  27. private readonly IMediaEncoder _mediaEncoder;
  28. public SubtitleEncoder(ILibraryManager libraryManager, ILogger logger, IApplicationPaths appPaths, IFileSystem fileSystem, IMediaEncoder mediaEncoder)
  29. {
  30. _libraryManager = libraryManager;
  31. _logger = logger;
  32. _appPaths = appPaths;
  33. _fileSystem = fileSystem;
  34. _mediaEncoder = mediaEncoder;
  35. }
  36. private string SubtitleCachePath
  37. {
  38. get
  39. {
  40. return Path.Combine(_appPaths.CachePath, "subtitles");
  41. }
  42. }
  43. public async Task<Stream> ConvertSubtitles(Stream stream,
  44. string inputFormat,
  45. string outputFormat,
  46. long startTimeTicks,
  47. CancellationToken cancellationToken)
  48. {
  49. var ms = new MemoryStream();
  50. try
  51. {
  52. // Return the original without any conversions, if possible
  53. if (startTimeTicks == 0 &&
  54. string.Equals(inputFormat, outputFormat, StringComparison.OrdinalIgnoreCase))
  55. {
  56. await stream.CopyToAsync(ms, 81920, cancellationToken).ConfigureAwait(false);
  57. }
  58. else
  59. {
  60. var trackInfo = await GetTrackInfo(stream, inputFormat, cancellationToken).ConfigureAwait(false);
  61. UpdateStartingPosition(trackInfo, startTimeTicks);
  62. var writer = GetWriter(outputFormat);
  63. writer.Write(trackInfo, ms, cancellationToken);
  64. }
  65. ms.Position = 0;
  66. }
  67. catch
  68. {
  69. ms.Dispose();
  70. throw;
  71. }
  72. return ms;
  73. }
  74. private void UpdateStartingPosition(SubtitleTrackInfo track, long startPositionTicks)
  75. {
  76. if (startPositionTicks == 0) return;
  77. foreach (var trackEvent in track.TrackEvents)
  78. {
  79. trackEvent.EndPositionTicks -= startPositionTicks;
  80. trackEvent.StartPositionTicks -= startPositionTicks;
  81. }
  82. track.TrackEvents = track.TrackEvents
  83. .SkipWhile(i => i.StartPositionTicks < 0 || i.EndPositionTicks < 0)
  84. .ToList();
  85. }
  86. public async Task<Stream> GetSubtitles(string itemId,
  87. string mediaSourceId,
  88. int subtitleStreamIndex,
  89. string outputFormat,
  90. long startTimeTicks,
  91. CancellationToken cancellationToken)
  92. {
  93. var subtitle = await GetSubtitleStream(itemId, mediaSourceId, subtitleStreamIndex, cancellationToken)
  94. .ConfigureAwait(false);
  95. using (var stream = subtitle.Item1)
  96. {
  97. var inputFormat = subtitle.Item2;
  98. return await ConvertSubtitles(stream, inputFormat, outputFormat, startTimeTicks, cancellationToken).ConfigureAwait(false);
  99. }
  100. }
  101. private async Task<Tuple<Stream, string>> GetSubtitleStream(string itemId,
  102. string mediaSourceId,
  103. int subtitleStreamIndex,
  104. CancellationToken cancellationToken)
  105. {
  106. var item = (Video)_libraryManager.GetItemById(new Guid(itemId));
  107. var mediaSource = item.GetMediaSources(false)
  108. .First(i => string.Equals(i.Id, mediaSourceId));
  109. var subtitleStream = mediaSource.MediaStreams
  110. .First(i => i.Type == MediaStreamType.Subtitle && i.Index == subtitleStreamIndex);
  111. var inputFiles = new[] { mediaSource.Path };
  112. if (mediaSource.VideoType.HasValue)
  113. {
  114. if (mediaSource.VideoType.Value == VideoType.BluRay ||
  115. mediaSource.VideoType.Value == VideoType.Dvd)
  116. {
  117. var mediaSourceItem = (Video)_libraryManager.GetItemById(new Guid(mediaSourceId));
  118. inputFiles = mediaSourceItem.GetPlayableStreamFiles().ToArray();
  119. }
  120. }
  121. var fileInfo = await GetReadableFile(mediaSource.Path, inputFiles, mediaSource.Protocol, subtitleStream, cancellationToken).ConfigureAwait(false);
  122. var stream = await GetSubtitleStream(fileInfo.Item1, subtitleStream.Language).ConfigureAwait(false);
  123. return new Tuple<Stream, string>(stream, fileInfo.Item2);
  124. }
  125. private async Task<Stream> GetSubtitleStream(string path, string language)
  126. {
  127. if (!string.IsNullOrEmpty(language))
  128. {
  129. var charset = GetSubtitleFileCharacterSet(path, language);
  130. if (!string.IsNullOrEmpty(charset))
  131. {
  132. using (var fs = _fileSystem.GetFileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, true))
  133. {
  134. using (var reader = new StreamReader(fs, Encoding.GetEncoding(charset)))
  135. {
  136. var text = await reader.ReadToEndAsync().ConfigureAwait(false);
  137. var bytes = Encoding.UTF8.GetBytes(text);
  138. return new MemoryStream(bytes);
  139. }
  140. }
  141. }
  142. }
  143. return File.OpenRead(path);
  144. }
  145. private async Task<Tuple<string, string>> GetReadableFile(string mediaPath,
  146. string[] inputFiles,
  147. MediaProtocol protocol,
  148. MediaStream subtitleStream,
  149. CancellationToken cancellationToken)
  150. {
  151. if (!subtitleStream.IsExternal)
  152. {
  153. // Extract
  154. var outputPath = GetSubtitleCachePath(mediaPath, subtitleStream.Index, ".ass");
  155. await ExtractTextSubtitle(inputFiles, protocol, subtitleStream.Index, false, outputPath, cancellationToken)
  156. .ConfigureAwait(false);
  157. return new Tuple<string, string>(outputPath, "ass");
  158. }
  159. var currentFormat = (Path.GetExtension(subtitleStream.Path) ?? subtitleStream.Codec)
  160. .TrimStart('.');
  161. if (GetReader(currentFormat, false) == null)
  162. {
  163. // Convert
  164. var outputPath = GetSubtitleCachePath(mediaPath, subtitleStream.Index, ".ass");
  165. await ConvertTextSubtitleToAss(subtitleStream.Path, outputPath, subtitleStream.Language, cancellationToken)
  166. .ConfigureAwait(false);
  167. return new Tuple<string, string>(outputPath, "ass");
  168. }
  169. return new Tuple<string, string>(subtitleStream.Path, currentFormat);
  170. }
  171. private async Task<SubtitleTrackInfo> GetTrackInfo(Stream stream,
  172. string inputFormat,
  173. CancellationToken cancellationToken)
  174. {
  175. var reader = GetReader(inputFormat, true);
  176. return reader.Parse(stream, cancellationToken);
  177. }
  178. private ISubtitleParser GetReader(string format, bool throwIfMissing)
  179. {
  180. if (string.IsNullOrEmpty(format))
  181. {
  182. throw new ArgumentNullException("format");
  183. }
  184. if (string.Equals(format, SubtitleFormat.SRT, StringComparison.OrdinalIgnoreCase))
  185. {
  186. return new SrtParser();
  187. }
  188. if (string.Equals(format, SubtitleFormat.SSA, StringComparison.OrdinalIgnoreCase) ||
  189. string.Equals(format, SubtitleFormat.ASS, StringComparison.OrdinalIgnoreCase))
  190. {
  191. return new SsaParser();
  192. }
  193. if (throwIfMissing)
  194. {
  195. throw new ArgumentException("Unsupported format: " + format);
  196. }
  197. return null;
  198. }
  199. private ISubtitleWriter GetWriter(string format)
  200. {
  201. if (string.IsNullOrEmpty(format))
  202. {
  203. throw new ArgumentNullException("format");
  204. }
  205. if (string.Equals(format, SubtitleFormat.SRT, StringComparison.OrdinalIgnoreCase))
  206. {
  207. return new SrtWriter();
  208. }
  209. if (string.Equals(format, SubtitleFormat.VTT, StringComparison.OrdinalIgnoreCase))
  210. {
  211. return new VttWriter();
  212. }
  213. throw new ArgumentException("Unsupported format: " + format);
  214. }
  215. /// <summary>
  216. /// The _semaphoreLocks
  217. /// </summary>
  218. private readonly ConcurrentDictionary<string, SemaphoreSlim> _semaphoreLocks =
  219. new ConcurrentDictionary<string, SemaphoreSlim>();
  220. /// <summary>
  221. /// Gets the lock.
  222. /// </summary>
  223. /// <param name="filename">The filename.</param>
  224. /// <returns>System.Object.</returns>
  225. private SemaphoreSlim GetLock(string filename)
  226. {
  227. return _semaphoreLocks.GetOrAdd(filename, key => new SemaphoreSlim(1, 1));
  228. }
  229. /// <summary>
  230. /// Converts the text subtitle to ass.
  231. /// </summary>
  232. /// <param name="inputPath">The input path.</param>
  233. /// <param name="outputPath">The output path.</param>
  234. /// <param name="language">The language.</param>
  235. /// <param name="cancellationToken">The cancellation token.</param>
  236. /// <returns>Task.</returns>
  237. public async Task ConvertTextSubtitleToAss(string inputPath, string outputPath, string language,
  238. CancellationToken cancellationToken)
  239. {
  240. var semaphore = GetLock(outputPath);
  241. await semaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
  242. try
  243. {
  244. if (!File.Exists(outputPath))
  245. {
  246. await ConvertTextSubtitleToAssInternal(inputPath, outputPath, language).ConfigureAwait(false);
  247. }
  248. }
  249. finally
  250. {
  251. semaphore.Release();
  252. }
  253. }
  254. /// <summary>
  255. /// Converts the text subtitle to ass.
  256. /// </summary>
  257. /// <param name="inputPath">The input path.</param>
  258. /// <param name="outputPath">The output path.</param>
  259. /// <param name="language">The language.</param>
  260. /// <returns>Task.</returns>
  261. /// <exception cref="System.ArgumentNullException">inputPath
  262. /// or
  263. /// outputPath</exception>
  264. /// <exception cref="System.ApplicationException"></exception>
  265. private async Task ConvertTextSubtitleToAssInternal(string inputPath, string outputPath, string language)
  266. {
  267. if (string.IsNullOrEmpty(inputPath))
  268. {
  269. throw new ArgumentNullException("inputPath");
  270. }
  271. if (string.IsNullOrEmpty(outputPath))
  272. {
  273. throw new ArgumentNullException("outputPath");
  274. }
  275. Directory.CreateDirectory(Path.GetDirectoryName(outputPath));
  276. var encodingParam = string.IsNullOrEmpty(language)
  277. ? string.Empty
  278. : GetSubtitleFileCharacterSet(inputPath, language);
  279. if (!string.IsNullOrEmpty(encodingParam))
  280. {
  281. encodingParam = " -sub_charenc " + encodingParam;
  282. }
  283. var process = new Process
  284. {
  285. StartInfo = new ProcessStartInfo
  286. {
  287. RedirectStandardOutput = false,
  288. RedirectStandardError = true,
  289. RedirectStandardInput = true,
  290. CreateNoWindow = true,
  291. UseShellExecute = false,
  292. FileName = _mediaEncoder.EncoderPath,
  293. Arguments = string.Format("{0} -i \"{1}\" -c:s ass \"{2}\"", encodingParam, inputPath, outputPath),
  294. WindowStyle = ProcessWindowStyle.Hidden,
  295. ErrorDialog = false
  296. }
  297. };
  298. _logger.Debug("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments);
  299. var logFilePath = Path.Combine(_appPaths.LogDirectoryPath, "ffmpeg-sub-convert-" + Guid.NewGuid() + ".txt");
  300. Directory.CreateDirectory(Path.GetDirectoryName(logFilePath));
  301. var logFileStream = _fileSystem.GetFileStream(logFilePath, FileMode.Create, FileAccess.Write, FileShare.Read,
  302. true);
  303. try
  304. {
  305. process.Start();
  306. }
  307. catch (Exception ex)
  308. {
  309. logFileStream.Dispose();
  310. _logger.ErrorException("Error starting ffmpeg", ex);
  311. throw;
  312. }
  313. var logTask = process.StandardError.BaseStream.CopyToAsync(logFileStream);
  314. var ranToCompletion = process.WaitForExit(60000);
  315. if (!ranToCompletion)
  316. {
  317. try
  318. {
  319. _logger.Info("Killing ffmpeg subtitle conversion process");
  320. process.StandardInput.WriteLine("q");
  321. process.WaitForExit(1000);
  322. await logTask.ConfigureAwait(false);
  323. }
  324. catch (Exception ex)
  325. {
  326. _logger.ErrorException("Error killing subtitle conversion process", ex);
  327. }
  328. finally
  329. {
  330. logFileStream.Dispose();
  331. }
  332. }
  333. var exitCode = ranToCompletion ? process.ExitCode : -1;
  334. process.Dispose();
  335. var failed = false;
  336. if (exitCode == -1)
  337. {
  338. failed = true;
  339. if (File.Exists(outputPath))
  340. {
  341. try
  342. {
  343. _logger.Info("Deleting converted subtitle due to failure: ", outputPath);
  344. File.Delete(outputPath);
  345. }
  346. catch (IOException ex)
  347. {
  348. _logger.ErrorException("Error deleting converted subtitle {0}", ex, outputPath);
  349. }
  350. }
  351. }
  352. else if (!File.Exists(outputPath))
  353. {
  354. failed = true;
  355. }
  356. if (failed)
  357. {
  358. var msg = string.Format("ffmpeg subtitle converted failed for {0}", inputPath);
  359. _logger.Error(msg);
  360. throw new ApplicationException(msg);
  361. }
  362. await SetAssFont(outputPath).ConfigureAwait(false);
  363. }
  364. /// <summary>
  365. /// Extracts the text subtitle.
  366. /// </summary>
  367. /// <param name="inputFiles">The input files.</param>
  368. /// <param name="protocol">The protocol.</param>
  369. /// <param name="subtitleStreamIndex">Index of the subtitle stream.</param>
  370. /// <param name="copySubtitleStream">if set to true, copy stream instead of converting.</param>
  371. /// <param name="outputPath">The output path.</param>
  372. /// <param name="cancellationToken">The cancellation token.</param>
  373. /// <returns>Task.</returns>
  374. /// <exception cref="System.ArgumentException">Must use inputPath list overload</exception>
  375. private async Task ExtractTextSubtitle(string[] inputFiles, MediaProtocol protocol, int subtitleStreamIndex,
  376. bool copySubtitleStream, string outputPath, CancellationToken cancellationToken)
  377. {
  378. var semaphore = GetLock(outputPath);
  379. await semaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
  380. try
  381. {
  382. if (!File.Exists(outputPath))
  383. {
  384. await ExtractTextSubtitleInternal(_mediaEncoder.GetInputArgument(inputFiles, protocol), subtitleStreamIndex,
  385. copySubtitleStream, outputPath, cancellationToken).ConfigureAwait(false);
  386. }
  387. }
  388. finally
  389. {
  390. semaphore.Release();
  391. }
  392. }
  393. /// <summary>
  394. /// Extracts the text subtitle.
  395. /// </summary>
  396. /// <param name="inputPath">The input path.</param>
  397. /// <param name="subtitleStreamIndex">Index of the subtitle stream.</param>
  398. /// <param name="copySubtitleStream">if set to true, copy stream instead of converting.</param>
  399. /// <param name="outputPath">The output path.</param>
  400. /// <param name="cancellationToken">The cancellation token.</param>
  401. /// <returns>Task.</returns>
  402. /// <exception cref="System.ArgumentNullException">inputPath
  403. /// or
  404. /// outputPath
  405. /// or
  406. /// cancellationToken</exception>
  407. /// <exception cref="System.ApplicationException"></exception>
  408. private async Task ExtractTextSubtitleInternal(string inputPath, int subtitleStreamIndex,
  409. bool copySubtitleStream, string outputPath, CancellationToken cancellationToken)
  410. {
  411. if (string.IsNullOrEmpty(inputPath))
  412. {
  413. throw new ArgumentNullException("inputPath");
  414. }
  415. if (string.IsNullOrEmpty(outputPath))
  416. {
  417. throw new ArgumentNullException("outputPath");
  418. }
  419. Directory.CreateDirectory(Path.GetDirectoryName(outputPath));
  420. var processArgs = string.Format("-i {0} -map 0:{1} -an -vn -c:s ass \"{2}\"", inputPath,
  421. subtitleStreamIndex, outputPath);
  422. if (copySubtitleStream)
  423. {
  424. processArgs = string.Format("-i {0} -map 0:{1} -an -vn -c:s copy \"{2}\"", inputPath,
  425. subtitleStreamIndex, outputPath);
  426. }
  427. var process = new Process
  428. {
  429. StartInfo = new ProcessStartInfo
  430. {
  431. CreateNoWindow = true,
  432. UseShellExecute = false,
  433. RedirectStandardOutput = false,
  434. RedirectStandardError = true,
  435. RedirectStandardInput = true,
  436. FileName = _mediaEncoder.EncoderPath,
  437. Arguments = processArgs,
  438. WindowStyle = ProcessWindowStyle.Hidden,
  439. ErrorDialog = false
  440. }
  441. };
  442. _logger.Debug("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments);
  443. var logFilePath = Path.Combine(_appPaths.LogDirectoryPath, "ffmpeg-sub-extract-" + Guid.NewGuid() + ".txt");
  444. Directory.CreateDirectory(Path.GetDirectoryName(logFilePath));
  445. var logFileStream = _fileSystem.GetFileStream(logFilePath, FileMode.Create, FileAccess.Write, FileShare.Read,
  446. true);
  447. try
  448. {
  449. process.Start();
  450. }
  451. catch (Exception ex)
  452. {
  453. logFileStream.Dispose();
  454. _logger.ErrorException("Error starting ffmpeg", ex);
  455. throw;
  456. }
  457. process.StandardError.BaseStream.CopyToAsync(logFileStream);
  458. var ranToCompletion = process.WaitForExit(60000);
  459. if (!ranToCompletion)
  460. {
  461. try
  462. {
  463. _logger.Info("Killing ffmpeg subtitle extraction process");
  464. process.StandardInput.WriteLine("q");
  465. process.WaitForExit(1000);
  466. }
  467. catch (Exception ex)
  468. {
  469. _logger.ErrorException("Error killing subtitle extraction process", ex);
  470. }
  471. finally
  472. {
  473. logFileStream.Dispose();
  474. }
  475. }
  476. var exitCode = ranToCompletion ? process.ExitCode : -1;
  477. process.Dispose();
  478. var failed = false;
  479. if (exitCode == -1)
  480. {
  481. failed = true;
  482. if (File.Exists(outputPath))
  483. {
  484. try
  485. {
  486. _logger.Info("Deleting extracted subtitle due to failure: ", outputPath);
  487. File.Delete(outputPath);
  488. }
  489. catch (IOException ex)
  490. {
  491. _logger.ErrorException("Error deleting extracted subtitle {0}", ex, outputPath);
  492. }
  493. }
  494. }
  495. else if (!File.Exists(outputPath))
  496. {
  497. failed = true;
  498. }
  499. if (failed)
  500. {
  501. var msg = string.Format("ffmpeg subtitle extraction failed for {0} to {1}", inputPath, outputPath);
  502. _logger.Error(msg);
  503. throw new ApplicationException(msg);
  504. }
  505. else
  506. {
  507. var msg = string.Format("ffmpeg subtitle extraction completed for {0} to {1}", inputPath, outputPath);
  508. _logger.Info(msg);
  509. }
  510. await SetAssFont(outputPath).ConfigureAwait(false);
  511. }
  512. /// <summary>
  513. /// Sets the ass font.
  514. /// </summary>
  515. /// <param name="file">The file.</param>
  516. /// <returns>Task.</returns>
  517. private async Task SetAssFont(string file)
  518. {
  519. _logger.Info("Setting ass font within {0}", file);
  520. string text;
  521. Encoding encoding;
  522. using (var reader = new StreamReader(file, true))
  523. {
  524. encoding = reader.CurrentEncoding;
  525. text = await reader.ReadToEndAsync().ConfigureAwait(false);
  526. }
  527. var newText = text.Replace(",Arial,", ",Arial Unicode MS,");
  528. if (!string.Equals(text, newText))
  529. {
  530. using (var writer = new StreamWriter(file, false, encoding))
  531. {
  532. writer.Write(newText);
  533. }
  534. }
  535. }
  536. private string GetSubtitleCachePath(string mediaPath, int subtitleStreamIndex, string outputSubtitleExtension)
  537. {
  538. var ticksParam = string.Empty;
  539. var date = _fileSystem.GetLastWriteTimeUtc(mediaPath);
  540. var filename = (mediaPath + "_" + subtitleStreamIndex.ToString(CultureInfo.InvariantCulture) + "_" + date.Ticks.ToString(CultureInfo.InvariantCulture) + ticksParam).GetMD5() + outputSubtitleExtension;
  541. var prefix = filename.Substring(0, 1);
  542. return Path.Combine(SubtitleCachePath, prefix, filename);
  543. }
  544. /// <summary>
  545. /// Gets the subtitle language encoding param.
  546. /// </summary>
  547. /// <param name="path">The path.</param>
  548. /// <param name="language">The language.</param>
  549. /// <returns>System.String.</returns>
  550. public string GetSubtitleFileCharacterSet(string path, string language)
  551. {
  552. if (GetFileEncoding(path).Equals(Encoding.UTF8))
  553. {
  554. return string.Empty;
  555. }
  556. switch (language.ToLower())
  557. {
  558. case "pol":
  559. case "cze":
  560. case "ces":
  561. case "slo":
  562. case "slk":
  563. case "hun":
  564. case "slv":
  565. case "srp":
  566. case "hrv":
  567. case "rum":
  568. case "ron":
  569. case "rup":
  570. case "alb":
  571. case "sqi":
  572. return "windows-1250";
  573. case "ara":
  574. return "windows-1256";
  575. case "heb":
  576. return "windows-1255";
  577. case "grc":
  578. case "gre":
  579. return "windows-1253";
  580. case "crh":
  581. case "ota":
  582. case "tur":
  583. return "windows-1254";
  584. case "rus":
  585. return "windows-1251";
  586. case "vie":
  587. return "windows-1258";
  588. case "kor":
  589. return "cp949";
  590. default:
  591. return "windows-1252";
  592. }
  593. }
  594. private static Encoding GetFileEncoding(string srcFile)
  595. {
  596. // *** Detect byte order mark if any - otherwise assume default
  597. var buffer = new byte[5];
  598. using (var file = new FileStream(srcFile, FileMode.Open))
  599. {
  600. file.Read(buffer, 0, 5);
  601. }
  602. if (buffer[0] == 0xef && buffer[1] == 0xbb && buffer[2] == 0xbf)
  603. return Encoding.UTF8;
  604. if (buffer[0] == 0xfe && buffer[1] == 0xff)
  605. return Encoding.Unicode;
  606. if (buffer[0] == 0 && buffer[1] == 0 && buffer[2] == 0xfe && buffer[3] == 0xff)
  607. return Encoding.UTF32;
  608. if (buffer[0] == 0x2b && buffer[1] == 0x2f && buffer[2] == 0x76)
  609. return Encoding.UTF7;
  610. // It's ok - anything aside from utf is ok since that's what we're looking for
  611. return Encoding.Default;
  612. }
  613. }
  614. }