SubtitleEncoder.cs 35 KB

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