SubtitleEncoder.cs 27 KB

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