SubtitleEncoder.cs 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001
  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. var stream = await GetStream(fileInfo.Path, fileInfo.Protocol, cancellationToken).ConfigureAwait(false);
  148. await using (stream.ConfigureAwait(false))
  149. {
  150. var result = await CharsetDetector.DetectFromStreamAsync(stream, cancellationToken).ConfigureAwait(false);
  151. var detected = result.Detected;
  152. stream.Position = 0;
  153. if (detected is not null)
  154. {
  155. _logger.LogDebug("charset {CharSet} detected for {Path}", detected.EncodingName, fileInfo.Path);
  156. using var reader = new StreamReader(stream, detected.Encoding);
  157. var text = await reader.ReadToEndAsync(cancellationToken).ConfigureAwait(false);
  158. return new MemoryStream(Encoding.UTF8.GetBytes(text));
  159. }
  160. }
  161. }
  162. return AsyncFile.OpenRead(fileInfo.Path);
  163. }
  164. internal async Task<SubtitleInfo> GetReadableFile(
  165. MediaSourceInfo mediaSource,
  166. MediaStream subtitleStream,
  167. CancellationToken cancellationToken)
  168. {
  169. if (!subtitleStream.IsExternal || subtitleStream.Path.EndsWith(".mks", StringComparison.OrdinalIgnoreCase))
  170. {
  171. await ExtractAllExtractableSubtitles(mediaSource, cancellationToken).ConfigureAwait(false);
  172. var outputFileExtension = GetExtractableSubtitleFileExtension(subtitleStream);
  173. var outputFormat = GetExtractableSubtitleFormat(subtitleStream);
  174. var outputPath = GetSubtitleCachePath(mediaSource, subtitleStream.Index, "." + outputFileExtension);
  175. return new SubtitleInfo()
  176. {
  177. Path = outputPath,
  178. Protocol = MediaProtocol.File,
  179. Format = outputFormat,
  180. IsExternal = false
  181. };
  182. }
  183. var currentFormat = (Path.GetExtension(subtitleStream.Path) ?? subtitleStream.Codec)
  184. .TrimStart('.');
  185. // Handle PGS subtitles as raw streams for the client to render
  186. if (MediaStream.IsPgsFormat(currentFormat))
  187. {
  188. return new SubtitleInfo()
  189. {
  190. Path = subtitleStream.Path,
  191. Protocol = _mediaSourceManager.GetPathProtocol(subtitleStream.Path),
  192. Format = "pgssub",
  193. IsExternal = true
  194. };
  195. }
  196. // Fallback to ffmpeg conversion
  197. if (!_subtitleParser.SupportsFileExtension(currentFormat))
  198. {
  199. // Convert
  200. var outputPath = GetSubtitleCachePath(mediaSource, subtitleStream.Index, ".srt");
  201. await ConvertTextSubtitleToSrt(subtitleStream, mediaSource, outputPath, cancellationToken).ConfigureAwait(false);
  202. return new SubtitleInfo()
  203. {
  204. Path = outputPath,
  205. Protocol = MediaProtocol.File,
  206. Format = "srt",
  207. IsExternal = true
  208. };
  209. }
  210. // It's possible that the subtitleStream and mediaSource don't share the same protocol (e.g. .STRM file with local subs)
  211. return new SubtitleInfo()
  212. {
  213. Path = subtitleStream.Path,
  214. Protocol = _mediaSourceManager.GetPathProtocol(subtitleStream.Path),
  215. Format = currentFormat,
  216. IsExternal = true
  217. };
  218. }
  219. private bool TryGetWriter(string format, [NotNullWhen(true)] out ISubtitleWriter? value)
  220. {
  221. ArgumentException.ThrowIfNullOrEmpty(format);
  222. if (string.Equals(format, SubtitleFormat.ASS, StringComparison.OrdinalIgnoreCase))
  223. {
  224. value = new AssWriter();
  225. return true;
  226. }
  227. if (string.Equals(format, "json", StringComparison.OrdinalIgnoreCase))
  228. {
  229. value = new JsonWriter();
  230. return true;
  231. }
  232. if (string.Equals(format, SubtitleFormat.SRT, StringComparison.OrdinalIgnoreCase) || string.Equals(format, SubtitleFormat.SUBRIP, StringComparison.OrdinalIgnoreCase))
  233. {
  234. value = new SrtWriter();
  235. return true;
  236. }
  237. if (string.Equals(format, SubtitleFormat.SSA, StringComparison.OrdinalIgnoreCase))
  238. {
  239. value = new SsaWriter();
  240. return true;
  241. }
  242. if (string.Equals(format, SubtitleFormat.VTT, StringComparison.OrdinalIgnoreCase) || string.Equals(format, SubtitleFormat.WEBVTT, StringComparison.OrdinalIgnoreCase))
  243. {
  244. value = new VttWriter();
  245. return true;
  246. }
  247. if (string.Equals(format, SubtitleFormat.TTML, StringComparison.OrdinalIgnoreCase))
  248. {
  249. value = new TtmlWriter();
  250. return true;
  251. }
  252. value = null;
  253. return false;
  254. }
  255. private ISubtitleWriter GetWriter(string format)
  256. {
  257. if (TryGetWriter(format, out var writer))
  258. {
  259. return writer;
  260. }
  261. throw new ArgumentException("Unsupported format: " + format);
  262. }
  263. /// <summary>
  264. /// Converts the text subtitle to SRT.
  265. /// </summary>
  266. /// <param name="subtitleStream">The subtitle stream.</param>
  267. /// <param name="mediaSource">The input mediaSource.</param>
  268. /// <param name="outputPath">The output path.</param>
  269. /// <param name="cancellationToken">The cancellation token.</param>
  270. /// <returns>Task.</returns>
  271. private async Task ConvertTextSubtitleToSrt(MediaStream subtitleStream, MediaSourceInfo mediaSource, string outputPath, CancellationToken cancellationToken)
  272. {
  273. using (await _semaphoreLocks.LockAsync(outputPath, cancellationToken).ConfigureAwait(false))
  274. {
  275. if (!File.Exists(outputPath))
  276. {
  277. await ConvertTextSubtitleToSrtInternal(subtitleStream, mediaSource, outputPath, cancellationToken).ConfigureAwait(false);
  278. }
  279. }
  280. }
  281. /// <summary>
  282. /// Converts the text subtitle to SRT internal.
  283. /// </summary>
  284. /// <param name="subtitleStream">The subtitle stream.</param>
  285. /// <param name="mediaSource">The input mediaSource.</param>
  286. /// <param name="outputPath">The output path.</param>
  287. /// <param name="cancellationToken">The cancellation token.</param>
  288. /// <returns>Task.</returns>
  289. /// <exception cref="ArgumentNullException">
  290. /// The <c>inputPath</c> or <c>outputPath</c> is <c>null</c>.
  291. /// </exception>
  292. private async Task ConvertTextSubtitleToSrtInternal(MediaStream subtitleStream, MediaSourceInfo mediaSource, string outputPath, CancellationToken cancellationToken)
  293. {
  294. var inputPath = subtitleStream.Path;
  295. ArgumentException.ThrowIfNullOrEmpty(inputPath);
  296. ArgumentException.ThrowIfNullOrEmpty(outputPath);
  297. Directory.CreateDirectory(Path.GetDirectoryName(outputPath) ?? throw new ArgumentException($"Provided path ({outputPath}) is not valid.", nameof(outputPath)));
  298. var encodingParam = await GetSubtitleFileCharacterSet(subtitleStream, subtitleStream.Language, mediaSource, cancellationToken).ConfigureAwait(false);
  299. // FFmpeg automatically convert character encoding when it is UTF-16
  300. // If we specify character encoding, it rejects with "do not specify a character encoding" and "Unable to recode subtitle event"
  301. if ((inputPath.EndsWith(".smi", StringComparison.Ordinal) || inputPath.EndsWith(".sami", StringComparison.Ordinal)) &&
  302. (encodingParam.Equals("UTF-16BE", StringComparison.OrdinalIgnoreCase) ||
  303. encodingParam.Equals("UTF-16LE", StringComparison.OrdinalIgnoreCase)))
  304. {
  305. encodingParam = string.Empty;
  306. }
  307. else if (!string.IsNullOrEmpty(encodingParam))
  308. {
  309. encodingParam = " -sub_charenc " + encodingParam;
  310. }
  311. int exitCode;
  312. using (var process = new Process
  313. {
  314. StartInfo = new ProcessStartInfo
  315. {
  316. CreateNoWindow = true,
  317. UseShellExecute = false,
  318. FileName = _mediaEncoder.EncoderPath,
  319. Arguments = string.Format(CultureInfo.InvariantCulture, "{0} -i \"{1}\" -c:s srt \"{2}\"", encodingParam, inputPath, outputPath),
  320. WindowStyle = ProcessWindowStyle.Hidden,
  321. ErrorDialog = false
  322. },
  323. EnableRaisingEvents = true
  324. })
  325. {
  326. _logger.LogInformation("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments);
  327. try
  328. {
  329. process.Start();
  330. }
  331. catch (Exception ex)
  332. {
  333. _logger.LogError(ex, "Error starting ffmpeg");
  334. throw;
  335. }
  336. try
  337. {
  338. await process.WaitForExitAsync(TimeSpan.FromMinutes(30)).ConfigureAwait(false);
  339. exitCode = process.ExitCode;
  340. }
  341. catch (OperationCanceledException)
  342. {
  343. process.Kill(true);
  344. exitCode = -1;
  345. }
  346. }
  347. var failed = false;
  348. if (exitCode == -1)
  349. {
  350. failed = true;
  351. if (File.Exists(outputPath))
  352. {
  353. try
  354. {
  355. _logger.LogInformation("Deleting converted subtitle due to failure: {Path}", outputPath);
  356. _fileSystem.DeleteFile(outputPath);
  357. }
  358. catch (IOException ex)
  359. {
  360. _logger.LogError(ex, "Error deleting converted subtitle {Path}", outputPath);
  361. }
  362. }
  363. }
  364. else if (!File.Exists(outputPath))
  365. {
  366. failed = true;
  367. }
  368. if (failed)
  369. {
  370. _logger.LogError("ffmpeg subtitle conversion failed for {Path}", inputPath);
  371. throw new FfmpegException(
  372. string.Format(CultureInfo.InvariantCulture, "ffmpeg subtitle conversion failed for {0}", inputPath));
  373. }
  374. await SetAssFont(outputPath, cancellationToken).ConfigureAwait(false);
  375. _logger.LogInformation("ffmpeg subtitle conversion succeeded for {Path}", inputPath);
  376. }
  377. private string GetExtractableSubtitleFormat(MediaStream subtitleStream)
  378. {
  379. if (string.Equals(subtitleStream.Codec, "ass", StringComparison.OrdinalIgnoreCase)
  380. || string.Equals(subtitleStream.Codec, "ssa", StringComparison.OrdinalIgnoreCase)
  381. || string.Equals(subtitleStream.Codec, "pgssub", StringComparison.OrdinalIgnoreCase))
  382. {
  383. return subtitleStream.Codec;
  384. }
  385. else
  386. {
  387. return "srt";
  388. }
  389. }
  390. private string GetExtractableSubtitleFileExtension(MediaStream subtitleStream)
  391. {
  392. // Using .pgssub as file extension is not allowed by ffmpeg. The file extension for pgs subtitles is .sup.
  393. if (string.Equals(subtitleStream.Codec, "pgssub", StringComparison.OrdinalIgnoreCase))
  394. {
  395. return "sup";
  396. }
  397. else
  398. {
  399. return GetExtractableSubtitleFormat(subtitleStream);
  400. }
  401. }
  402. private bool IsCodecCopyable(string codec)
  403. {
  404. return string.Equals(codec, "ass", StringComparison.OrdinalIgnoreCase)
  405. || string.Equals(codec, "ssa", StringComparison.OrdinalIgnoreCase)
  406. || string.Equals(codec, "srt", StringComparison.OrdinalIgnoreCase)
  407. || string.Equals(codec, "subrip", StringComparison.OrdinalIgnoreCase)
  408. || string.Equals(codec, "pgssub", StringComparison.OrdinalIgnoreCase);
  409. }
  410. /// <inheritdoc />
  411. public async Task ExtractAllExtractableSubtitles(MediaSourceInfo mediaSource, CancellationToken cancellationToken)
  412. {
  413. var locks = new List<IDisposable>();
  414. var extractableStreams = new List<MediaStream>();
  415. try
  416. {
  417. var subtitleStreams = mediaSource.MediaStreams
  418. .Where(stream => stream is { IsExtractableSubtitleStream: true, SupportsExternalStream: true });
  419. foreach (var subtitleStream in subtitleStreams)
  420. {
  421. if (subtitleStream.IsExternal && !subtitleStream.Path.EndsWith(".mks", StringComparison.OrdinalIgnoreCase))
  422. {
  423. continue;
  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. await ExtractAllExtractableSubtitlesMKS(mediaSource, extractableStreams, cancellationToken).ConfigureAwait(false);
  439. }
  440. }
  441. catch (Exception ex)
  442. {
  443. _logger.LogWarning(ex, "Unable to get streams for File:{File}", mediaSource.Path);
  444. }
  445. finally
  446. {
  447. locks.ForEach(x => x.Dispose());
  448. }
  449. }
  450. private async Task ExtractAllExtractableSubtitlesMKS(
  451. MediaSourceInfo mediaSource,
  452. List<MediaStream> subtitleStreams,
  453. CancellationToken cancellationToken)
  454. {
  455. var mksFiles = new List<string>();
  456. foreach (var subtitleStream in subtitleStreams)
  457. {
  458. if (string.IsNullOrEmpty(subtitleStream.Path) || !subtitleStream.Path.EndsWith(".mks", StringComparison.OrdinalIgnoreCase))
  459. {
  460. continue;
  461. }
  462. if (!mksFiles.Contains(subtitleStream.Path))
  463. {
  464. mksFiles.Add(subtitleStream.Path);
  465. }
  466. }
  467. if (mksFiles.Count == 0)
  468. {
  469. return;
  470. }
  471. foreach (string mksFile in mksFiles)
  472. {
  473. var inputPath = _mediaEncoder.GetInputArgument(mksFile, mediaSource);
  474. var outputPaths = new List<string>();
  475. var args = string.Format(
  476. CultureInfo.InvariantCulture,
  477. "-i {0} -copyts",
  478. inputPath);
  479. foreach (var subtitleStream in subtitleStreams)
  480. {
  481. if (!subtitleStream.Path.Equals(mksFile, StringComparison.OrdinalIgnoreCase))
  482. {
  483. continue;
  484. }
  485. var outputPath = GetSubtitleCachePath(mediaSource, subtitleStream.Index, "." + GetExtractableSubtitleFileExtension(subtitleStream));
  486. var outputCodec = IsCodecCopyable(subtitleStream.Codec) ? "copy" : "srt";
  487. var streamIndex = EncodingHelper.FindIndex(mediaSource.MediaStreams, subtitleStream);
  488. if (streamIndex == -1)
  489. {
  490. _logger.LogError("Cannot find subtitle stream index for {InputPath} ({Index}), skipping this stream", inputPath, subtitleStream.Index);
  491. continue;
  492. }
  493. Directory.CreateDirectory(Path.GetDirectoryName(outputPath) ?? throw new FileNotFoundException($"Calculated path ({outputPath}) is not valid."));
  494. outputPaths.Add(outputPath);
  495. args += string.Format(
  496. CultureInfo.InvariantCulture,
  497. " -map 0:{0} -an -vn -c:s {1} \"{2}\"",
  498. streamIndex,
  499. outputCodec,
  500. outputPath);
  501. }
  502. await ExtractSubtitlesForFile(inputPath, args, outputPaths, cancellationToken).ConfigureAwait(false);
  503. }
  504. }
  505. private async Task ExtractAllExtractableSubtitlesInternal(
  506. MediaSourceInfo mediaSource,
  507. List<MediaStream> subtitleStreams,
  508. CancellationToken cancellationToken)
  509. {
  510. var inputPath = _mediaEncoder.GetInputArgument(mediaSource.Path, mediaSource);
  511. var outputPaths = new List<string>();
  512. var args = string.Format(
  513. CultureInfo.InvariantCulture,
  514. "-i {0} -copyts",
  515. inputPath);
  516. foreach (var subtitleStream in subtitleStreams)
  517. {
  518. if (!string.IsNullOrEmpty(subtitleStream.Path) && subtitleStream.Path.EndsWith(".mks", StringComparison.OrdinalIgnoreCase))
  519. {
  520. _logger.LogDebug("Subtitle {Index} for file {InputPath} is part in an MKS file. Skipping", inputPath, subtitleStream.Index);
  521. continue;
  522. }
  523. var outputPath = GetSubtitleCachePath(mediaSource, subtitleStream.Index, "." + GetExtractableSubtitleFileExtension(subtitleStream));
  524. var outputCodec = IsCodecCopyable(subtitleStream.Codec) ? "copy" : "srt";
  525. var streamIndex = EncodingHelper.FindIndex(mediaSource.MediaStreams, subtitleStream);
  526. if (streamIndex == -1)
  527. {
  528. _logger.LogError("Cannot find subtitle stream index for {InputPath} ({Index}), skipping this stream", inputPath, subtitleStream.Index);
  529. continue;
  530. }
  531. Directory.CreateDirectory(Path.GetDirectoryName(outputPath) ?? throw new FileNotFoundException($"Calculated path ({outputPath}) is not valid."));
  532. outputPaths.Add(outputPath);
  533. args += string.Format(
  534. CultureInfo.InvariantCulture,
  535. " -map 0:{0} -an -vn -c:s {1} \"{2}\"",
  536. streamIndex,
  537. outputCodec,
  538. outputPath);
  539. }
  540. if (outputPaths.Count == 0)
  541. {
  542. return;
  543. }
  544. await ExtractSubtitlesForFile(inputPath, args, outputPaths, cancellationToken).ConfigureAwait(false);
  545. }
  546. private async Task ExtractSubtitlesForFile(
  547. string inputPath,
  548. string args,
  549. List<string> outputPaths,
  550. CancellationToken cancellationToken)
  551. {
  552. int exitCode;
  553. using (var process = new Process
  554. {
  555. StartInfo = new ProcessStartInfo
  556. {
  557. CreateNoWindow = true,
  558. UseShellExecute = false,
  559. FileName = _mediaEncoder.EncoderPath,
  560. Arguments = args,
  561. WindowStyle = ProcessWindowStyle.Hidden,
  562. ErrorDialog = false
  563. },
  564. EnableRaisingEvents = true
  565. })
  566. {
  567. _logger.LogInformation("{File} {Arguments}", process.StartInfo.FileName, process.StartInfo.Arguments);
  568. try
  569. {
  570. process.Start();
  571. }
  572. catch (Exception ex)
  573. {
  574. _logger.LogError(ex, "Error starting ffmpeg");
  575. throw;
  576. }
  577. try
  578. {
  579. await process.WaitForExitAsync(TimeSpan.FromMinutes(30)).ConfigureAwait(false);
  580. exitCode = process.ExitCode;
  581. }
  582. catch (OperationCanceledException)
  583. {
  584. process.Kill(true);
  585. exitCode = -1;
  586. }
  587. }
  588. var failed = false;
  589. if (exitCode == -1)
  590. {
  591. failed = true;
  592. foreach (var outputPath in outputPaths)
  593. {
  594. try
  595. {
  596. _logger.LogWarning("Deleting extracted subtitle due to failure: {Path}", outputPath);
  597. _fileSystem.DeleteFile(outputPath);
  598. }
  599. catch (FileNotFoundException)
  600. {
  601. }
  602. catch (IOException ex)
  603. {
  604. _logger.LogError(ex, "Error deleting extracted subtitle {Path}", outputPath);
  605. }
  606. }
  607. }
  608. else
  609. {
  610. foreach (var outputPath in outputPaths)
  611. {
  612. if (!File.Exists(outputPath))
  613. {
  614. _logger.LogError("ffmpeg subtitle extraction failed for {InputPath} to {OutputPath}", inputPath, outputPath);
  615. failed = true;
  616. continue;
  617. }
  618. if (outputPath.EndsWith("ass", StringComparison.OrdinalIgnoreCase))
  619. {
  620. await SetAssFont(outputPath, cancellationToken).ConfigureAwait(false);
  621. }
  622. _logger.LogInformation("ffmpeg subtitle extraction completed for {InputPath} to {OutputPath}", inputPath, outputPath);
  623. }
  624. }
  625. if (failed)
  626. {
  627. throw new FfmpegException(
  628. string.Format(CultureInfo.InvariantCulture, "ffmpeg subtitle extraction failed for {0}", inputPath));
  629. }
  630. }
  631. /// <summary>
  632. /// Extracts the text subtitle.
  633. /// </summary>
  634. /// <param name="mediaSource">The mediaSource.</param>
  635. /// <param name="subtitleStream">The subtitle stream.</param>
  636. /// <param name="outputCodec">The output codec.</param>
  637. /// <param name="outputPath">The output path.</param>
  638. /// <param name="cancellationToken">The cancellation token.</param>
  639. /// <returns>Task.</returns>
  640. /// <exception cref="ArgumentException">Must use inputPath list overload.</exception>
  641. private async Task ExtractTextSubtitle(
  642. MediaSourceInfo mediaSource,
  643. MediaStream subtitleStream,
  644. string outputCodec,
  645. string outputPath,
  646. CancellationToken cancellationToken)
  647. {
  648. using (await _semaphoreLocks.LockAsync(outputPath, cancellationToken).ConfigureAwait(false))
  649. {
  650. if (!File.Exists(outputPath))
  651. {
  652. var subtitleStreamIndex = EncodingHelper.FindIndex(mediaSource.MediaStreams, subtitleStream);
  653. var args = _mediaEncoder.GetInputArgument(mediaSource.Path, mediaSource);
  654. if (subtitleStream.IsExternal)
  655. {
  656. args = _mediaEncoder.GetExternalSubtitleInputArgument(subtitleStream.Path);
  657. }
  658. await ExtractTextSubtitleInternal(
  659. args,
  660. subtitleStreamIndex,
  661. outputCodec,
  662. outputPath,
  663. cancellationToken).ConfigureAwait(false);
  664. }
  665. }
  666. }
  667. private async Task ExtractTextSubtitleInternal(
  668. string inputPath,
  669. int subtitleStreamIndex,
  670. string outputCodec,
  671. string outputPath,
  672. CancellationToken cancellationToken)
  673. {
  674. ArgumentException.ThrowIfNullOrEmpty(inputPath);
  675. ArgumentException.ThrowIfNullOrEmpty(outputPath);
  676. Directory.CreateDirectory(Path.GetDirectoryName(outputPath) ?? throw new ArgumentException($"Provided path ({outputPath}) is not valid.", nameof(outputPath)));
  677. var processArgs = string.Format(
  678. CultureInfo.InvariantCulture,
  679. "-i {0} -copyts -map 0:{1} -an -vn -c:s {2} \"{3}\"",
  680. inputPath,
  681. subtitleStreamIndex,
  682. outputCodec,
  683. outputPath);
  684. int exitCode;
  685. using (var process = new Process
  686. {
  687. StartInfo = new ProcessStartInfo
  688. {
  689. CreateNoWindow = true,
  690. UseShellExecute = false,
  691. FileName = _mediaEncoder.EncoderPath,
  692. Arguments = processArgs,
  693. WindowStyle = ProcessWindowStyle.Hidden,
  694. ErrorDialog = false
  695. },
  696. EnableRaisingEvents = true
  697. })
  698. {
  699. _logger.LogInformation("{File} {Arguments}", process.StartInfo.FileName, process.StartInfo.Arguments);
  700. try
  701. {
  702. process.Start();
  703. }
  704. catch (Exception ex)
  705. {
  706. _logger.LogError(ex, "Error starting ffmpeg");
  707. throw;
  708. }
  709. try
  710. {
  711. await process.WaitForExitAsync(TimeSpan.FromMinutes(30)).ConfigureAwait(false);
  712. exitCode = process.ExitCode;
  713. }
  714. catch (OperationCanceledException)
  715. {
  716. process.Kill(true);
  717. exitCode = -1;
  718. }
  719. }
  720. var failed = false;
  721. if (exitCode == -1)
  722. {
  723. failed = true;
  724. try
  725. {
  726. _logger.LogWarning("Deleting extracted subtitle due to failure: {Path}", outputPath);
  727. _fileSystem.DeleteFile(outputPath);
  728. }
  729. catch (FileNotFoundException)
  730. {
  731. }
  732. catch (IOException ex)
  733. {
  734. _logger.LogError(ex, "Error deleting extracted subtitle {Path}", outputPath);
  735. }
  736. }
  737. else if (!File.Exists(outputPath))
  738. {
  739. failed = true;
  740. }
  741. if (failed)
  742. {
  743. _logger.LogError("ffmpeg subtitle extraction failed for {InputPath} to {OutputPath}", inputPath, outputPath);
  744. throw new FfmpegException(
  745. string.Format(CultureInfo.InvariantCulture, "ffmpeg subtitle extraction failed for {0} to {1}", inputPath, outputPath));
  746. }
  747. _logger.LogInformation("ffmpeg subtitle extraction completed for {InputPath} to {OutputPath}", inputPath, outputPath);
  748. if (string.Equals(outputCodec, "ass", StringComparison.OrdinalIgnoreCase))
  749. {
  750. await SetAssFont(outputPath, cancellationToken).ConfigureAwait(false);
  751. }
  752. }
  753. /// <summary>
  754. /// Sets the ass font.
  755. /// </summary>
  756. /// <param name="file">The file.</param>
  757. /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <c>System.Threading.CancellationToken.None</c>.</param>
  758. /// <returns>Task.</returns>
  759. private async Task SetAssFont(string file, CancellationToken cancellationToken = default)
  760. {
  761. _logger.LogInformation("Setting ass font within {File}", file);
  762. string text;
  763. Encoding encoding;
  764. using (var fileStream = AsyncFile.OpenRead(file))
  765. using (var reader = new StreamReader(fileStream, true))
  766. {
  767. encoding = reader.CurrentEncoding;
  768. text = await reader.ReadToEndAsync(cancellationToken).ConfigureAwait(false);
  769. }
  770. var newText = text.Replace(",Arial,", ",Arial Unicode MS,", StringComparison.Ordinal);
  771. if (!string.Equals(text, newText, StringComparison.Ordinal))
  772. {
  773. var fileStream = new FileStream(file, FileMode.Create, FileAccess.Write, FileShare.None, IODefaults.FileStreamBufferSize, FileOptions.Asynchronous);
  774. await using (fileStream.ConfigureAwait(false))
  775. {
  776. var writer = new StreamWriter(fileStream, encoding);
  777. await using (writer.ConfigureAwait(false))
  778. {
  779. await writer.WriteAsync(newText.AsMemory(), cancellationToken).ConfigureAwait(false);
  780. }
  781. }
  782. }
  783. }
  784. private string GetSubtitleCachePath(MediaSourceInfo mediaSource, int subtitleStreamIndex, string outputSubtitleExtension)
  785. {
  786. return _pathManager.GetSubtitlePath(mediaSource.Id, subtitleStreamIndex, outputSubtitleExtension);
  787. }
  788. /// <inheritdoc />
  789. public async Task<string> GetSubtitleFileCharacterSet(MediaStream subtitleStream, string language, MediaSourceInfo mediaSource, CancellationToken cancellationToken)
  790. {
  791. var subtitleCodec = subtitleStream.Codec;
  792. var path = subtitleStream.Path;
  793. if (path.EndsWith(".mks", StringComparison.OrdinalIgnoreCase))
  794. {
  795. path = GetSubtitleCachePath(mediaSource, subtitleStream.Index, "." + subtitleCodec);
  796. await ExtractTextSubtitle(mediaSource, subtitleStream, subtitleCodec, path, cancellationToken)
  797. .ConfigureAwait(false);
  798. }
  799. var stream = await GetStream(path, mediaSource.Protocol, cancellationToken).ConfigureAwait(false);
  800. await using (stream.ConfigureAwait(false))
  801. {
  802. var result = await CharsetDetector.DetectFromStreamAsync(stream, cancellationToken).ConfigureAwait(false);
  803. var charset = result.Detected?.EncodingName ?? string.Empty;
  804. // UTF16 is automatically converted to UTF8 by FFmpeg, do not specify a character encoding
  805. if ((path.EndsWith(".ass", StringComparison.Ordinal) || path.EndsWith(".ssa", StringComparison.Ordinal) || path.EndsWith(".srt", StringComparison.Ordinal))
  806. && (string.Equals(charset, "utf-16le", StringComparison.OrdinalIgnoreCase)
  807. || string.Equals(charset, "utf-16be", StringComparison.OrdinalIgnoreCase)))
  808. {
  809. charset = string.Empty;
  810. }
  811. _logger.LogDebug("charset {0} detected for {Path}", charset, path);
  812. return charset;
  813. }
  814. }
  815. private async Task<Stream> GetStream(string path, MediaProtocol protocol, CancellationToken cancellationToken)
  816. {
  817. switch (protocol)
  818. {
  819. case MediaProtocol.Http:
  820. {
  821. using var response = await _httpClientFactory.CreateClient(NamedClient.Default)
  822. .GetAsync(new Uri(path), cancellationToken)
  823. .ConfigureAwait(false);
  824. return await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
  825. }
  826. case MediaProtocol.File:
  827. return AsyncFile.OpenRead(path);
  828. default:
  829. throw new ArgumentOutOfRangeException(nameof(protocol));
  830. }
  831. }
  832. public async Task<string> GetSubtitleFilePath(MediaStream subtitleStream, MediaSourceInfo mediaSource, CancellationToken cancellationToken)
  833. {
  834. var info = await GetReadableFile(mediaSource, subtitleStream, cancellationToken)
  835. .ConfigureAwait(false);
  836. return info.Path;
  837. }
  838. /// <inheritdoc />
  839. public void Dispose()
  840. {
  841. _semaphoreLocks.Dispose();
  842. }
  843. #pragma warning disable CA1034 // Nested types should not be visible
  844. // Only public for the unit tests
  845. public readonly record struct SubtitleInfo
  846. {
  847. public string Path { get; init; }
  848. public MediaProtocol Protocol { get; init; }
  849. public string Format { get; init; }
  850. public bool IsExternal { get; init; }
  851. }
  852. }
  853. }