SubtitleEncoder.cs 30 KB

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