SubtitleEncoder.cs 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760
  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.GetPlayackMediaSources(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. if (requiresCharset)
  159. {
  160. using (var stream = await GetStream(path, protocol, cancellationToken).ConfigureAwait(false))
  161. {
  162. var result = CharsetDetector.DetectFromStream(stream).Detected;
  163. if (result != null)
  164. {
  165. _logger.LogDebug("charset {CharSet} detected for {Path}", result.EncodingName, path);
  166. using var reader = new StreamReader(stream, result.Encoding);
  167. var text = await reader.ReadToEndAsync().ConfigureAwait(false);
  168. return new MemoryStream(Encoding.UTF8.GetBytes(text));
  169. }
  170. }
  171. }
  172. return File.OpenRead(path);
  173. }
  174. private async Task<SubtitleInfo> GetReadableFile(
  175. string mediaPath,
  176. string[] inputFiles,
  177. MediaProtocol protocol,
  178. MediaStream subtitleStream,
  179. CancellationToken cancellationToken)
  180. {
  181. if (!subtitleStream.IsExternal)
  182. {
  183. string outputFormat;
  184. string outputCodec;
  185. if (string.Equals(subtitleStream.Codec, "ass", StringComparison.OrdinalIgnoreCase) ||
  186. string.Equals(subtitleStream.Codec, "ssa", StringComparison.OrdinalIgnoreCase) ||
  187. string.Equals(subtitleStream.Codec, "srt", StringComparison.OrdinalIgnoreCase))
  188. {
  189. // Extract
  190. outputCodec = "copy";
  191. outputFormat = subtitleStream.Codec;
  192. }
  193. else if (string.Equals(subtitleStream.Codec, "subrip", StringComparison.OrdinalIgnoreCase))
  194. {
  195. // Extract
  196. outputCodec = "copy";
  197. outputFormat = "srt";
  198. }
  199. else
  200. {
  201. // Extract
  202. outputCodec = "srt";
  203. outputFormat = "srt";
  204. }
  205. // Extract
  206. var outputPath = GetSubtitleCachePath(mediaPath, protocol, subtitleStream.Index, "." + outputFormat);
  207. await ExtractTextSubtitle(inputFiles, protocol, subtitleStream.Index, outputCodec, outputPath, cancellationToken)
  208. .ConfigureAwait(false);
  209. return new SubtitleInfo(outputPath, MediaProtocol.File, outputFormat, false);
  210. }
  211. var currentFormat = (Path.GetExtension(subtitleStream.Path) ?? subtitleStream.Codec)
  212. .TrimStart('.');
  213. if (GetReader(currentFormat, false) == null)
  214. {
  215. // Convert
  216. var outputPath = GetSubtitleCachePath(mediaPath, protocol, subtitleStream.Index, ".srt");
  217. await ConvertTextSubtitleToSrt(subtitleStream.Path, subtitleStream.Language, protocol, outputPath, cancellationToken).ConfigureAwait(false);
  218. return new SubtitleInfo(outputPath, MediaProtocol.File, "srt", true);
  219. }
  220. return new SubtitleInfo(subtitleStream.Path, protocol, currentFormat, true);
  221. }
  222. private struct SubtitleInfo
  223. {
  224. public SubtitleInfo(string path, MediaProtocol protocol, string format, bool isExternal)
  225. {
  226. Path = path;
  227. Protocol = protocol;
  228. Format = format;
  229. IsExternal = isExternal;
  230. }
  231. public string Path { get; set; }
  232. public MediaProtocol Protocol { get; set; }
  233. public string Format { get; set; }
  234. public bool IsExternal { get; set; }
  235. }
  236. private ISubtitleParser GetReader(string format, bool throwIfMissing)
  237. {
  238. if (string.IsNullOrEmpty(format))
  239. {
  240. throw new ArgumentNullException(nameof(format));
  241. }
  242. if (string.Equals(format, SubtitleFormat.SRT, StringComparison.OrdinalIgnoreCase))
  243. {
  244. return new SrtParser(_logger);
  245. }
  246. if (string.Equals(format, SubtitleFormat.SSA, StringComparison.OrdinalIgnoreCase))
  247. {
  248. return new SsaParser();
  249. }
  250. if (string.Equals(format, SubtitleFormat.ASS, StringComparison.OrdinalIgnoreCase))
  251. {
  252. return new AssParser();
  253. }
  254. if (throwIfMissing)
  255. {
  256. throw new ArgumentException("Unsupported format: " + format);
  257. }
  258. return null;
  259. }
  260. private ISubtitleWriter TryGetWriter(string format)
  261. {
  262. if (string.IsNullOrEmpty(format))
  263. {
  264. throw new ArgumentNullException(nameof(format));
  265. }
  266. if (string.Equals(format, "json", StringComparison.OrdinalIgnoreCase))
  267. {
  268. return new JsonWriter();
  269. }
  270. if (string.Equals(format, SubtitleFormat.SRT, StringComparison.OrdinalIgnoreCase))
  271. {
  272. return new SrtWriter();
  273. }
  274. if (string.Equals(format, SubtitleFormat.VTT, StringComparison.OrdinalIgnoreCase))
  275. {
  276. return new VttWriter();
  277. }
  278. if (string.Equals(format, SubtitleFormat.TTML, StringComparison.OrdinalIgnoreCase))
  279. {
  280. return new TtmlWriter();
  281. }
  282. return null;
  283. }
  284. private ISubtitleWriter GetWriter(string format)
  285. {
  286. var writer = TryGetWriter(format);
  287. if (writer != null)
  288. {
  289. return writer;
  290. }
  291. throw new ArgumentException("Unsupported format: " + format);
  292. }
  293. /// <summary>
  294. /// The _semaphoreLocks
  295. /// </summary>
  296. private readonly ConcurrentDictionary<string, SemaphoreSlim> _semaphoreLocks =
  297. new ConcurrentDictionary<string, SemaphoreSlim>();
  298. /// <summary>
  299. /// Gets the lock.
  300. /// </summary>
  301. /// <param name="filename">The filename.</param>
  302. /// <returns>System.Object.</returns>
  303. private SemaphoreSlim GetLock(string filename)
  304. {
  305. return _semaphoreLocks.GetOrAdd(filename, key => new SemaphoreSlim(1, 1));
  306. }
  307. /// <summary>
  308. /// Converts the text subtitle to SRT.
  309. /// </summary>
  310. /// <param name="inputPath">The input path.</param>
  311. /// <param name="inputProtocol">The input protocol.</param>
  312. /// <param name="outputPath">The output path.</param>
  313. /// <param name="cancellationToken">The cancellation token.</param>
  314. /// <returns>Task.</returns>
  315. private async Task ConvertTextSubtitleToSrt(string inputPath, string language, MediaProtocol inputProtocol, string outputPath, CancellationToken cancellationToken)
  316. {
  317. var semaphore = GetLock(outputPath);
  318. await semaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
  319. try
  320. {
  321. if (!File.Exists(outputPath))
  322. {
  323. await ConvertTextSubtitleToSrtInternal(inputPath, language, inputProtocol, outputPath, cancellationToken).ConfigureAwait(false);
  324. }
  325. }
  326. finally
  327. {
  328. semaphore.Release();
  329. }
  330. }
  331. /// <summary>
  332. /// Converts the text subtitle to SRT internal.
  333. /// </summary>
  334. /// <param name="inputPath">The input path.</param>
  335. /// <param name="inputProtocol">The input protocol.</param>
  336. /// <param name="outputPath">The output path.</param>
  337. /// <param name="cancellationToken">The cancellation token.</param>
  338. /// <returns>Task.</returns>
  339. /// <exception cref="ArgumentNullException">
  340. /// inputPath
  341. /// or
  342. /// outputPath
  343. /// </exception>
  344. private async Task ConvertTextSubtitleToSrtInternal(string inputPath, string language, MediaProtocol inputProtocol, string outputPath, CancellationToken cancellationToken)
  345. {
  346. if (string.IsNullOrEmpty(inputPath))
  347. {
  348. throw new ArgumentNullException(nameof(inputPath));
  349. }
  350. if (string.IsNullOrEmpty(outputPath))
  351. {
  352. throw new ArgumentNullException(nameof(outputPath));
  353. }
  354. Directory.CreateDirectory(Path.GetDirectoryName(outputPath));
  355. var encodingParam = await GetSubtitleFileCharacterSet(inputPath, language, inputProtocol, cancellationToken).ConfigureAwait(false);
  356. // FFmpeg automatically convert character encoding when it is UTF-16
  357. // If we specify character encoding, it rejects with "do not specify a character encoding" and "Unable to recode subtitle event"
  358. if ((inputPath.EndsWith(".smi") || inputPath.EndsWith(".sami")) && (encodingParam == "UTF-16BE" || encodingParam == "UTF-16LE"))
  359. {
  360. encodingParam = "";
  361. }
  362. else if (!string.IsNullOrEmpty(encodingParam))
  363. {
  364. encodingParam = " -sub_charenc " + encodingParam;
  365. }
  366. var process = _processFactory.Create(new ProcessOptions
  367. {
  368. CreateNoWindow = true,
  369. UseShellExecute = false,
  370. FileName = _mediaEncoder.EncoderPath,
  371. Arguments = string.Format("{0} -i \"{1}\" -c:s srt \"{2}\"", encodingParam, inputPath, outputPath),
  372. EnableRaisingEvents = true,
  373. IsHidden = true,
  374. ErrorDialog = false
  375. });
  376. _logger.LogInformation("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments);
  377. try
  378. {
  379. process.Start();
  380. }
  381. catch (Exception ex)
  382. {
  383. _logger.LogError(ex, "Error starting ffmpeg");
  384. throw;
  385. }
  386. var ranToCompletion = await process.WaitForExitAsync(300000).ConfigureAwait(false);
  387. if (!ranToCompletion)
  388. {
  389. try
  390. {
  391. _logger.LogInformation("Killing ffmpeg subtitle conversion process");
  392. process.Kill();
  393. }
  394. catch (Exception ex)
  395. {
  396. _logger.LogError(ex, "Error killing subtitle conversion process");
  397. }
  398. }
  399. var exitCode = ranToCompletion ? process.ExitCode : -1;
  400. process.Dispose();
  401. var failed = false;
  402. if (exitCode == -1)
  403. {
  404. failed = true;
  405. if (File.Exists(outputPath))
  406. {
  407. try
  408. {
  409. _logger.LogInformation("Deleting converted subtitle due to failure: ", outputPath);
  410. _fileSystem.DeleteFile(outputPath);
  411. }
  412. catch (IOException ex)
  413. {
  414. _logger.LogError(ex, "Error deleting converted subtitle {Path}", outputPath);
  415. }
  416. }
  417. }
  418. else if (!File.Exists(outputPath))
  419. {
  420. failed = true;
  421. }
  422. if (failed)
  423. {
  424. _logger.LogError("ffmpeg subtitle conversion failed for {Path}", inputPath);
  425. throw new Exception(
  426. string.Format(CultureInfo.InvariantCulture, "ffmpeg subtitle conversion failed for {0}", inputPath));
  427. }
  428. await SetAssFont(outputPath).ConfigureAwait(false);
  429. _logger.LogInformation("ffmpeg subtitle conversion succeeded for {Path}", inputPath);
  430. }
  431. /// <summary>
  432. /// Extracts the text subtitle.
  433. /// </summary>
  434. /// <param name="inputFiles">The input files.</param>
  435. /// <param name="protocol">The protocol.</param>
  436. /// <param name="subtitleStreamIndex">Index of the subtitle stream.</param>
  437. /// <param name="outputCodec">The output codec.</param>
  438. /// <param name="outputPath">The output path.</param>
  439. /// <param name="cancellationToken">The cancellation token.</param>
  440. /// <returns>Task.</returns>
  441. /// <exception cref="ArgumentException">Must use inputPath list overload</exception>
  442. private async Task ExtractTextSubtitle(
  443. string[] inputFiles,
  444. MediaProtocol protocol,
  445. int subtitleStreamIndex,
  446. string outputCodec,
  447. string outputPath,
  448. CancellationToken cancellationToken)
  449. {
  450. var semaphore = GetLock(outputPath);
  451. await semaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
  452. try
  453. {
  454. if (!File.Exists(outputPath))
  455. {
  456. await ExtractTextSubtitleInternal(
  457. _mediaEncoder.GetInputArgument(inputFiles, protocol),
  458. subtitleStreamIndex,
  459. outputCodec,
  460. outputPath,
  461. cancellationToken).ConfigureAwait(false);
  462. }
  463. }
  464. finally
  465. {
  466. semaphore.Release();
  467. }
  468. }
  469. private async Task ExtractTextSubtitleInternal(
  470. string inputPath,
  471. int subtitleStreamIndex,
  472. string outputCodec,
  473. string outputPath,
  474. CancellationToken cancellationToken)
  475. {
  476. if (string.IsNullOrEmpty(inputPath))
  477. {
  478. throw new ArgumentNullException(nameof(inputPath));
  479. }
  480. if (string.IsNullOrEmpty(outputPath))
  481. {
  482. throw new ArgumentNullException(nameof(outputPath));
  483. }
  484. Directory.CreateDirectory(Path.GetDirectoryName(outputPath));
  485. var processArgs = string.Format(
  486. CultureInfo.InvariantCulture,
  487. "-i {0} -map 0:{1} -an -vn -c:s {2} \"{3}\"",
  488. inputPath,
  489. subtitleStreamIndex,
  490. outputCodec,
  491. outputPath);
  492. var process = _processFactory.Create(new ProcessOptions
  493. {
  494. CreateNoWindow = true,
  495. UseShellExecute = false,
  496. EnableRaisingEvents = true,
  497. FileName = _mediaEncoder.EncoderPath,
  498. Arguments = processArgs,
  499. IsHidden = true,
  500. ErrorDialog = false
  501. });
  502. _logger.LogInformation("{File} {Arguments}", process.StartInfo.FileName, process.StartInfo.Arguments);
  503. try
  504. {
  505. process.Start();
  506. }
  507. catch (Exception ex)
  508. {
  509. _logger.LogError(ex, "Error starting ffmpeg");
  510. throw;
  511. }
  512. var ranToCompletion = await process.WaitForExitAsync(300000).ConfigureAwait(false);
  513. if (!ranToCompletion)
  514. {
  515. try
  516. {
  517. _logger.LogWarning("Killing ffmpeg subtitle extraction process");
  518. process.Kill();
  519. }
  520. catch (Exception ex)
  521. {
  522. _logger.LogError(ex, "Error killing subtitle extraction process");
  523. }
  524. }
  525. var exitCode = ranToCompletion ? process.ExitCode : -1;
  526. process.Dispose();
  527. var failed = false;
  528. if (exitCode == -1)
  529. {
  530. failed = true;
  531. try
  532. {
  533. _logger.LogWarning("Deleting extracted subtitle due to failure: {Path}", outputPath);
  534. _fileSystem.DeleteFile(outputPath);
  535. }
  536. catch (FileNotFoundException)
  537. {
  538. }
  539. catch (IOException ex)
  540. {
  541. _logger.LogError(ex, "Error deleting extracted subtitle {Path}", outputPath);
  542. }
  543. }
  544. else if (!File.Exists(outputPath))
  545. {
  546. failed = true;
  547. }
  548. if (failed)
  549. {
  550. var msg = $"ffmpeg subtitle extraction failed for {inputPath} to {outputPath}";
  551. _logger.LogError(msg);
  552. throw new Exception(msg);
  553. }
  554. else
  555. {
  556. var msg = $"ffmpeg subtitle extraction completed for {inputPath} to {outputPath}";
  557. _logger.LogInformation(msg);
  558. }
  559. if (string.Equals(outputCodec, "ass", StringComparison.OrdinalIgnoreCase))
  560. {
  561. await SetAssFont(outputPath).ConfigureAwait(false);
  562. }
  563. }
  564. /// <summary>
  565. /// Sets the ass font.
  566. /// </summary>
  567. /// <param name="file">The file.</param>
  568. /// <returns>Task.</returns>
  569. private async Task SetAssFont(string file)
  570. {
  571. _logger.LogInformation("Setting ass font within {File}", file);
  572. string text;
  573. Encoding encoding;
  574. using (var fileStream = File.OpenRead(file))
  575. using (var reader = new StreamReader(fileStream, true))
  576. {
  577. encoding = reader.CurrentEncoding;
  578. text = await reader.ReadToEndAsync().ConfigureAwait(false);
  579. }
  580. var newText = text.Replace(",Arial,", ",Arial Unicode MS,");
  581. if (!string.Equals(text, newText))
  582. {
  583. using (var fileStream = _fileSystem.GetFileStream(file, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read))
  584. using (var writer = new StreamWriter(fileStream, encoding))
  585. {
  586. writer.Write(newText);
  587. }
  588. }
  589. }
  590. private string GetSubtitleCachePath(string mediaPath, MediaProtocol protocol, int subtitleStreamIndex, string outputSubtitleExtension)
  591. {
  592. if (protocol == MediaProtocol.File)
  593. {
  594. var ticksParam = string.Empty;
  595. var date = _fileSystem.GetLastWriteTimeUtc(mediaPath);
  596. var filename = (mediaPath + "_" + subtitleStreamIndex.ToString(CultureInfo.InvariantCulture) + "_" + date.Ticks.ToString(CultureInfo.InvariantCulture) + ticksParam).GetMD5() + outputSubtitleExtension;
  597. var prefix = filename.Substring(0, 1);
  598. return Path.Combine(SubtitleCachePath, prefix, filename);
  599. }
  600. else
  601. {
  602. var filename = (mediaPath + "_" + subtitleStreamIndex.ToString(CultureInfo.InvariantCulture)).GetMD5() + outputSubtitleExtension;
  603. var prefix = filename.Substring(0, 1);
  604. return Path.Combine(SubtitleCachePath, prefix, filename);
  605. }
  606. }
  607. /// <inheritdoc />
  608. public async Task<string> GetSubtitleFileCharacterSet(string path, string language, MediaProtocol protocol, CancellationToken cancellationToken)
  609. {
  610. using (var stream = await GetStream(path, protocol, cancellationToken).ConfigureAwait(false))
  611. {
  612. var charset = CharsetDetector.DetectFromStream(stream).Detected?.EncodingName;
  613. _logger.LogDebug("charset {0} detected for {Path}", charset ?? "null", path);
  614. return charset;
  615. }
  616. }
  617. private Task<Stream> GetStream(string path, MediaProtocol protocol, CancellationToken cancellationToken)
  618. {
  619. switch (protocol)
  620. {
  621. case MediaProtocol.Http:
  622. var opts = new HttpRequestOptions()
  623. {
  624. Url = path,
  625. CancellationToken = cancellationToken,
  626. BufferContent = true
  627. };
  628. return _httpClient.Get(opts);
  629. case MediaProtocol.File:
  630. return Task.FromResult<Stream>(File.OpenRead(path));
  631. default:
  632. throw new ArgumentOutOfRangeException(nameof(protocol));
  633. }
  634. }
  635. }
  636. }