SubtitleEncoder.cs 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004
  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 = await CharsetDetector.DetectFromStreamAsync(stream, cancellationToken).ConfigureAwait(false);
  150. var detected = result.Detected;
  151. stream.Position = 0;
  152. if (detected is not null)
  153. {
  154. _logger.LogDebug("charset {CharSet} detected for {Path}", detected.EncodingName, fileInfo.Path);
  155. using var reader = new StreamReader(stream, detected.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 });
  423. foreach (var subtitleStream in subtitleStreams)
  424. {
  425. if (subtitleStream.IsExternal && !subtitleStream.Path.EndsWith(".mks", StringComparison.OrdinalIgnoreCase))
  426. {
  427. continue;
  428. }
  429. var outputPath = GetSubtitleCachePath(mediaSource, subtitleStream.Index, "." + GetExtractableSubtitleFileExtension(subtitleStream));
  430. var releaser = await _semaphoreLocks.LockAsync(outputPath, cancellationToken).ConfigureAwait(false);
  431. if (File.Exists(outputPath))
  432. {
  433. releaser.Dispose();
  434. continue;
  435. }
  436. locks.Add(releaser);
  437. extractableStreams.Add(subtitleStream);
  438. }
  439. if (extractableStreams.Count > 0)
  440. {
  441. await ExtractAllExtractableSubtitlesInternal(mediaSource, extractableStreams, cancellationToken).ConfigureAwait(false);
  442. await ExtractAllExtractableSubtitlesMKS(mediaSource, extractableStreams, cancellationToken).ConfigureAwait(false);
  443. }
  444. }
  445. catch (Exception ex)
  446. {
  447. _logger.LogWarning(ex, "Unable to get streams for File:{File}", mediaSource.Path);
  448. }
  449. finally
  450. {
  451. locks.ForEach(x => x.Dispose());
  452. }
  453. }
  454. private async Task ExtractAllExtractableSubtitlesMKS(
  455. MediaSourceInfo mediaSource,
  456. List<MediaStream> subtitleStreams,
  457. CancellationToken cancellationToken)
  458. {
  459. var mksFiles = new List<string>();
  460. foreach (var subtitleStream in subtitleStreams)
  461. {
  462. if (string.IsNullOrEmpty(subtitleStream.Path) || !subtitleStream.Path.EndsWith(".mks", StringComparison.OrdinalIgnoreCase))
  463. {
  464. continue;
  465. }
  466. if (!mksFiles.Contains(subtitleStream.Path))
  467. {
  468. mksFiles.Add(subtitleStream.Path);
  469. }
  470. }
  471. if (mksFiles.Count == 0)
  472. {
  473. return;
  474. }
  475. foreach (string mksFile in mksFiles)
  476. {
  477. var inputPath = _mediaEncoder.GetInputArgument(mksFile, mediaSource);
  478. var outputPaths = new List<string>();
  479. var args = string.Format(
  480. CultureInfo.InvariantCulture,
  481. "-i {0} -copyts",
  482. inputPath);
  483. foreach (var subtitleStream in subtitleStreams)
  484. {
  485. if (!subtitleStream.Path.Equals(mksFile, StringComparison.OrdinalIgnoreCase))
  486. {
  487. continue;
  488. }
  489. var outputPath = GetSubtitleCachePath(mediaSource, subtitleStream.Index, "." + GetExtractableSubtitleFileExtension(subtitleStream));
  490. var outputCodec = IsCodecCopyable(subtitleStream.Codec) ? "copy" : "srt";
  491. var streamIndex = EncodingHelper.FindIndex(mediaSource.MediaStreams, subtitleStream);
  492. if (streamIndex == -1)
  493. {
  494. _logger.LogError("Cannot find subtitle stream index for {InputPath} ({Index}), skipping this stream", inputPath, subtitleStream.Index);
  495. continue;
  496. }
  497. Directory.CreateDirectory(Path.GetDirectoryName(outputPath) ?? throw new FileNotFoundException($"Calculated path ({outputPath}) is not valid."));
  498. outputPaths.Add(outputPath);
  499. args += string.Format(
  500. CultureInfo.InvariantCulture,
  501. " -map 0:{0} -an -vn -c:s {1} \"{2}\"",
  502. streamIndex,
  503. outputCodec,
  504. outputPath);
  505. }
  506. await ExtractSubtitlesForFile(inputPath, args, outputPaths, cancellationToken).ConfigureAwait(false);
  507. }
  508. }
  509. private async Task ExtractAllExtractableSubtitlesInternal(
  510. MediaSourceInfo mediaSource,
  511. List<MediaStream> subtitleStreams,
  512. CancellationToken cancellationToken)
  513. {
  514. var inputPath = _mediaEncoder.GetInputArgument(mediaSource.Path, mediaSource);
  515. var outputPaths = new List<string>();
  516. var args = string.Format(
  517. CultureInfo.InvariantCulture,
  518. "-i {0} -copyts",
  519. inputPath);
  520. foreach (var subtitleStream in subtitleStreams)
  521. {
  522. if (!string.IsNullOrEmpty(subtitleStream.Path) && subtitleStream.Path.EndsWith(".mks", StringComparison.OrdinalIgnoreCase))
  523. {
  524. _logger.LogDebug("Subtitle {Index} for file {InputPath} is part in an MKS file. Skipping", inputPath, subtitleStream.Index);
  525. continue;
  526. }
  527. var outputPath = GetSubtitleCachePath(mediaSource, subtitleStream.Index, "." + GetExtractableSubtitleFileExtension(subtitleStream));
  528. var outputCodec = IsCodecCopyable(subtitleStream.Codec) ? "copy" : "srt";
  529. var streamIndex = EncodingHelper.FindIndex(mediaSource.MediaStreams, subtitleStream);
  530. if (streamIndex == -1)
  531. {
  532. _logger.LogError("Cannot find subtitle stream index for {InputPath} ({Index}), skipping this stream", inputPath, subtitleStream.Index);
  533. continue;
  534. }
  535. Directory.CreateDirectory(Path.GetDirectoryName(outputPath) ?? throw new FileNotFoundException($"Calculated path ({outputPath}) is not valid."));
  536. outputPaths.Add(outputPath);
  537. args += string.Format(
  538. CultureInfo.InvariantCulture,
  539. " -map 0:{0} -an -vn -c:s {1} \"{2}\"",
  540. streamIndex,
  541. outputCodec,
  542. outputPath);
  543. }
  544. if (outputPaths.Count == 0)
  545. {
  546. return;
  547. }
  548. await ExtractSubtitlesForFile(inputPath, args, outputPaths, cancellationToken).ConfigureAwait(false);
  549. }
  550. private async Task ExtractSubtitlesForFile(
  551. string inputPath,
  552. string args,
  553. List<string> outputPaths,
  554. CancellationToken cancellationToken)
  555. {
  556. int exitCode;
  557. using (var process = new Process
  558. {
  559. StartInfo = new ProcessStartInfo
  560. {
  561. CreateNoWindow = true,
  562. UseShellExecute = false,
  563. FileName = _mediaEncoder.EncoderPath,
  564. Arguments = args,
  565. WindowStyle = ProcessWindowStyle.Hidden,
  566. ErrorDialog = false
  567. },
  568. EnableRaisingEvents = true
  569. })
  570. {
  571. _logger.LogInformation("{File} {Arguments}", process.StartInfo.FileName, process.StartInfo.Arguments);
  572. try
  573. {
  574. process.Start();
  575. }
  576. catch (Exception ex)
  577. {
  578. _logger.LogError(ex, "Error starting ffmpeg");
  579. throw;
  580. }
  581. try
  582. {
  583. await process.WaitForExitAsync(TimeSpan.FromMinutes(30)).ConfigureAwait(false);
  584. exitCode = process.ExitCode;
  585. }
  586. catch (OperationCanceledException)
  587. {
  588. process.Kill(true);
  589. exitCode = -1;
  590. }
  591. }
  592. var failed = false;
  593. if (exitCode == -1)
  594. {
  595. failed = true;
  596. foreach (var outputPath in outputPaths)
  597. {
  598. try
  599. {
  600. _logger.LogWarning("Deleting extracted subtitle due to failure: {Path}", outputPath);
  601. _fileSystem.DeleteFile(outputPath);
  602. }
  603. catch (FileNotFoundException)
  604. {
  605. }
  606. catch (IOException ex)
  607. {
  608. _logger.LogError(ex, "Error deleting extracted subtitle {Path}", outputPath);
  609. }
  610. }
  611. }
  612. else
  613. {
  614. foreach (var outputPath in outputPaths)
  615. {
  616. if (!File.Exists(outputPath))
  617. {
  618. _logger.LogError("ffmpeg subtitle extraction failed for {InputPath} to {OutputPath}", inputPath, outputPath);
  619. failed = true;
  620. continue;
  621. }
  622. if (outputPath.EndsWith("ass", StringComparison.OrdinalIgnoreCase))
  623. {
  624. await SetAssFont(outputPath, cancellationToken).ConfigureAwait(false);
  625. }
  626. _logger.LogInformation("ffmpeg subtitle extraction completed for {InputPath} to {OutputPath}", inputPath, outputPath);
  627. }
  628. }
  629. if (failed)
  630. {
  631. throw new FfmpegException(
  632. string.Format(CultureInfo.InvariantCulture, "ffmpeg subtitle extraction failed for {0}", inputPath));
  633. }
  634. }
  635. /// <summary>
  636. /// Extracts the text subtitle.
  637. /// </summary>
  638. /// <param name="mediaSource">The mediaSource.</param>
  639. /// <param name="subtitleStream">The subtitle stream.</param>
  640. /// <param name="outputCodec">The output codec.</param>
  641. /// <param name="outputPath">The output path.</param>
  642. /// <param name="cancellationToken">The cancellation token.</param>
  643. /// <returns>Task.</returns>
  644. /// <exception cref="ArgumentException">Must use inputPath list overload.</exception>
  645. private async Task ExtractTextSubtitle(
  646. MediaSourceInfo mediaSource,
  647. MediaStream subtitleStream,
  648. string outputCodec,
  649. string outputPath,
  650. CancellationToken cancellationToken)
  651. {
  652. using (await _semaphoreLocks.LockAsync(outputPath, cancellationToken).ConfigureAwait(false))
  653. {
  654. if (!File.Exists(outputPath))
  655. {
  656. var subtitleStreamIndex = EncodingHelper.FindIndex(mediaSource.MediaStreams, subtitleStream);
  657. var args = _mediaEncoder.GetInputArgument(mediaSource.Path, mediaSource);
  658. if (subtitleStream.IsExternal)
  659. {
  660. args = _mediaEncoder.GetExternalSubtitleInputArgument(subtitleStream.Path);
  661. }
  662. await ExtractTextSubtitleInternal(
  663. args,
  664. subtitleStreamIndex,
  665. outputCodec,
  666. outputPath,
  667. cancellationToken).ConfigureAwait(false);
  668. }
  669. }
  670. }
  671. private async Task ExtractTextSubtitleInternal(
  672. string inputPath,
  673. int subtitleStreamIndex,
  674. string outputCodec,
  675. string outputPath,
  676. CancellationToken cancellationToken)
  677. {
  678. ArgumentException.ThrowIfNullOrEmpty(inputPath);
  679. ArgumentException.ThrowIfNullOrEmpty(outputPath);
  680. Directory.CreateDirectory(Path.GetDirectoryName(outputPath) ?? throw new ArgumentException($"Provided path ({outputPath}) is not valid.", nameof(outputPath)));
  681. var processArgs = string.Format(
  682. CultureInfo.InvariantCulture,
  683. "-i {0} -copyts -map 0:{1} -an -vn -c:s {2} \"{3}\"",
  684. inputPath,
  685. subtitleStreamIndex,
  686. outputCodec,
  687. outputPath);
  688. int exitCode;
  689. using (var process = new Process
  690. {
  691. StartInfo = new ProcessStartInfo
  692. {
  693. CreateNoWindow = true,
  694. UseShellExecute = false,
  695. FileName = _mediaEncoder.EncoderPath,
  696. Arguments = processArgs,
  697. WindowStyle = ProcessWindowStyle.Hidden,
  698. ErrorDialog = false
  699. },
  700. EnableRaisingEvents = true
  701. })
  702. {
  703. _logger.LogInformation("{File} {Arguments}", process.StartInfo.FileName, process.StartInfo.Arguments);
  704. try
  705. {
  706. process.Start();
  707. }
  708. catch (Exception ex)
  709. {
  710. _logger.LogError(ex, "Error starting ffmpeg");
  711. throw;
  712. }
  713. try
  714. {
  715. await process.WaitForExitAsync(TimeSpan.FromMinutes(30)).ConfigureAwait(false);
  716. exitCode = process.ExitCode;
  717. }
  718. catch (OperationCanceledException)
  719. {
  720. process.Kill(true);
  721. exitCode = -1;
  722. }
  723. }
  724. var failed = false;
  725. if (exitCode == -1)
  726. {
  727. failed = true;
  728. try
  729. {
  730. _logger.LogWarning("Deleting extracted subtitle due to failure: {Path}", outputPath);
  731. _fileSystem.DeleteFile(outputPath);
  732. }
  733. catch (FileNotFoundException)
  734. {
  735. }
  736. catch (IOException ex)
  737. {
  738. _logger.LogError(ex, "Error deleting extracted subtitle {Path}", outputPath);
  739. }
  740. }
  741. else if (!File.Exists(outputPath))
  742. {
  743. failed = true;
  744. }
  745. if (failed)
  746. {
  747. _logger.LogError("ffmpeg subtitle extraction failed for {InputPath} to {OutputPath}", inputPath, outputPath);
  748. throw new FfmpegException(
  749. string.Format(CultureInfo.InvariantCulture, "ffmpeg subtitle extraction failed for {0} to {1}", inputPath, outputPath));
  750. }
  751. _logger.LogInformation("ffmpeg subtitle extraction completed for {InputPath} to {OutputPath}", inputPath, outputPath);
  752. if (string.Equals(outputCodec, "ass", StringComparison.OrdinalIgnoreCase))
  753. {
  754. await SetAssFont(outputPath, cancellationToken).ConfigureAwait(false);
  755. }
  756. }
  757. /// <summary>
  758. /// Sets the ass font.
  759. /// </summary>
  760. /// <param name="file">The file.</param>
  761. /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <c>System.Threading.CancellationToken.None</c>.</param>
  762. /// <returns>Task.</returns>
  763. private async Task SetAssFont(string file, CancellationToken cancellationToken = default)
  764. {
  765. _logger.LogInformation("Setting ass font within {File}", file);
  766. string text;
  767. Encoding encoding;
  768. using (var fileStream = AsyncFile.OpenRead(file))
  769. using (var reader = new StreamReader(fileStream, true))
  770. {
  771. encoding = reader.CurrentEncoding;
  772. text = await reader.ReadToEndAsync(cancellationToken).ConfigureAwait(false);
  773. }
  774. var newText = text.Replace(",Arial,", ",Arial Unicode MS,", StringComparison.Ordinal);
  775. if (!string.Equals(text, newText, StringComparison.Ordinal))
  776. {
  777. var fileStream = new FileStream(file, FileMode.Create, FileAccess.Write, FileShare.None, IODefaults.FileStreamBufferSize, FileOptions.Asynchronous);
  778. await using (fileStream.ConfigureAwait(false))
  779. {
  780. var writer = new StreamWriter(fileStream, encoding);
  781. await using (writer.ConfigureAwait(false))
  782. {
  783. await writer.WriteAsync(newText.AsMemory(), cancellationToken).ConfigureAwait(false);
  784. }
  785. }
  786. }
  787. }
  788. private string GetSubtitleCachePath(MediaSourceInfo mediaSource, int subtitleStreamIndex, string outputSubtitleExtension)
  789. {
  790. return _pathManager.GetSubtitlePath(mediaSource.Id, subtitleStreamIndex, outputSubtitleExtension);
  791. }
  792. /// <inheritdoc />
  793. public async Task<string> GetSubtitleFileCharacterSet(MediaStream subtitleStream, string language, MediaSourceInfo mediaSource, CancellationToken cancellationToken)
  794. {
  795. var subtitleCodec = subtitleStream.Codec;
  796. var path = subtitleStream.Path;
  797. if (path.EndsWith(".mks", StringComparison.OrdinalIgnoreCase))
  798. {
  799. path = GetSubtitleCachePath(mediaSource, subtitleStream.Index, "." + subtitleCodec);
  800. await ExtractTextSubtitle(mediaSource, subtitleStream, subtitleCodec, path, cancellationToken)
  801. .ConfigureAwait(false);
  802. }
  803. using (var stream = await GetStream(path, mediaSource.Protocol, cancellationToken).ConfigureAwait(false))
  804. {
  805. var result = await CharsetDetector.DetectFromStreamAsync(stream, cancellationToken).ConfigureAwait(false);
  806. var charset = result.Detected?.EncodingName ?? string.Empty;
  807. // UTF16 is automatically converted to UTF8 by FFmpeg, do not specify a character encoding
  808. if ((path.EndsWith(".ass", StringComparison.Ordinal) || path.EndsWith(".ssa", StringComparison.Ordinal) || path.EndsWith(".srt", StringComparison.Ordinal))
  809. && (string.Equals(charset, "utf-16le", StringComparison.OrdinalIgnoreCase)
  810. || string.Equals(charset, "utf-16be", StringComparison.OrdinalIgnoreCase)))
  811. {
  812. charset = string.Empty;
  813. }
  814. _logger.LogDebug("charset {0} detected for {Path}", charset, path);
  815. return charset;
  816. }
  817. }
  818. private async Task<Stream> GetStream(string path, MediaProtocol protocol, CancellationToken cancellationToken)
  819. {
  820. switch (protocol)
  821. {
  822. case MediaProtocol.Http:
  823. {
  824. using var response = await _httpClientFactory.CreateClient(NamedClient.Default)
  825. .GetAsync(new Uri(path), cancellationToken)
  826. .ConfigureAwait(false);
  827. return await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
  828. }
  829. case MediaProtocol.File:
  830. return AsyncFile.OpenRead(path);
  831. default:
  832. throw new ArgumentOutOfRangeException(nameof(protocol));
  833. }
  834. }
  835. public async Task<string> GetSubtitleFilePath(MediaStream subtitleStream, MediaSourceInfo mediaSource, CancellationToken cancellationToken)
  836. {
  837. var info = await GetReadableFile(mediaSource, subtitleStream, cancellationToken)
  838. .ConfigureAwait(false);
  839. return info.Path;
  840. }
  841. /// <inheritdoc />
  842. public void Dispose()
  843. {
  844. _semaphoreLocks.Dispose();
  845. }
  846. #pragma warning disable CA1034 // Nested types should not be visible
  847. // Only public for the unit tests
  848. public readonly record struct SubtitleInfo
  849. {
  850. public string Path { get; init; }
  851. public MediaProtocol Protocol { get; init; }
  852. public string Format { get; init; }
  853. public bool IsExternal { get; init; }
  854. }
  855. }
  856. }