SubtitleEncoder.cs 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910
  1. #pragma warning disable CS1591
  2. using System;
  3. using System.Collections.Generic;
  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 AsyncKeyedLock;
  14. using MediaBrowser.Common;
  15. using MediaBrowser.Common.Extensions;
  16. using MediaBrowser.Common.Net;
  17. using MediaBrowser.Controller.Entities;
  18. using MediaBrowser.Controller.IO;
  19. using MediaBrowser.Controller.Library;
  20. using MediaBrowser.Controller.MediaEncoding;
  21. using MediaBrowser.Model.Dto;
  22. using MediaBrowser.Model.Entities;
  23. using MediaBrowser.Model.IO;
  24. using MediaBrowser.Model.MediaInfo;
  25. using Microsoft.Extensions.Logging;
  26. using UtfUnknown;
  27. namespace MediaBrowser.MediaEncoding.Subtitles
  28. {
  29. public sealed class SubtitleEncoder : ISubtitleEncoder, IDisposable
  30. {
  31. private readonly ILogger<SubtitleEncoder> _logger;
  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. private readonly IPathManager _pathManager;
  38. /// <summary>
  39. /// The _semaphoreLocks.
  40. /// </summary>
  41. private readonly AsyncKeyedLocker<string> _semaphoreLocks = new(o =>
  42. {
  43. o.PoolSize = 20;
  44. o.PoolInitialFill = 1;
  45. });
  46. public SubtitleEncoder(
  47. ILogger<SubtitleEncoder> logger,
  48. IFileSystem fileSystem,
  49. IMediaEncoder mediaEncoder,
  50. IHttpClientFactory httpClientFactory,
  51. IMediaSourceManager mediaSourceManager,
  52. ISubtitleParser subtitleParser,
  53. IPathManager pathManager)
  54. {
  55. _logger = logger;
  56. _fileSystem = fileSystem;
  57. _mediaEncoder = mediaEncoder;
  58. _httpClientFactory = httpClientFactory;
  59. _mediaSourceManager = mediaSourceManager;
  60. _subtitleParser = subtitleParser;
  61. _pathManager = pathManager;
  62. }
  63. private MemoryStream ConvertSubtitles(
  64. Stream stream,
  65. string inputFormat,
  66. string outputFormat,
  67. long startTimeTicks,
  68. long endTimeTicks,
  69. bool preserveOriginalTimestamps,
  70. CancellationToken cancellationToken)
  71. {
  72. var ms = new MemoryStream();
  73. try
  74. {
  75. var trackInfo = _subtitleParser.Parse(stream, inputFormat);
  76. FilterEvents(trackInfo, startTimeTicks, endTimeTicks, preserveOriginalTimestamps);
  77. var writer = GetWriter(outputFormat);
  78. writer.Write(trackInfo, ms, cancellationToken);
  79. ms.Position = 0;
  80. }
  81. catch
  82. {
  83. ms.Dispose();
  84. throw;
  85. }
  86. return ms;
  87. }
  88. private void FilterEvents(SubtitleTrackInfo track, long startPositionTicks, long endTimeTicks, bool preserveTimestamps)
  89. {
  90. // Drop subs that are earlier than what we're looking for
  91. track.TrackEvents = track.TrackEvents
  92. .SkipWhile(i => (i.StartPositionTicks - startPositionTicks) < 0 || (i.EndPositionTicks - startPositionTicks) < 0)
  93. .ToArray();
  94. if (endTimeTicks > 0)
  95. {
  96. track.TrackEvents = track.TrackEvents
  97. .TakeWhile(i => i.StartPositionTicks <= endTimeTicks)
  98. .ToArray();
  99. }
  100. if (!preserveTimestamps)
  101. {
  102. foreach (var trackEvent in track.TrackEvents)
  103. {
  104. trackEvent.EndPositionTicks -= startPositionTicks;
  105. trackEvent.StartPositionTicks -= startPositionTicks;
  106. }
  107. }
  108. }
  109. async Task<Stream> ISubtitleEncoder.GetSubtitles(BaseItem item, string mediaSourceId, int subtitleStreamIndex, string outputFormat, long startTimeTicks, long endTimeTicks, bool preserveOriginalTimestamps, CancellationToken cancellationToken)
  110. {
  111. ArgumentNullException.ThrowIfNull(item);
  112. if (string.IsNullOrWhiteSpace(mediaSourceId))
  113. {
  114. throw new ArgumentNullException(nameof(mediaSourceId));
  115. }
  116. var mediaSources = await _mediaSourceManager.GetPlaybackMediaSources(item, null, true, false, cancellationToken).ConfigureAwait(false);
  117. var mediaSource = mediaSources
  118. .First(i => string.Equals(i.Id, mediaSourceId, StringComparison.OrdinalIgnoreCase));
  119. var subtitleStream = mediaSource.MediaStreams
  120. .First(i => i.Type == MediaStreamType.Subtitle && i.Index == subtitleStreamIndex);
  121. var (stream, inputFormat) = await GetSubtitleStream(mediaSource, subtitleStream, cancellationToken)
  122. .ConfigureAwait(false);
  123. // Return the original if the same format is being requested
  124. // Character encoding was already handled in GetSubtitleStream
  125. if (string.Equals(inputFormat, outputFormat, StringComparison.OrdinalIgnoreCase))
  126. {
  127. return stream;
  128. }
  129. using (stream)
  130. {
  131. return ConvertSubtitles(stream, inputFormat, outputFormat, startTimeTicks, endTimeTicks, preserveOriginalTimestamps, cancellationToken);
  132. }
  133. }
  134. private async Task<(Stream Stream, string Format)> GetSubtitleStream(
  135. MediaSourceInfo mediaSource,
  136. MediaStream subtitleStream,
  137. CancellationToken cancellationToken)
  138. {
  139. var fileInfo = await GetReadableFile(mediaSource, subtitleStream, cancellationToken).ConfigureAwait(false);
  140. var stream = await GetSubtitleStream(fileInfo, cancellationToken).ConfigureAwait(false);
  141. return (stream, fileInfo.Format);
  142. }
  143. private async Task<Stream> GetSubtitleStream(SubtitleInfo fileInfo, CancellationToken cancellationToken)
  144. {
  145. if (fileInfo.IsExternal)
  146. {
  147. using (var stream = await GetStream(fileInfo.Path, fileInfo.Protocol, cancellationToken).ConfigureAwait(false))
  148. {
  149. var result = CharsetDetector.DetectFromStream(stream).Detected;
  150. stream.Position = 0;
  151. if (result is not null)
  152. {
  153. _logger.LogDebug("charset {CharSet} detected for {Path}", result.EncodingName, fileInfo.Path);
  154. using var reader = new StreamReader(stream, result.Encoding);
  155. var text = await reader.ReadToEndAsync(cancellationToken).ConfigureAwait(false);
  156. return new MemoryStream(Encoding.UTF8.GetBytes(text));
  157. }
  158. }
  159. }
  160. return AsyncFile.OpenRead(fileInfo.Path);
  161. }
  162. internal async Task<SubtitleInfo> GetReadableFile(
  163. MediaSourceInfo mediaSource,
  164. MediaStream subtitleStream,
  165. CancellationToken cancellationToken)
  166. {
  167. if (!subtitleStream.IsExternal || subtitleStream.Path.EndsWith(".mks", StringComparison.OrdinalIgnoreCase))
  168. {
  169. await ExtractAllExtractableSubtitles(mediaSource, cancellationToken).ConfigureAwait(false);
  170. var outputFileExtension = GetExtractableSubtitleFileExtension(subtitleStream);
  171. var outputFormat = GetExtractableSubtitleFormat(subtitleStream);
  172. var outputPath = GetSubtitleCachePath(mediaSource, subtitleStream.Index, "." + outputFileExtension);
  173. return new SubtitleInfo()
  174. {
  175. Path = outputPath,
  176. Protocol = MediaProtocol.File,
  177. Format = outputFormat,
  178. IsExternal = false
  179. };
  180. }
  181. var currentFormat = (Path.GetExtension(subtitleStream.Path) ?? subtitleStream.Codec)
  182. .TrimStart('.');
  183. // Handle PGS subtitles as raw streams for the client to render
  184. if (MediaStream.IsPgsFormat(currentFormat))
  185. {
  186. return new SubtitleInfo()
  187. {
  188. Path = subtitleStream.Path,
  189. Protocol = _mediaSourceManager.GetPathProtocol(subtitleStream.Path),
  190. Format = "pgssub",
  191. IsExternal = true
  192. };
  193. }
  194. // Fallback to ffmpeg conversion
  195. if (!_subtitleParser.SupportsFileExtension(currentFormat))
  196. {
  197. // Convert
  198. var outputPath = GetSubtitleCachePath(mediaSource, subtitleStream.Index, ".srt");
  199. await ConvertTextSubtitleToSrt(subtitleStream, mediaSource, outputPath, cancellationToken).ConfigureAwait(false);
  200. return new SubtitleInfo()
  201. {
  202. Path = outputPath,
  203. Protocol = MediaProtocol.File,
  204. Format = "srt",
  205. IsExternal = true
  206. };
  207. }
  208. // It's possible that the subtitleStream and mediaSource don't share the same protocol (e.g. .STRM file with local subs)
  209. return new SubtitleInfo()
  210. {
  211. Path = subtitleStream.Path,
  212. Protocol = _mediaSourceManager.GetPathProtocol(subtitleStream.Path),
  213. Format = currentFormat,
  214. IsExternal = true
  215. };
  216. }
  217. private bool TryGetWriter(string format, [NotNullWhen(true)] out ISubtitleWriter? value)
  218. {
  219. ArgumentException.ThrowIfNullOrEmpty(format);
  220. if (string.Equals(format, SubtitleFormat.ASS, StringComparison.OrdinalIgnoreCase))
  221. {
  222. value = new AssWriter();
  223. return true;
  224. }
  225. if (string.Equals(format, "json", StringComparison.OrdinalIgnoreCase))
  226. {
  227. value = new JsonWriter();
  228. return true;
  229. }
  230. if (string.Equals(format, SubtitleFormat.SRT, StringComparison.OrdinalIgnoreCase) || string.Equals(format, SubtitleFormat.SUBRIP, StringComparison.OrdinalIgnoreCase))
  231. {
  232. value = new SrtWriter();
  233. return true;
  234. }
  235. if (string.Equals(format, SubtitleFormat.SSA, StringComparison.OrdinalIgnoreCase))
  236. {
  237. value = new SsaWriter();
  238. return true;
  239. }
  240. if (string.Equals(format, SubtitleFormat.VTT, StringComparison.OrdinalIgnoreCase) || string.Equals(format, SubtitleFormat.WEBVTT, StringComparison.OrdinalIgnoreCase))
  241. {
  242. value = new VttWriter();
  243. return true;
  244. }
  245. if (string.Equals(format, SubtitleFormat.TTML, StringComparison.OrdinalIgnoreCase))
  246. {
  247. value = new TtmlWriter();
  248. return true;
  249. }
  250. value = null;
  251. return false;
  252. }
  253. private ISubtitleWriter GetWriter(string format)
  254. {
  255. if (TryGetWriter(format, out var writer))
  256. {
  257. return writer;
  258. }
  259. throw new ArgumentException("Unsupported format: " + format);
  260. }
  261. /// <summary>
  262. /// Converts the text subtitle to SRT.
  263. /// </summary>
  264. /// <param name="subtitleStream">The subtitle stream.</param>
  265. /// <param name="mediaSource">The input mediaSource.</param>
  266. /// <param name="outputPath">The output path.</param>
  267. /// <param name="cancellationToken">The cancellation token.</param>
  268. /// <returns>Task.</returns>
  269. private async Task ConvertTextSubtitleToSrt(MediaStream subtitleStream, MediaSourceInfo mediaSource, string outputPath, CancellationToken cancellationToken)
  270. {
  271. using (await _semaphoreLocks.LockAsync(outputPath, cancellationToken).ConfigureAwait(false))
  272. {
  273. if (!File.Exists(outputPath))
  274. {
  275. await ConvertTextSubtitleToSrtInternal(subtitleStream, mediaSource, outputPath, cancellationToken).ConfigureAwait(false);
  276. }
  277. }
  278. }
  279. /// <summary>
  280. /// Converts the text subtitle to SRT internal.
  281. /// </summary>
  282. /// <param name="subtitleStream">The subtitle stream.</param>
  283. /// <param name="mediaSource">The input mediaSource.</param>
  284. /// <param name="outputPath">The output path.</param>
  285. /// <param name="cancellationToken">The cancellation token.</param>
  286. /// <returns>Task.</returns>
  287. /// <exception cref="ArgumentNullException">
  288. /// The <c>inputPath</c> or <c>outputPath</c> is <c>null</c>.
  289. /// </exception>
  290. private async Task ConvertTextSubtitleToSrtInternal(MediaStream subtitleStream, MediaSourceInfo mediaSource, string outputPath, CancellationToken cancellationToken)
  291. {
  292. var inputPath = subtitleStream.Path;
  293. ArgumentException.ThrowIfNullOrEmpty(inputPath);
  294. ArgumentException.ThrowIfNullOrEmpty(outputPath);
  295. Directory.CreateDirectory(Path.GetDirectoryName(outputPath) ?? throw new ArgumentException($"Provided path ({outputPath}) is not valid.", nameof(outputPath)));
  296. var encodingParam = await GetSubtitleFileCharacterSet(subtitleStream, subtitleStream.Language, mediaSource, cancellationToken).ConfigureAwait(false);
  297. // FFmpeg automatically convert character encoding when it is UTF-16
  298. // If we specify character encoding, it rejects with "do not specify a character encoding" and "Unable to recode subtitle event"
  299. if ((inputPath.EndsWith(".smi", StringComparison.Ordinal) || inputPath.EndsWith(".sami", StringComparison.Ordinal)) &&
  300. (encodingParam.Equals("UTF-16BE", StringComparison.OrdinalIgnoreCase) ||
  301. encodingParam.Equals("UTF-16LE", StringComparison.OrdinalIgnoreCase)))
  302. {
  303. encodingParam = string.Empty;
  304. }
  305. else if (!string.IsNullOrEmpty(encodingParam))
  306. {
  307. encodingParam = " -sub_charenc " + encodingParam;
  308. }
  309. int exitCode;
  310. using (var process = new Process
  311. {
  312. StartInfo = new ProcessStartInfo
  313. {
  314. CreateNoWindow = true,
  315. UseShellExecute = false,
  316. FileName = _mediaEncoder.EncoderPath,
  317. Arguments = string.Format(CultureInfo.InvariantCulture, "{0} -i \"{1}\" -c:s srt \"{2}\"", encodingParam, inputPath, outputPath),
  318. WindowStyle = ProcessWindowStyle.Hidden,
  319. ErrorDialog = false
  320. },
  321. EnableRaisingEvents = true
  322. })
  323. {
  324. _logger.LogInformation("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments);
  325. try
  326. {
  327. process.Start();
  328. }
  329. catch (Exception ex)
  330. {
  331. _logger.LogError(ex, "Error starting ffmpeg");
  332. throw;
  333. }
  334. try
  335. {
  336. await process.WaitForExitAsync(TimeSpan.FromMinutes(30)).ConfigureAwait(false);
  337. exitCode = process.ExitCode;
  338. }
  339. catch (OperationCanceledException)
  340. {
  341. process.Kill(true);
  342. exitCode = -1;
  343. }
  344. }
  345. var failed = false;
  346. if (exitCode == -1)
  347. {
  348. failed = true;
  349. if (File.Exists(outputPath))
  350. {
  351. try
  352. {
  353. _logger.LogInformation("Deleting converted subtitle due to failure: {Path}", outputPath);
  354. _fileSystem.DeleteFile(outputPath);
  355. }
  356. catch (IOException ex)
  357. {
  358. _logger.LogError(ex, "Error deleting converted subtitle {Path}", outputPath);
  359. }
  360. }
  361. }
  362. else if (!File.Exists(outputPath))
  363. {
  364. failed = true;
  365. }
  366. if (failed)
  367. {
  368. _logger.LogError("ffmpeg subtitle conversion failed for {Path}", inputPath);
  369. throw new FfmpegException(
  370. string.Format(CultureInfo.InvariantCulture, "ffmpeg subtitle conversion failed for {0}", inputPath));
  371. }
  372. await SetAssFont(outputPath, cancellationToken).ConfigureAwait(false);
  373. _logger.LogInformation("ffmpeg subtitle conversion succeeded for {Path}", inputPath);
  374. }
  375. private string GetExtractableSubtitleFormat(MediaStream subtitleStream)
  376. {
  377. if (string.Equals(subtitleStream.Codec, "ass", StringComparison.OrdinalIgnoreCase)
  378. || string.Equals(subtitleStream.Codec, "ssa", StringComparison.OrdinalIgnoreCase)
  379. || string.Equals(subtitleStream.Codec, "pgssub", StringComparison.OrdinalIgnoreCase))
  380. {
  381. return subtitleStream.Codec;
  382. }
  383. else
  384. {
  385. return "srt";
  386. }
  387. }
  388. private string GetExtractableSubtitleFileExtension(MediaStream subtitleStream)
  389. {
  390. // Using .pgssub as file extension is not allowed by ffmpeg. The file extension for pgs subtitles is .sup.
  391. if (string.Equals(subtitleStream.Codec, "pgssub", StringComparison.OrdinalIgnoreCase))
  392. {
  393. return "sup";
  394. }
  395. else
  396. {
  397. return GetExtractableSubtitleFormat(subtitleStream);
  398. }
  399. }
  400. private bool IsCodecCopyable(string codec)
  401. {
  402. return string.Equals(codec, "ass", StringComparison.OrdinalIgnoreCase)
  403. || string.Equals(codec, "ssa", StringComparison.OrdinalIgnoreCase)
  404. || string.Equals(codec, "srt", StringComparison.OrdinalIgnoreCase)
  405. || string.Equals(codec, "subrip", StringComparison.OrdinalIgnoreCase)
  406. || string.Equals(codec, "pgssub", StringComparison.OrdinalIgnoreCase);
  407. }
  408. /// <summary>
  409. /// Extracts all extractable subtitles (text and pgs).
  410. /// </summary>
  411. /// <param name="mediaSource">The mediaSource.</param>
  412. /// <param name="cancellationToken">The cancellation token.</param>
  413. /// <returns>Task.</returns>
  414. private async Task ExtractAllExtractableSubtitles(MediaSourceInfo mediaSource, CancellationToken cancellationToken)
  415. {
  416. var locks = new List<IDisposable>();
  417. var extractableStreams = new List<MediaStream>();
  418. try
  419. {
  420. var subtitleStreams = mediaSource.MediaStreams
  421. .Where(stream => stream is { IsExtractableSubtitleStream: true, SupportsExternalStream: true, IsExternal: false });
  422. foreach (var subtitleStream in subtitleStreams)
  423. {
  424. var outputPath = GetSubtitleCachePath(mediaSource, subtitleStream.Index, "." + GetExtractableSubtitleFileExtension(subtitleStream));
  425. var releaser = await _semaphoreLocks.LockAsync(outputPath, cancellationToken).ConfigureAwait(false);
  426. if (File.Exists(outputPath))
  427. {
  428. releaser.Dispose();
  429. continue;
  430. }
  431. locks.Add(releaser);
  432. extractableStreams.Add(subtitleStream);
  433. }
  434. if (extractableStreams.Count > 0)
  435. {
  436. await ExtractAllExtractableSubtitlesInternal(mediaSource, extractableStreams, cancellationToken).ConfigureAwait(false);
  437. }
  438. }
  439. catch (Exception ex)
  440. {
  441. _logger.LogWarning(ex, "Unable to get streams for File:{File}", mediaSource.Path);
  442. }
  443. finally
  444. {
  445. locks.ForEach(x => x.Dispose());
  446. }
  447. }
  448. private async Task ExtractAllExtractableSubtitlesInternal(
  449. MediaSourceInfo mediaSource,
  450. List<MediaStream> subtitleStreams,
  451. CancellationToken cancellationToken)
  452. {
  453. var inputPath = _mediaEncoder.GetInputArgument(mediaSource.Path, mediaSource);
  454. var outputPaths = new List<string>();
  455. var args = string.Format(
  456. CultureInfo.InvariantCulture,
  457. "-i {0} -copyts",
  458. inputPath);
  459. foreach (var subtitleStream in subtitleStreams)
  460. {
  461. var outputPath = GetSubtitleCachePath(mediaSource, subtitleStream.Index, "." + GetExtractableSubtitleFileExtension(subtitleStream));
  462. var outputCodec = IsCodecCopyable(subtitleStream.Codec) ? "copy" : "srt";
  463. var streamIndex = EncodingHelper.FindIndex(mediaSource.MediaStreams, subtitleStream);
  464. if (streamIndex == -1)
  465. {
  466. _logger.LogError("Cannot find subtitle stream index for {InputPath} ({Index}), skipping this stream", inputPath, subtitleStream.Index);
  467. continue;
  468. }
  469. Directory.CreateDirectory(Path.GetDirectoryName(outputPath) ?? throw new FileNotFoundException($"Calculated path ({outputPath}) is not valid."));
  470. outputPaths.Add(outputPath);
  471. args += string.Format(
  472. CultureInfo.InvariantCulture,
  473. " -map 0:{0} -an -vn -c:s {1} \"{2}\"",
  474. streamIndex,
  475. outputCodec,
  476. outputPath);
  477. }
  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 = args,
  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. try
  504. {
  505. await process.WaitForExitAsync(TimeSpan.FromMinutes(30)).ConfigureAwait(false);
  506. exitCode = process.ExitCode;
  507. }
  508. catch (OperationCanceledException)
  509. {
  510. process.Kill(true);
  511. exitCode = -1;
  512. }
  513. }
  514. var failed = false;
  515. if (exitCode == -1)
  516. {
  517. failed = true;
  518. foreach (var outputPath in outputPaths)
  519. {
  520. try
  521. {
  522. _logger.LogWarning("Deleting extracted subtitle due to failure: {Path}", outputPath);
  523. _fileSystem.DeleteFile(outputPath);
  524. }
  525. catch (FileNotFoundException)
  526. {
  527. }
  528. catch (IOException ex)
  529. {
  530. _logger.LogError(ex, "Error deleting extracted subtitle {Path}", outputPath);
  531. }
  532. }
  533. }
  534. else
  535. {
  536. foreach (var outputPath in outputPaths)
  537. {
  538. if (!File.Exists(outputPath))
  539. {
  540. _logger.LogError("ffmpeg subtitle extraction failed for {InputPath} to {OutputPath}", inputPath, outputPath);
  541. failed = true;
  542. continue;
  543. }
  544. if (outputPath.EndsWith("ass", StringComparison.OrdinalIgnoreCase))
  545. {
  546. await SetAssFont(outputPath, cancellationToken).ConfigureAwait(false);
  547. }
  548. _logger.LogInformation("ffmpeg subtitle extraction completed for {InputPath} to {OutputPath}", inputPath, outputPath);
  549. }
  550. }
  551. if (failed)
  552. {
  553. throw new FfmpegException(
  554. string.Format(CultureInfo.InvariantCulture, "ffmpeg subtitle extraction failed for {0}", inputPath));
  555. }
  556. }
  557. /// <summary>
  558. /// Extracts the text subtitle.
  559. /// </summary>
  560. /// <param name="mediaSource">The mediaSource.</param>
  561. /// <param name="subtitleStream">The subtitle stream.</param>
  562. /// <param name="outputCodec">The output codec.</param>
  563. /// <param name="outputPath">The output path.</param>
  564. /// <param name="cancellationToken">The cancellation token.</param>
  565. /// <returns>Task.</returns>
  566. /// <exception cref="ArgumentException">Must use inputPath list overload.</exception>
  567. private async Task ExtractTextSubtitle(
  568. MediaSourceInfo mediaSource,
  569. MediaStream subtitleStream,
  570. string outputCodec,
  571. string outputPath,
  572. CancellationToken cancellationToken)
  573. {
  574. using (await _semaphoreLocks.LockAsync(outputPath, cancellationToken).ConfigureAwait(false))
  575. {
  576. if (!File.Exists(outputPath))
  577. {
  578. var subtitleStreamIndex = EncodingHelper.FindIndex(mediaSource.MediaStreams, subtitleStream);
  579. var args = _mediaEncoder.GetInputArgument(mediaSource.Path, mediaSource);
  580. if (subtitleStream.IsExternal)
  581. {
  582. args = _mediaEncoder.GetExternalSubtitleInputArgument(subtitleStream.Path);
  583. }
  584. await ExtractTextSubtitleInternal(
  585. args,
  586. subtitleStreamIndex,
  587. outputCodec,
  588. outputPath,
  589. cancellationToken).ConfigureAwait(false);
  590. }
  591. }
  592. }
  593. private async Task ExtractTextSubtitleInternal(
  594. string inputPath,
  595. int subtitleStreamIndex,
  596. string outputCodec,
  597. string outputPath,
  598. CancellationToken cancellationToken)
  599. {
  600. ArgumentException.ThrowIfNullOrEmpty(inputPath);
  601. ArgumentException.ThrowIfNullOrEmpty(outputPath);
  602. Directory.CreateDirectory(Path.GetDirectoryName(outputPath) ?? throw new ArgumentException($"Provided path ({outputPath}) is not valid.", nameof(outputPath)));
  603. var processArgs = string.Format(
  604. CultureInfo.InvariantCulture,
  605. "-i {0} -copyts -map 0:{1} -an -vn -c:s {2} \"{3}\"",
  606. inputPath,
  607. subtitleStreamIndex,
  608. outputCodec,
  609. outputPath);
  610. int exitCode;
  611. using (var process = new Process
  612. {
  613. StartInfo = new ProcessStartInfo
  614. {
  615. CreateNoWindow = true,
  616. UseShellExecute = false,
  617. FileName = _mediaEncoder.EncoderPath,
  618. Arguments = processArgs,
  619. WindowStyle = ProcessWindowStyle.Hidden,
  620. ErrorDialog = false
  621. },
  622. EnableRaisingEvents = true
  623. })
  624. {
  625. _logger.LogInformation("{File} {Arguments}", process.StartInfo.FileName, process.StartInfo.Arguments);
  626. try
  627. {
  628. process.Start();
  629. }
  630. catch (Exception ex)
  631. {
  632. _logger.LogError(ex, "Error starting ffmpeg");
  633. throw;
  634. }
  635. try
  636. {
  637. await process.WaitForExitAsync(TimeSpan.FromMinutes(30)).ConfigureAwait(false);
  638. exitCode = process.ExitCode;
  639. }
  640. catch (OperationCanceledException)
  641. {
  642. process.Kill(true);
  643. exitCode = -1;
  644. }
  645. }
  646. var failed = false;
  647. if (exitCode == -1)
  648. {
  649. failed = true;
  650. try
  651. {
  652. _logger.LogWarning("Deleting extracted subtitle due to failure: {Path}", outputPath);
  653. _fileSystem.DeleteFile(outputPath);
  654. }
  655. catch (FileNotFoundException)
  656. {
  657. }
  658. catch (IOException ex)
  659. {
  660. _logger.LogError(ex, "Error deleting extracted subtitle {Path}", outputPath);
  661. }
  662. }
  663. else if (!File.Exists(outputPath))
  664. {
  665. failed = true;
  666. }
  667. if (failed)
  668. {
  669. _logger.LogError("ffmpeg subtitle extraction failed for {InputPath} to {OutputPath}", inputPath, outputPath);
  670. throw new FfmpegException(
  671. string.Format(CultureInfo.InvariantCulture, "ffmpeg subtitle extraction failed for {0} to {1}", inputPath, outputPath));
  672. }
  673. _logger.LogInformation("ffmpeg subtitle extraction completed for {InputPath} to {OutputPath}", inputPath, outputPath);
  674. if (string.Equals(outputCodec, "ass", StringComparison.OrdinalIgnoreCase))
  675. {
  676. await SetAssFont(outputPath, cancellationToken).ConfigureAwait(false);
  677. }
  678. }
  679. /// <summary>
  680. /// Sets the ass font.
  681. /// </summary>
  682. /// <param name="file">The file.</param>
  683. /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <c>System.Threading.CancellationToken.None</c>.</param>
  684. /// <returns>Task.</returns>
  685. private async Task SetAssFont(string file, CancellationToken cancellationToken = default)
  686. {
  687. _logger.LogInformation("Setting ass font within {File}", file);
  688. string text;
  689. Encoding encoding;
  690. using (var fileStream = AsyncFile.OpenRead(file))
  691. using (var reader = new StreamReader(fileStream, true))
  692. {
  693. encoding = reader.CurrentEncoding;
  694. text = await reader.ReadToEndAsync(cancellationToken).ConfigureAwait(false);
  695. }
  696. var newText = text.Replace(",Arial,", ",Arial Unicode MS,", StringComparison.Ordinal);
  697. if (!string.Equals(text, newText, StringComparison.Ordinal))
  698. {
  699. var fileStream = new FileStream(file, FileMode.Create, FileAccess.Write, FileShare.None, IODefaults.FileStreamBufferSize, FileOptions.Asynchronous);
  700. await using (fileStream.ConfigureAwait(false))
  701. {
  702. var writer = new StreamWriter(fileStream, encoding);
  703. await using (writer.ConfigureAwait(false))
  704. {
  705. await writer.WriteAsync(newText.AsMemory(), cancellationToken).ConfigureAwait(false);
  706. }
  707. }
  708. }
  709. }
  710. private string GetSubtitleCachePath(MediaSourceInfo mediaSource, int subtitleStreamIndex, string outputSubtitleExtension)
  711. {
  712. return _pathManager.GetSubtitlePath(mediaSource.Id, subtitleStreamIndex, outputSubtitleExtension);
  713. }
  714. /// <inheritdoc />
  715. public async Task<string> GetSubtitleFileCharacterSet(MediaStream subtitleStream, string language, MediaSourceInfo mediaSource, CancellationToken cancellationToken)
  716. {
  717. var subtitleCodec = subtitleStream.Codec;
  718. var path = subtitleStream.Path;
  719. if (path.EndsWith(".mks", StringComparison.OrdinalIgnoreCase))
  720. {
  721. path = GetSubtitleCachePath(mediaSource, subtitleStream.Index, "." + subtitleCodec);
  722. await ExtractTextSubtitle(mediaSource, subtitleStream, subtitleCodec, path, cancellationToken)
  723. .ConfigureAwait(false);
  724. }
  725. using (var stream = await GetStream(path, mediaSource.Protocol, cancellationToken).ConfigureAwait(false))
  726. {
  727. var charset = CharsetDetector.DetectFromStream(stream).Detected?.EncodingName ?? string.Empty;
  728. // UTF16 is automatically converted to UTF8 by FFmpeg, do not specify a character encoding
  729. if ((path.EndsWith(".ass", StringComparison.Ordinal) || path.EndsWith(".ssa", StringComparison.Ordinal) || path.EndsWith(".srt", StringComparison.Ordinal))
  730. && (string.Equals(charset, "utf-16le", StringComparison.OrdinalIgnoreCase)
  731. || string.Equals(charset, "utf-16be", StringComparison.OrdinalIgnoreCase)))
  732. {
  733. charset = string.Empty;
  734. }
  735. _logger.LogDebug("charset {0} detected for {Path}", charset, path);
  736. return charset;
  737. }
  738. }
  739. private async Task<Stream> GetStream(string path, MediaProtocol protocol, CancellationToken cancellationToken)
  740. {
  741. switch (protocol)
  742. {
  743. case MediaProtocol.Http:
  744. {
  745. using var response = await _httpClientFactory.CreateClient(NamedClient.Default)
  746. .GetAsync(new Uri(path), cancellationToken)
  747. .ConfigureAwait(false);
  748. return await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
  749. }
  750. case MediaProtocol.File:
  751. return AsyncFile.OpenRead(path);
  752. default:
  753. throw new ArgumentOutOfRangeException(nameof(protocol));
  754. }
  755. }
  756. public async Task<string> GetSubtitleFilePath(MediaStream subtitleStream, MediaSourceInfo mediaSource, CancellationToken cancellationToken)
  757. {
  758. var info = await GetReadableFile(mediaSource, subtitleStream, cancellationToken)
  759. .ConfigureAwait(false);
  760. return info.Path;
  761. }
  762. /// <inheritdoc />
  763. public void Dispose()
  764. {
  765. _semaphoreLocks.Dispose();
  766. }
  767. #pragma warning disable CA1034 // Nested types should not be visible
  768. // Only public for the unit tests
  769. public readonly record struct SubtitleInfo
  770. {
  771. public string Path { get; init; }
  772. public MediaProtocol Protocol { get; init; }
  773. public string Format { get; init; }
  774. public bool IsExternal { get; init; }
  775. }
  776. }
  777. }