SubtitleEncoder.cs 29 KB

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