SubtitleEncoder.cs 29 KB

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