SubtitleEncoder.cs 34 KB

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