SubtitleEncoder.cs 29 KB

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