SubtitleEncoder.cs 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763
  1. using System;
  2. using System.Collections.Concurrent;
  3. using System.Globalization;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Text;
  7. using System.Threading;
  8. using System.Threading.Tasks;
  9. using MediaBrowser.Common.Configuration;
  10. using MediaBrowser.Common.Extensions;
  11. using MediaBrowser.Common.Net;
  12. using MediaBrowser.Controller.Entities;
  13. using MediaBrowser.Controller.Library;
  14. using MediaBrowser.Controller.MediaEncoding;
  15. using MediaBrowser.Model.Diagnostics;
  16. using MediaBrowser.Model.Dto;
  17. using MediaBrowser.Model.Entities;
  18. using MediaBrowser.Model.IO;
  19. using MediaBrowser.Model.MediaInfo;
  20. using Microsoft.Extensions.Logging;
  21. using UtfUnknown;
  22. namespace MediaBrowser.MediaEncoding.Subtitles
  23. {
  24. public class SubtitleEncoder : ISubtitleEncoder
  25. {
  26. private readonly ILibraryManager _libraryManager;
  27. private readonly ILogger _logger;
  28. private readonly IApplicationPaths _appPaths;
  29. private readonly IFileSystem _fileSystem;
  30. private readonly IMediaEncoder _mediaEncoder;
  31. private readonly IHttpClient _httpClient;
  32. private readonly IMediaSourceManager _mediaSourceManager;
  33. private readonly IProcessFactory _processFactory;
  34. public SubtitleEncoder(
  35. ILibraryManager libraryManager,
  36. ILogger<SubtitleEncoder> logger,
  37. IApplicationPaths appPaths,
  38. IFileSystem fileSystem,
  39. IMediaEncoder mediaEncoder,
  40. IHttpClient httpClient,
  41. IMediaSourceManager mediaSourceManager,
  42. IProcessFactory processFactory)
  43. {
  44. _libraryManager = libraryManager;
  45. _logger = logger;
  46. _appPaths = appPaths;
  47. _fileSystem = fileSystem;
  48. _mediaEncoder = mediaEncoder;
  49. _httpClient = httpClient;
  50. _mediaSourceManager = mediaSourceManager;
  51. _processFactory = processFactory;
  52. }
  53. private string SubtitleCachePath => Path.Combine(_appPaths.DataPath, "subtitles");
  54. private Stream ConvertSubtitles(
  55. Stream stream,
  56. string inputFormat,
  57. string outputFormat,
  58. long startTimeTicks,
  59. long endTimeTicks,
  60. bool preserveOriginalTimestamps,
  61. CancellationToken cancellationToken)
  62. {
  63. var ms = new MemoryStream();
  64. try
  65. {
  66. var reader = GetReader(inputFormat, true);
  67. var trackInfo = reader.Parse(stream, cancellationToken);
  68. FilterEvents(trackInfo, startTimeTicks, endTimeTicks, preserveOriginalTimestamps);
  69. var writer = GetWriter(outputFormat);
  70. writer.Write(trackInfo, ms, cancellationToken);
  71. ms.Position = 0;
  72. }
  73. catch
  74. {
  75. ms.Dispose();
  76. throw;
  77. }
  78. return ms;
  79. }
  80. private void FilterEvents(SubtitleTrackInfo track, long startPositionTicks, long endTimeTicks, bool preserveTimestamps)
  81. {
  82. // Drop subs that are earlier than what we're looking for
  83. track.TrackEvents = track.TrackEvents
  84. .SkipWhile(i => (i.StartPositionTicks - startPositionTicks) < 0 || (i.EndPositionTicks - startPositionTicks) < 0)
  85. .ToArray();
  86. if (endTimeTicks > 0)
  87. {
  88. track.TrackEvents = track.TrackEvents
  89. .TakeWhile(i => i.StartPositionTicks <= endTimeTicks)
  90. .ToArray();
  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. async Task<Stream> ISubtitleEncoder.GetSubtitles(BaseItem item, string mediaSourceId, int subtitleStreamIndex, string outputFormat, long startTimeTicks, long endTimeTicks, bool preserveOriginalTimestamps, CancellationToken cancellationToken)
  102. {
  103. if (item == null)
  104. {
  105. throw new ArgumentNullException(nameof(item));
  106. }
  107. if (string.IsNullOrWhiteSpace(mediaSourceId))
  108. {
  109. throw new ArgumentNullException(nameof(mediaSourceId));
  110. }
  111. var mediaSources = await _mediaSourceManager.GetPlaybackMediaSources(item, null, true, false, cancellationToken).ConfigureAwait(false);
  112. var mediaSource = mediaSources
  113. .First(i => string.Equals(i.Id, mediaSourceId, StringComparison.OrdinalIgnoreCase));
  114. var subtitleStream = mediaSource.MediaStreams
  115. .First(i => i.Type == MediaStreamType.Subtitle && i.Index == subtitleStreamIndex);
  116. var subtitle = await GetSubtitleStream(mediaSource, subtitleStream, cancellationToken)
  117. .ConfigureAwait(false);
  118. var inputFormat = subtitle.format;
  119. var writer = TryGetWriter(outputFormat);
  120. // Return the original if we don't have any way of converting it
  121. if (writer == null)
  122. {
  123. return subtitle.stream;
  124. }
  125. // Return the original if the same format is being requested
  126. // Character encoding was already handled in GetSubtitleStream
  127. if (string.Equals(inputFormat, outputFormat, StringComparison.OrdinalIgnoreCase))
  128. {
  129. return subtitle.stream;
  130. }
  131. using (var stream = subtitle.stream)
  132. {
  133. return ConvertSubtitles(stream, inputFormat, outputFormat, startTimeTicks, endTimeTicks, preserveOriginalTimestamps, cancellationToken);
  134. }
  135. }
  136. private async Task<(Stream stream, string format)> GetSubtitleStream(
  137. MediaSourceInfo mediaSource,
  138. MediaStream subtitleStream,
  139. CancellationToken cancellationToken)
  140. {
  141. string[] inputFiles;
  142. if (mediaSource.VideoType.HasValue
  143. && (mediaSource.VideoType.Value == VideoType.BluRay || mediaSource.VideoType.Value == VideoType.Dvd))
  144. {
  145. var mediaSourceItem = (Video)_libraryManager.GetItemById(new Guid(mediaSource.Id));
  146. inputFiles = mediaSourceItem.GetPlayableStreamFileNames();
  147. }
  148. else
  149. {
  150. inputFiles = new[] { mediaSource.Path };
  151. }
  152. var fileInfo = await GetReadableFile(mediaSource.Path, inputFiles, mediaSource.Protocol, subtitleStream, cancellationToken).ConfigureAwait(false);
  153. var stream = await GetSubtitleStream(fileInfo.Path, fileInfo.Protocol, fileInfo.IsExternal, cancellationToken).ConfigureAwait(false);
  154. return (stream, fileInfo.Format);
  155. }
  156. private async Task<Stream> GetSubtitleStream(string path, MediaProtocol protocol, bool requiresCharset, CancellationToken cancellationToken)
  157. {
  158. using (var stream = await GetStream(path, protocol, cancellationToken).ConfigureAwait(false))
  159. {
  160. if (requiresCharset)
  161. {
  162. var result = CharsetDetector.DetectFromStream(stream).Detected;
  163. stream.Position = 0;
  164. if (result != null)
  165. {
  166. _logger.LogDebug("charset {CharSet} detected for {Path}", result.EncodingName, path);
  167. using var reader = new StreamReader(stream, result.Encoding);
  168. var text = await reader.ReadToEndAsync().ConfigureAwait(false);
  169. return new MemoryStream(Encoding.UTF8.GetBytes(text));
  170. }
  171. }
  172. return stream;
  173. }
  174. }
  175. private async Task<SubtitleInfo> GetReadableFile(
  176. string mediaPath,
  177. string[] inputFiles,
  178. MediaProtocol protocol,
  179. MediaStream subtitleStream,
  180. CancellationToken cancellationToken)
  181. {
  182. if (!subtitleStream.IsExternal)
  183. {
  184. string outputFormat;
  185. string outputCodec;
  186. if (string.Equals(subtitleStream.Codec, "ass", StringComparison.OrdinalIgnoreCase) ||
  187. string.Equals(subtitleStream.Codec, "ssa", StringComparison.OrdinalIgnoreCase) ||
  188. string.Equals(subtitleStream.Codec, "srt", StringComparison.OrdinalIgnoreCase))
  189. {
  190. // Extract
  191. outputCodec = "copy";
  192. outputFormat = subtitleStream.Codec;
  193. }
  194. else if (string.Equals(subtitleStream.Codec, "subrip", StringComparison.OrdinalIgnoreCase))
  195. {
  196. // Extract
  197. outputCodec = "copy";
  198. outputFormat = "srt";
  199. }
  200. else
  201. {
  202. // Extract
  203. outputCodec = "srt";
  204. outputFormat = "srt";
  205. }
  206. // Extract
  207. var outputPath = GetSubtitleCachePath(mediaPath, protocol, subtitleStream.Index, "." + outputFormat);
  208. await ExtractTextSubtitle(inputFiles, protocol, subtitleStream.Index, outputCodec, outputPath, cancellationToken)
  209. .ConfigureAwait(false);
  210. return new SubtitleInfo(outputPath, MediaProtocol.File, outputFormat, false);
  211. }
  212. var currentFormat = (Path.GetExtension(subtitleStream.Path) ?? subtitleStream.Codec)
  213. .TrimStart('.');
  214. if (GetReader(currentFormat, false) == null)
  215. {
  216. // Convert
  217. var outputPath = GetSubtitleCachePath(mediaPath, protocol, subtitleStream.Index, ".srt");
  218. await ConvertTextSubtitleToSrt(subtitleStream.Path, subtitleStream.Language, protocol, outputPath, cancellationToken).ConfigureAwait(false);
  219. return new SubtitleInfo(outputPath, MediaProtocol.File, "srt", true);
  220. }
  221. return new SubtitleInfo(subtitleStream.Path, protocol, currentFormat, true);
  222. }
  223. private struct SubtitleInfo
  224. {
  225. public SubtitleInfo(string path, MediaProtocol protocol, string format, bool isExternal)
  226. {
  227. Path = path;
  228. Protocol = protocol;
  229. Format = format;
  230. IsExternal = isExternal;
  231. }
  232. public string Path { get; set; }
  233. public MediaProtocol Protocol { get; set; }
  234. public string Format { get; set; }
  235. public bool IsExternal { get; set; }
  236. }
  237. private ISubtitleParser GetReader(string format, bool throwIfMissing)
  238. {
  239. if (string.IsNullOrEmpty(format))
  240. {
  241. throw new ArgumentNullException(nameof(format));
  242. }
  243. if (string.Equals(format, SubtitleFormat.SRT, StringComparison.OrdinalIgnoreCase))
  244. {
  245. return new SrtParser(_logger);
  246. }
  247. if (string.Equals(format, SubtitleFormat.SSA, StringComparison.OrdinalIgnoreCase))
  248. {
  249. return new SsaParser();
  250. }
  251. if (string.Equals(format, SubtitleFormat.ASS, StringComparison.OrdinalIgnoreCase))
  252. {
  253. return new AssParser();
  254. }
  255. if (throwIfMissing)
  256. {
  257. throw new ArgumentException("Unsupported format: " + format);
  258. }
  259. return null;
  260. }
  261. private ISubtitleWriter TryGetWriter(string format)
  262. {
  263. if (string.IsNullOrEmpty(format))
  264. {
  265. throw new ArgumentNullException(nameof(format));
  266. }
  267. if (string.Equals(format, "json", StringComparison.OrdinalIgnoreCase))
  268. {
  269. return new JsonWriter();
  270. }
  271. if (string.Equals(format, SubtitleFormat.SRT, StringComparison.OrdinalIgnoreCase))
  272. {
  273. return new SrtWriter();
  274. }
  275. if (string.Equals(format, SubtitleFormat.VTT, StringComparison.OrdinalIgnoreCase))
  276. {
  277. return new VttWriter();
  278. }
  279. if (string.Equals(format, SubtitleFormat.TTML, StringComparison.OrdinalIgnoreCase))
  280. {
  281. return new TtmlWriter();
  282. }
  283. return null;
  284. }
  285. private ISubtitleWriter GetWriter(string format)
  286. {
  287. var writer = TryGetWriter(format);
  288. if (writer != null)
  289. {
  290. return writer;
  291. }
  292. throw new ArgumentException("Unsupported format: " + format);
  293. }
  294. /// <summary>
  295. /// The _semaphoreLocks
  296. /// </summary>
  297. private readonly ConcurrentDictionary<string, SemaphoreSlim> _semaphoreLocks =
  298. new ConcurrentDictionary<string, SemaphoreSlim>();
  299. /// <summary>
  300. /// Gets the lock.
  301. /// </summary>
  302. /// <param name="filename">The filename.</param>
  303. /// <returns>System.Object.</returns>
  304. private SemaphoreSlim GetLock(string filename)
  305. {
  306. return _semaphoreLocks.GetOrAdd(filename, key => new SemaphoreSlim(1, 1));
  307. }
  308. /// <summary>
  309. /// Converts the text subtitle to SRT.
  310. /// </summary>
  311. /// <param name="inputPath">The input path.</param>
  312. /// <param name="inputProtocol">The input protocol.</param>
  313. /// <param name="outputPath">The output path.</param>
  314. /// <param name="cancellationToken">The cancellation token.</param>
  315. /// <returns>Task.</returns>
  316. private async Task ConvertTextSubtitleToSrt(string inputPath, string language, MediaProtocol inputProtocol, string outputPath, CancellationToken cancellationToken)
  317. {
  318. var semaphore = GetLock(outputPath);
  319. await semaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
  320. try
  321. {
  322. if (!File.Exists(outputPath))
  323. {
  324. await ConvertTextSubtitleToSrtInternal(inputPath, language, inputProtocol, outputPath, cancellationToken).ConfigureAwait(false);
  325. }
  326. }
  327. finally
  328. {
  329. semaphore.Release();
  330. }
  331. }
  332. /// <summary>
  333. /// Converts the text subtitle to SRT internal.
  334. /// </summary>
  335. /// <param name="inputPath">The input path.</param>
  336. /// <param name="inputProtocol">The input protocol.</param>
  337. /// <param name="outputPath">The output path.</param>
  338. /// <param name="cancellationToken">The cancellation token.</param>
  339. /// <returns>Task.</returns>
  340. /// <exception cref="ArgumentNullException">
  341. /// inputPath
  342. /// or
  343. /// outputPath
  344. /// </exception>
  345. private async Task ConvertTextSubtitleToSrtInternal(string inputPath, string language, MediaProtocol inputProtocol, string outputPath, CancellationToken cancellationToken)
  346. {
  347. if (string.IsNullOrEmpty(inputPath))
  348. {
  349. throw new ArgumentNullException(nameof(inputPath));
  350. }
  351. if (string.IsNullOrEmpty(outputPath))
  352. {
  353. throw new ArgumentNullException(nameof(outputPath));
  354. }
  355. Directory.CreateDirectory(Path.GetDirectoryName(outputPath));
  356. var encodingParam = await GetSubtitleFileCharacterSet(inputPath, language, inputProtocol, cancellationToken).ConfigureAwait(false);
  357. // FFmpeg automatically convert character encoding when it is UTF-16
  358. // If we specify character encoding, it rejects with "do not specify a character encoding" and "Unable to recode subtitle event"
  359. if ((inputPath.EndsWith(".smi") || inputPath.EndsWith(".sami")) && (encodingParam == "UTF-16BE" || encodingParam == "UTF-16LE"))
  360. {
  361. encodingParam = "";
  362. }
  363. else if (!string.IsNullOrEmpty(encodingParam))
  364. {
  365. encodingParam = " -sub_charenc " + encodingParam;
  366. }
  367. var process = _processFactory.Create(new ProcessOptions
  368. {
  369. CreateNoWindow = true,
  370. UseShellExecute = false,
  371. FileName = _mediaEncoder.EncoderPath,
  372. Arguments = string.Format("{0} -i \"{1}\" -c:s srt \"{2}\"", encodingParam, inputPath, outputPath),
  373. EnableRaisingEvents = true,
  374. IsHidden = true,
  375. ErrorDialog = false
  376. });
  377. _logger.LogInformation("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments);
  378. try
  379. {
  380. process.Start();
  381. }
  382. catch (Exception ex)
  383. {
  384. _logger.LogError(ex, "Error starting ffmpeg");
  385. throw;
  386. }
  387. var ranToCompletion = await process.WaitForExitAsync(300000).ConfigureAwait(false);
  388. if (!ranToCompletion)
  389. {
  390. try
  391. {
  392. _logger.LogInformation("Killing ffmpeg subtitle conversion process");
  393. process.Kill();
  394. }
  395. catch (Exception ex)
  396. {
  397. _logger.LogError(ex, "Error killing subtitle conversion process");
  398. }
  399. }
  400. var exitCode = ranToCompletion ? process.ExitCode : -1;
  401. process.Dispose();
  402. var failed = false;
  403. if (exitCode == -1)
  404. {
  405. failed = true;
  406. if (File.Exists(outputPath))
  407. {
  408. try
  409. {
  410. _logger.LogInformation("Deleting converted subtitle due to failure: ", outputPath);
  411. _fileSystem.DeleteFile(outputPath);
  412. }
  413. catch (IOException ex)
  414. {
  415. _logger.LogError(ex, "Error deleting converted subtitle {Path}", outputPath);
  416. }
  417. }
  418. }
  419. else if (!File.Exists(outputPath))
  420. {
  421. failed = true;
  422. }
  423. if (failed)
  424. {
  425. _logger.LogError("ffmpeg subtitle conversion failed for {Path}", inputPath);
  426. throw new Exception(
  427. string.Format(CultureInfo.InvariantCulture, "ffmpeg subtitle conversion failed for {0}", inputPath));
  428. }
  429. await SetAssFont(outputPath).ConfigureAwait(false);
  430. _logger.LogInformation("ffmpeg subtitle conversion succeeded for {Path}", inputPath);
  431. }
  432. /// <summary>
  433. /// Extracts the text subtitle.
  434. /// </summary>
  435. /// <param name="inputFiles">The input files.</param>
  436. /// <param name="protocol">The protocol.</param>
  437. /// <param name="subtitleStreamIndex">Index of the subtitle stream.</param>
  438. /// <param name="outputCodec">The output codec.</param>
  439. /// <param name="outputPath">The output path.</param>
  440. /// <param name="cancellationToken">The cancellation token.</param>
  441. /// <returns>Task.</returns>
  442. /// <exception cref="ArgumentException">Must use inputPath list overload</exception>
  443. private async Task ExtractTextSubtitle(
  444. string[] inputFiles,
  445. MediaProtocol protocol,
  446. int subtitleStreamIndex,
  447. string outputCodec,
  448. string outputPath,
  449. CancellationToken cancellationToken)
  450. {
  451. var semaphore = GetLock(outputPath);
  452. await semaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
  453. try
  454. {
  455. if (!File.Exists(outputPath))
  456. {
  457. await ExtractTextSubtitleInternal(
  458. _mediaEncoder.GetInputArgument(inputFiles, protocol),
  459. subtitleStreamIndex,
  460. outputCodec,
  461. outputPath,
  462. cancellationToken).ConfigureAwait(false);
  463. }
  464. }
  465. finally
  466. {
  467. semaphore.Release();
  468. }
  469. }
  470. private async Task ExtractTextSubtitleInternal(
  471. string inputPath,
  472. int subtitleStreamIndex,
  473. string outputCodec,
  474. string outputPath,
  475. CancellationToken cancellationToken)
  476. {
  477. if (string.IsNullOrEmpty(inputPath))
  478. {
  479. throw new ArgumentNullException(nameof(inputPath));
  480. }
  481. if (string.IsNullOrEmpty(outputPath))
  482. {
  483. throw new ArgumentNullException(nameof(outputPath));
  484. }
  485. Directory.CreateDirectory(Path.GetDirectoryName(outputPath));
  486. var processArgs = string.Format(
  487. CultureInfo.InvariantCulture,
  488. "-i {0} -map 0:{1} -an -vn -c:s {2} \"{3}\"",
  489. inputPath,
  490. subtitleStreamIndex,
  491. outputCodec,
  492. outputPath);
  493. var process = _processFactory.Create(new ProcessOptions
  494. {
  495. CreateNoWindow = true,
  496. UseShellExecute = false,
  497. EnableRaisingEvents = true,
  498. FileName = _mediaEncoder.EncoderPath,
  499. Arguments = processArgs,
  500. IsHidden = true,
  501. ErrorDialog = false
  502. });
  503. _logger.LogInformation("{File} {Arguments}", process.StartInfo.FileName, process.StartInfo.Arguments);
  504. try
  505. {
  506. process.Start();
  507. }
  508. catch (Exception ex)
  509. {
  510. _logger.LogError(ex, "Error starting ffmpeg");
  511. throw;
  512. }
  513. var ranToCompletion = await process.WaitForExitAsync(300000).ConfigureAwait(false);
  514. if (!ranToCompletion)
  515. {
  516. try
  517. {
  518. _logger.LogWarning("Killing ffmpeg subtitle extraction process");
  519. process.Kill();
  520. }
  521. catch (Exception ex)
  522. {
  523. _logger.LogError(ex, "Error killing subtitle extraction process");
  524. }
  525. }
  526. var exitCode = ranToCompletion ? process.ExitCode : -1;
  527. process.Dispose();
  528. var failed = false;
  529. if (exitCode == -1)
  530. {
  531. failed = true;
  532. try
  533. {
  534. _logger.LogWarning("Deleting extracted subtitle due to failure: {Path}", outputPath);
  535. _fileSystem.DeleteFile(outputPath);
  536. }
  537. catch (FileNotFoundException)
  538. {
  539. }
  540. catch (IOException ex)
  541. {
  542. _logger.LogError(ex, "Error deleting extracted subtitle {Path}", outputPath);
  543. }
  544. }
  545. else if (!File.Exists(outputPath))
  546. {
  547. failed = true;
  548. }
  549. if (failed)
  550. {
  551. var msg = $"ffmpeg subtitle extraction failed for {inputPath} to {outputPath}";
  552. _logger.LogError(msg);
  553. throw new Exception(msg);
  554. }
  555. else
  556. {
  557. var msg = $"ffmpeg subtitle extraction completed for {inputPath} to {outputPath}";
  558. _logger.LogInformation(msg);
  559. }
  560. if (string.Equals(outputCodec, "ass", StringComparison.OrdinalIgnoreCase))
  561. {
  562. await SetAssFont(outputPath).ConfigureAwait(false);
  563. }
  564. }
  565. /// <summary>
  566. /// Sets the ass font.
  567. /// </summary>
  568. /// <param name="file">The file.</param>
  569. /// <returns>Task.</returns>
  570. private async Task SetAssFont(string file)
  571. {
  572. _logger.LogInformation("Setting ass font within {File}", file);
  573. string text;
  574. Encoding encoding;
  575. using (var fileStream = File.OpenRead(file))
  576. using (var reader = new StreamReader(fileStream, true))
  577. {
  578. encoding = reader.CurrentEncoding;
  579. text = await reader.ReadToEndAsync().ConfigureAwait(false);
  580. }
  581. var newText = text.Replace(",Arial,", ",Arial Unicode MS,");
  582. if (!string.Equals(text, newText))
  583. {
  584. using (var fileStream = new FileStream(file, FileMode.Create, FileAccess.Write, FileShare.Read))
  585. using (var writer = new StreamWriter(fileStream, encoding))
  586. {
  587. writer.Write(newText);
  588. }
  589. }
  590. }
  591. private string GetSubtitleCachePath(string mediaPath, MediaProtocol protocol, int subtitleStreamIndex, string outputSubtitleExtension)
  592. {
  593. if (protocol == MediaProtocol.File)
  594. {
  595. var ticksParam = string.Empty;
  596. var date = _fileSystem.GetLastWriteTimeUtc(mediaPath);
  597. var filename = (mediaPath + "_" + subtitleStreamIndex.ToString(CultureInfo.InvariantCulture) + "_" + date.Ticks.ToString(CultureInfo.InvariantCulture) + ticksParam).GetMD5() + outputSubtitleExtension;
  598. var prefix = filename.Substring(0, 1);
  599. return Path.Combine(SubtitleCachePath, prefix, filename);
  600. }
  601. else
  602. {
  603. var filename = (mediaPath + "_" + subtitleStreamIndex.ToString(CultureInfo.InvariantCulture)).GetMD5() + outputSubtitleExtension;
  604. var prefix = filename.Substring(0, 1);
  605. return Path.Combine(SubtitleCachePath, prefix, filename);
  606. }
  607. }
  608. /// <inheritdoc />
  609. public async Task<string> GetSubtitleFileCharacterSet(string path, string language, MediaProtocol protocol, CancellationToken cancellationToken)
  610. {
  611. using (var stream = await GetStream(path, protocol, cancellationToken).ConfigureAwait(false))
  612. {
  613. var charset = CharsetDetector.DetectFromStream(stream).Detected?.EncodingName;
  614. _logger.LogDebug("charset {0} detected for {Path}", charset ?? "null", path);
  615. return charset;
  616. }
  617. }
  618. private Task<Stream> GetStream(string path, MediaProtocol protocol, CancellationToken cancellationToken)
  619. {
  620. switch (protocol)
  621. {
  622. case MediaProtocol.Http:
  623. var opts = new HttpRequestOptions()
  624. {
  625. Url = path,
  626. CancellationToken = cancellationToken,
  627. // Needed for seeking
  628. BufferContent = true
  629. };
  630. return _httpClient.Get(opts);
  631. case MediaProtocol.File:
  632. return Task.FromResult<Stream>(File.OpenRead(path));
  633. default:
  634. throw new ArgumentOutOfRangeException(nameof(protocol));
  635. }
  636. }
  637. }
  638. }