SubtitleEncoder.cs 28 KB

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