2
0

SubtitleEncoder.cs 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774
  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, fileInfo.Item3).ConfigureAwait(false);
  139. return new Tuple<Stream, string>(stream, fileInfo.Item2);
  140. }
  141. private async Task<Stream> GetSubtitleStream(string path, string language, bool requiresCharset)
  142. {
  143. if (requiresCharset && !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, bool>> GetReadableFile(string mediaPath,
  162. string[] inputFiles,
  163. MediaProtocol protocol,
  164. MediaStream subtitleStream,
  165. CancellationToken cancellationToken)
  166. {
  167. if (!subtitleStream.IsExternal)
  168. {
  169. string outputFormat;
  170. string outputCodec;
  171. if (string.Equals(subtitleStream.Codec, "ass", StringComparison.OrdinalIgnoreCase))
  172. {
  173. // Extract
  174. outputCodec = "copy";
  175. outputFormat = "ass";
  176. }
  177. else if (string.Equals(subtitleStream.Codec, "subrip", StringComparison.OrdinalIgnoreCase) ||
  178. string.Equals(subtitleStream.Codec, "srt", StringComparison.OrdinalIgnoreCase))
  179. {
  180. // Extract
  181. outputCodec = "copy";
  182. outputFormat = "srt";
  183. }
  184. else
  185. {
  186. // Extract
  187. outputCodec = "srt";
  188. outputFormat = "srt";
  189. }
  190. // Extract
  191. var outputPath = GetSubtitleCachePath(mediaPath, subtitleStream.Index, "." + outputFormat);
  192. await ExtractTextSubtitle(inputFiles, protocol, subtitleStream.Index, outputCodec, outputPath, cancellationToken)
  193. .ConfigureAwait(false);
  194. return new Tuple<string, string, bool>(outputPath, outputFormat, false);
  195. }
  196. var currentFormat = (Path.GetExtension(subtitleStream.Path) ?? subtitleStream.Codec)
  197. .TrimStart('.');
  198. if (GetReader(currentFormat, false) == null)
  199. {
  200. // Convert
  201. var outputPath = GetSubtitleCachePath(mediaPath, subtitleStream.Index, ".srt");
  202. await ConvertTextSubtitleToSrt(subtitleStream.Path, outputPath, subtitleStream.Language, cancellationToken)
  203. .ConfigureAwait(false);
  204. return new Tuple<string, string, bool>(outputPath, "srt", false);
  205. }
  206. return new Tuple<string, string, bool>(subtitleStream.Path, currentFormat, false);
  207. }
  208. private async Task<SubtitleTrackInfo> GetTrackInfo(Stream stream,
  209. string inputFormat,
  210. CancellationToken cancellationToken)
  211. {
  212. var reader = GetReader(inputFormat, true);
  213. return reader.Parse(stream, cancellationToken);
  214. }
  215. private ISubtitleParser GetReader(string format, bool throwIfMissing)
  216. {
  217. if (string.IsNullOrEmpty(format))
  218. {
  219. throw new ArgumentNullException("format");
  220. }
  221. if (string.Equals(format, SubtitleFormat.SRT, StringComparison.OrdinalIgnoreCase))
  222. {
  223. return new SrtParser();
  224. }
  225. if (string.Equals(format, SubtitleFormat.SSA, StringComparison.OrdinalIgnoreCase))
  226. {
  227. return new SsaParser();
  228. }
  229. if (string.Equals(format, SubtitleFormat.ASS, StringComparison.OrdinalIgnoreCase))
  230. {
  231. return new AssParser();
  232. }
  233. if (throwIfMissing)
  234. {
  235. throw new ArgumentException("Unsupported format: " + format);
  236. }
  237. return null;
  238. }
  239. private ISubtitleWriter GetWriter(string format)
  240. {
  241. if (string.IsNullOrEmpty(format))
  242. {
  243. throw new ArgumentNullException("format");
  244. }
  245. if (string.Equals(format, "json", StringComparison.OrdinalIgnoreCase))
  246. {
  247. return new JsonWriter(_json);
  248. }
  249. if (string.Equals(format, SubtitleFormat.SRT, StringComparison.OrdinalIgnoreCase))
  250. {
  251. return new SrtWriter();
  252. }
  253. if (string.Equals(format, SubtitleFormat.VTT, StringComparison.OrdinalIgnoreCase))
  254. {
  255. return new VttWriter();
  256. }
  257. if (string.Equals(format, SubtitleFormat.TTML, StringComparison.OrdinalIgnoreCase))
  258. {
  259. return new TtmlWriter();
  260. }
  261. throw new ArgumentException("Unsupported format: " + format);
  262. }
  263. /// <summary>
  264. /// The _semaphoreLocks
  265. /// </summary>
  266. private readonly ConcurrentDictionary<string, SemaphoreSlim> _semaphoreLocks =
  267. new ConcurrentDictionary<string, SemaphoreSlim>();
  268. /// <summary>
  269. /// Gets the lock.
  270. /// </summary>
  271. /// <param name="filename">The filename.</param>
  272. /// <returns>System.Object.</returns>
  273. private SemaphoreSlim GetLock(string filename)
  274. {
  275. return _semaphoreLocks.GetOrAdd(filename, key => new SemaphoreSlim(1, 1));
  276. }
  277. /// <summary>
  278. /// Converts the text subtitle to SRT.
  279. /// </summary>
  280. /// <param name="inputPath">The input path.</param>
  281. /// <param name="outputPath">The output path.</param>
  282. /// <param name="language">The language.</param>
  283. /// <param name="cancellationToken">The cancellation token.</param>
  284. /// <returns>Task.</returns>
  285. public async Task ConvertTextSubtitleToSrt(string inputPath, string outputPath, string language,
  286. CancellationToken cancellationToken)
  287. {
  288. var semaphore = GetLock(outputPath);
  289. await semaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
  290. try
  291. {
  292. if (!File.Exists(outputPath))
  293. {
  294. await ConvertTextSubtitleToSrtInternal(inputPath, outputPath, language).ConfigureAwait(false);
  295. }
  296. }
  297. finally
  298. {
  299. semaphore.Release();
  300. }
  301. }
  302. /// <summary>
  303. /// Converts the text subtitle to SRT internal.
  304. /// </summary>
  305. /// <param name="inputPath">The input path.</param>
  306. /// <param name="outputPath">The output path.</param>
  307. /// <param name="language">The language.</param>
  308. /// <returns>Task.</returns>
  309. /// <exception cref="System.ArgumentNullException">
  310. /// inputPath
  311. /// or
  312. /// outputPath
  313. /// </exception>
  314. /// <exception cref="System.ApplicationException"></exception>
  315. private async Task ConvertTextSubtitleToSrtInternal(string inputPath, string outputPath, string language)
  316. {
  317. if (string.IsNullOrEmpty(inputPath))
  318. {
  319. throw new ArgumentNullException("inputPath");
  320. }
  321. if (string.IsNullOrEmpty(outputPath))
  322. {
  323. throw new ArgumentNullException("outputPath");
  324. }
  325. Directory.CreateDirectory(Path.GetDirectoryName(outputPath));
  326. var encodingParam = string.IsNullOrEmpty(language)
  327. ? string.Empty
  328. : GetSubtitleFileCharacterSet(inputPath, language);
  329. if (!string.IsNullOrEmpty(encodingParam))
  330. {
  331. encodingParam = " -sub_charenc " + encodingParam;
  332. }
  333. var process = new Process
  334. {
  335. StartInfo = new ProcessStartInfo
  336. {
  337. RedirectStandardOutput = false,
  338. RedirectStandardError = true,
  339. RedirectStandardInput = true,
  340. CreateNoWindow = true,
  341. UseShellExecute = false,
  342. FileName = _mediaEncoder.EncoderPath,
  343. Arguments = string.Format("{0} -i \"{1}\" -c:s srt \"{2}\"", encodingParam, inputPath, outputPath),
  344. WindowStyle = ProcessWindowStyle.Hidden,
  345. ErrorDialog = false
  346. }
  347. };
  348. _logger.Debug("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments);
  349. var logFilePath = Path.Combine(_appPaths.LogDirectoryPath, "ffmpeg-sub-convert-" + Guid.NewGuid() + ".txt");
  350. Directory.CreateDirectory(Path.GetDirectoryName(logFilePath));
  351. var logFileStream = _fileSystem.GetFileStream(logFilePath, FileMode.Create, FileAccess.Write, FileShare.Read,
  352. true);
  353. try
  354. {
  355. process.Start();
  356. }
  357. catch (Exception ex)
  358. {
  359. logFileStream.Dispose();
  360. _logger.ErrorException("Error starting ffmpeg", ex);
  361. throw;
  362. }
  363. var logTask = process.StandardError.BaseStream.CopyToAsync(logFileStream);
  364. var ranToCompletion = process.WaitForExit(60000);
  365. if (!ranToCompletion)
  366. {
  367. try
  368. {
  369. _logger.Info("Killing ffmpeg subtitle conversion process");
  370. process.StandardInput.WriteLine("q");
  371. process.WaitForExit(1000);
  372. await logTask.ConfigureAwait(false);
  373. }
  374. catch (Exception ex)
  375. {
  376. _logger.ErrorException("Error killing subtitle conversion process", ex);
  377. }
  378. finally
  379. {
  380. logFileStream.Dispose();
  381. }
  382. }
  383. var exitCode = ranToCompletion ? process.ExitCode : -1;
  384. process.Dispose();
  385. var failed = false;
  386. if (exitCode == -1)
  387. {
  388. failed = true;
  389. if (File.Exists(outputPath))
  390. {
  391. try
  392. {
  393. _logger.Info("Deleting converted subtitle due to failure: ", outputPath);
  394. File.Delete(outputPath);
  395. }
  396. catch (IOException ex)
  397. {
  398. _logger.ErrorException("Error deleting converted subtitle {0}", ex, outputPath);
  399. }
  400. }
  401. }
  402. else if (!File.Exists(outputPath))
  403. {
  404. failed = true;
  405. }
  406. if (failed)
  407. {
  408. var msg = string.Format("ffmpeg subtitle converted failed for {0}", inputPath);
  409. _logger.Error(msg);
  410. throw new ApplicationException(msg);
  411. }
  412. await SetAssFont(outputPath).ConfigureAwait(false);
  413. }
  414. /// <summary>
  415. /// Extracts the text subtitle.
  416. /// </summary>
  417. /// <param name="inputFiles">The input files.</param>
  418. /// <param name="protocol">The protocol.</param>
  419. /// <param name="subtitleStreamIndex">Index of the subtitle stream.</param>
  420. /// <param name="outputCodec">The output codec.</param>
  421. /// <param name="outputPath">The output path.</param>
  422. /// <param name="cancellationToken">The cancellation token.</param>
  423. /// <returns>Task.</returns>
  424. /// <exception cref="System.ArgumentException">Must use inputPath list overload</exception>
  425. private async Task ExtractTextSubtitle(string[] inputFiles, MediaProtocol protocol, int subtitleStreamIndex,
  426. string outputCodec, string outputPath, CancellationToken cancellationToken)
  427. {
  428. var semaphore = GetLock(outputPath);
  429. await semaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
  430. try
  431. {
  432. if (!File.Exists(outputPath))
  433. {
  434. await ExtractTextSubtitleInternal(_mediaEncoder.GetInputArgument(inputFiles, protocol), subtitleStreamIndex,
  435. outputCodec, outputPath, cancellationToken).ConfigureAwait(false);
  436. }
  437. }
  438. finally
  439. {
  440. semaphore.Release();
  441. }
  442. }
  443. private async Task ExtractTextSubtitleInternal(string inputPath, int subtitleStreamIndex,
  444. string outputCodec, string outputPath, CancellationToken cancellationToken)
  445. {
  446. if (string.IsNullOrEmpty(inputPath))
  447. {
  448. throw new ArgumentNullException("inputPath");
  449. }
  450. if (string.IsNullOrEmpty(outputPath))
  451. {
  452. throw new ArgumentNullException("outputPath");
  453. }
  454. Directory.CreateDirectory(Path.GetDirectoryName(outputPath));
  455. var processArgs = string.Format("-i {0} -map 0:{1} -an -vn -c:s {2} \"{3}\"", inputPath,
  456. subtitleStreamIndex, outputCodec, outputPath);
  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. if (string.Equals(outputCodec, "ass", StringComparison.OrdinalIgnoreCase))
  541. {
  542. await SetAssFont(outputPath).ConfigureAwait(false);
  543. }
  544. }
  545. /// <summary>
  546. /// Sets the ass font.
  547. /// </summary>
  548. /// <param name="file">The file.</param>
  549. /// <returns>Task.</returns>
  550. private async Task SetAssFont(string file)
  551. {
  552. _logger.Info("Setting ass font within {0}", file);
  553. string text;
  554. Encoding encoding;
  555. using (var reader = new StreamReader(file, true))
  556. {
  557. encoding = reader.CurrentEncoding;
  558. text = await reader.ReadToEndAsync().ConfigureAwait(false);
  559. }
  560. var newText = text.Replace(",Arial,", ",Arial Unicode MS,");
  561. if (!string.Equals(text, newText))
  562. {
  563. using (var writer = new StreamWriter(file, false, encoding))
  564. {
  565. writer.Write(newText);
  566. }
  567. }
  568. }
  569. private string GetSubtitleCachePath(string mediaPath, int subtitleStreamIndex, string outputSubtitleExtension)
  570. {
  571. var ticksParam = string.Empty;
  572. var date = _fileSystem.GetLastWriteTimeUtc(mediaPath);
  573. var filename = (mediaPath + "_" + subtitleStreamIndex.ToString(CultureInfo.InvariantCulture) + "_" + date.Ticks.ToString(CultureInfo.InvariantCulture) + ticksParam).GetMD5() + outputSubtitleExtension;
  574. var prefix = filename.Substring(0, 1);
  575. return Path.Combine(SubtitleCachePath, prefix, filename);
  576. }
  577. /// <summary>
  578. /// Gets the subtitle language encoding param.
  579. /// </summary>
  580. /// <param name="path">The path.</param>
  581. /// <param name="language">The language.</param>
  582. /// <returns>System.String.</returns>
  583. public string GetSubtitleFileCharacterSet(string path, string language)
  584. {
  585. if (GetFileEncoding(path).Equals(Encoding.UTF8))
  586. {
  587. return string.Empty;
  588. }
  589. switch (language.ToLower())
  590. {
  591. case "pol":
  592. case "cze":
  593. case "ces":
  594. case "slo":
  595. case "slk":
  596. case "hun":
  597. case "slv":
  598. case "srp":
  599. case "hrv":
  600. case "rum":
  601. case "ron":
  602. case "rup":
  603. case "alb":
  604. case "sqi":
  605. return "windows-1250";
  606. case "ara":
  607. return "windows-1256";
  608. case "heb":
  609. return "windows-1255";
  610. case "grc":
  611. case "gre":
  612. return "windows-1253";
  613. case "crh":
  614. case "ota":
  615. case "tur":
  616. return "windows-1254";
  617. case "rus":
  618. return "windows-1251";
  619. case "vie":
  620. return "windows-1258";
  621. case "kor":
  622. return "cp949";
  623. default:
  624. return "windows-1252";
  625. }
  626. }
  627. private static Encoding GetFileEncoding(string srcFile)
  628. {
  629. // *** Detect byte order mark if any - otherwise assume default
  630. var buffer = new byte[5];
  631. using (var file = new FileStream(srcFile, FileMode.Open))
  632. {
  633. file.Read(buffer, 0, 5);
  634. }
  635. if (buffer[0] == 0xef && buffer[1] == 0xbb && buffer[2] == 0xbf)
  636. return Encoding.UTF8;
  637. if (buffer[0] == 0xfe && buffer[1] == 0xff)
  638. return Encoding.Unicode;
  639. if (buffer[0] == 0 && buffer[1] == 0 && buffer[2] == 0xfe && buffer[3] == 0xff)
  640. return Encoding.UTF32;
  641. if (buffer[0] == 0x2b && buffer[1] == 0x2f && buffer[2] == 0x76)
  642. return Encoding.UTF7;
  643. // It's ok - anything aside from utf is ok since that's what we're looking for
  644. return Encoding.Default;
  645. }
  646. }
  647. }