SubtitleEncoder.cs 29 KB

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