SubtitleEncoder.cs 28 KB

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