SubtitleEncoder.cs 28 KB

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