SubtitleEncoder.cs 26 KB

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