SubtitleEncoder.cs 29 KB

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