SubtitleEncoder.cs 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900
  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<AsyncKeyedLockReleaser<string>>();
  392. var extractableStreams = new List<MediaStream>();
  393. try
  394. {
  395. var subtitleStreams = mediaSource.MediaStreams
  396. .Where(stream => stream.IsTextSubtitleStream && stream.SupportsExternalStream);
  397. foreach (var subtitleStream in subtitleStreams)
  398. {
  399. var outputPath = GetSubtitleCachePath(mediaSource, subtitleStream.Index, "." + GetTextSubtitleFormat(subtitleStream));
  400. var @lock = _semaphoreLocks.GetOrAdd(outputPath);
  401. await @lock.SemaphoreSlim.WaitAsync(cancellationToken).ConfigureAwait(false);
  402. if (File.Exists(outputPath))
  403. {
  404. @lock.Dispose();
  405. continue;
  406. }
  407. locks.Add(@lock);
  408. extractableStreams.Add(subtitleStream);
  409. }
  410. if (extractableStreams.Count > 0)
  411. {
  412. await ExtractAllTextSubtitlesInternal(mediaSource, extractableStreams, cancellationToken).ConfigureAwait(false);
  413. }
  414. }
  415. catch (Exception ex)
  416. {
  417. _logger.LogWarning(ex, "Unable to get streams for File:{File}", mediaSource.Path);
  418. }
  419. finally
  420. {
  421. foreach (var @lock in locks)
  422. {
  423. @lock.Dispose();
  424. }
  425. }
  426. }
  427. private async Task ExtractAllTextSubtitlesInternal(
  428. MediaSourceInfo mediaSource,
  429. List<MediaStream> subtitleStreams,
  430. CancellationToken cancellationToken)
  431. {
  432. var inputPath = mediaSource.Path;
  433. var outputPaths = new List<string>();
  434. var args = string.Format(
  435. CultureInfo.InvariantCulture,
  436. "-i {0} -copyts",
  437. inputPath);
  438. foreach (var subtitleStream in subtitleStreams)
  439. {
  440. var outputPath = GetSubtitleCachePath(mediaSource, subtitleStream.Index, "." + GetTextSubtitleFormat(subtitleStream));
  441. var outputCodec = IsCodecCopyable(subtitleStream.Codec) ? "copy" : "srt";
  442. var streamIndex = EncodingHelper.FindIndex(mediaSource.MediaStreams, subtitleStream);
  443. if (streamIndex == -1)
  444. {
  445. _logger.LogError("Cannot find subtitle stream index for {InputPath} ({Index}), skipping this stream", inputPath, subtitleStream.Index);
  446. continue;
  447. }
  448. Directory.CreateDirectory(Path.GetDirectoryName(outputPath) ?? throw new FileNotFoundException($"Calculated path ({outputPath}) is not valid."));
  449. outputPaths.Add(outputPath);
  450. args += string.Format(
  451. CultureInfo.InvariantCulture,
  452. " -map 0:{0} -an -vn -c:s {1} \"{2}\"",
  453. streamIndex,
  454. outputCodec,
  455. outputPath);
  456. }
  457. int exitCode;
  458. using (var process = new Process
  459. {
  460. StartInfo = new ProcessStartInfo
  461. {
  462. CreateNoWindow = true,
  463. UseShellExecute = false,
  464. FileName = _mediaEncoder.EncoderPath,
  465. Arguments = args,
  466. WindowStyle = ProcessWindowStyle.Hidden,
  467. ErrorDialog = false
  468. },
  469. EnableRaisingEvents = true
  470. })
  471. {
  472. _logger.LogInformation("{File} {Arguments}", process.StartInfo.FileName, process.StartInfo.Arguments);
  473. try
  474. {
  475. process.Start();
  476. }
  477. catch (Exception ex)
  478. {
  479. _logger.LogError(ex, "Error starting ffmpeg");
  480. throw;
  481. }
  482. try
  483. {
  484. await process.WaitForExitAsync(TimeSpan.FromMinutes(30)).ConfigureAwait(false);
  485. exitCode = process.ExitCode;
  486. }
  487. catch (OperationCanceledException)
  488. {
  489. process.Kill(true);
  490. exitCode = -1;
  491. }
  492. }
  493. var failed = false;
  494. if (exitCode == -1)
  495. {
  496. failed = true;
  497. foreach (var outputPath in outputPaths)
  498. {
  499. try
  500. {
  501. _logger.LogWarning("Deleting extracted subtitle due to failure: {Path}", outputPath);
  502. _fileSystem.DeleteFile(outputPath);
  503. }
  504. catch (FileNotFoundException)
  505. {
  506. }
  507. catch (IOException ex)
  508. {
  509. _logger.LogError(ex, "Error deleting extracted subtitle {Path}", outputPath);
  510. }
  511. }
  512. }
  513. else
  514. {
  515. foreach (var outputPath in outputPaths)
  516. {
  517. if (!File.Exists(outputPath))
  518. {
  519. _logger.LogError("ffmpeg subtitle extraction failed for {InputPath} to {OutputPath}", inputPath, outputPath);
  520. failed = true;
  521. continue;
  522. }
  523. if (outputPath.EndsWith("ass", StringComparison.OrdinalIgnoreCase))
  524. {
  525. await SetAssFont(outputPath, cancellationToken).ConfigureAwait(false);
  526. }
  527. _logger.LogInformation("ffmpeg subtitle extraction completed for {InputPath} to {OutputPath}", inputPath, outputPath);
  528. }
  529. }
  530. if (failed)
  531. {
  532. throw new FfmpegException(
  533. string.Format(CultureInfo.InvariantCulture, "ffmpeg subtitle extraction failed for {0}", inputPath));
  534. }
  535. }
  536. /// <summary>
  537. /// Extracts the text subtitle.
  538. /// </summary>
  539. /// <param name="mediaSource">The mediaSource.</param>
  540. /// <param name="subtitleStream">The subtitle stream.</param>
  541. /// <param name="outputCodec">The output codec.</param>
  542. /// <param name="outputPath">The output path.</param>
  543. /// <param name="cancellationToken">The cancellation token.</param>
  544. /// <returns>Task.</returns>
  545. /// <exception cref="ArgumentException">Must use inputPath list overload.</exception>
  546. private async Task ExtractTextSubtitle(
  547. MediaSourceInfo mediaSource,
  548. MediaStream subtitleStream,
  549. string outputCodec,
  550. string outputPath,
  551. CancellationToken cancellationToken)
  552. {
  553. using (await _semaphoreLocks.LockAsync(outputPath, cancellationToken).ConfigureAwait(false))
  554. {
  555. if (!File.Exists(outputPath))
  556. {
  557. var subtitleStreamIndex = EncodingHelper.FindIndex(mediaSource.MediaStreams, subtitleStream);
  558. var args = _mediaEncoder.GetInputArgument(mediaSource.Path, mediaSource);
  559. if (subtitleStream.IsExternal)
  560. {
  561. args = _mediaEncoder.GetExternalSubtitleInputArgument(subtitleStream.Path);
  562. }
  563. await ExtractTextSubtitleInternal(
  564. args,
  565. subtitleStreamIndex,
  566. outputCodec,
  567. outputPath,
  568. cancellationToken).ConfigureAwait(false);
  569. }
  570. }
  571. }
  572. private async Task ExtractTextSubtitleInternal(
  573. string inputPath,
  574. int subtitleStreamIndex,
  575. string outputCodec,
  576. string outputPath,
  577. CancellationToken cancellationToken)
  578. {
  579. ArgumentException.ThrowIfNullOrEmpty(inputPath);
  580. ArgumentException.ThrowIfNullOrEmpty(outputPath);
  581. Directory.CreateDirectory(Path.GetDirectoryName(outputPath) ?? throw new ArgumentException($"Provided path ({outputPath}) is not valid.", nameof(outputPath)));
  582. var processArgs = string.Format(
  583. CultureInfo.InvariantCulture,
  584. "-i {0} -copyts -map 0:{1} -an -vn -c:s {2} \"{3}\"",
  585. inputPath,
  586. subtitleStreamIndex,
  587. outputCodec,
  588. outputPath);
  589. int exitCode;
  590. using (var process = new Process
  591. {
  592. StartInfo = new ProcessStartInfo
  593. {
  594. CreateNoWindow = true,
  595. UseShellExecute = false,
  596. FileName = _mediaEncoder.EncoderPath,
  597. Arguments = processArgs,
  598. WindowStyle = ProcessWindowStyle.Hidden,
  599. ErrorDialog = false
  600. },
  601. EnableRaisingEvents = true
  602. })
  603. {
  604. _logger.LogInformation("{File} {Arguments}", process.StartInfo.FileName, process.StartInfo.Arguments);
  605. try
  606. {
  607. process.Start();
  608. }
  609. catch (Exception ex)
  610. {
  611. _logger.LogError(ex, "Error starting ffmpeg");
  612. throw;
  613. }
  614. try
  615. {
  616. await process.WaitForExitAsync(TimeSpan.FromMinutes(30)).ConfigureAwait(false);
  617. exitCode = process.ExitCode;
  618. }
  619. catch (OperationCanceledException)
  620. {
  621. process.Kill(true);
  622. exitCode = -1;
  623. }
  624. }
  625. var failed = false;
  626. if (exitCode == -1)
  627. {
  628. failed = true;
  629. try
  630. {
  631. _logger.LogWarning("Deleting extracted subtitle due to failure: {Path}", outputPath);
  632. _fileSystem.DeleteFile(outputPath);
  633. }
  634. catch (FileNotFoundException)
  635. {
  636. }
  637. catch (IOException ex)
  638. {
  639. _logger.LogError(ex, "Error deleting extracted subtitle {Path}", outputPath);
  640. }
  641. }
  642. else if (!File.Exists(outputPath))
  643. {
  644. failed = true;
  645. }
  646. if (failed)
  647. {
  648. _logger.LogError("ffmpeg subtitle extraction failed for {InputPath} to {OutputPath}", inputPath, outputPath);
  649. throw new FfmpegException(
  650. string.Format(CultureInfo.InvariantCulture, "ffmpeg subtitle extraction failed for {0} to {1}", inputPath, outputPath));
  651. }
  652. _logger.LogInformation("ffmpeg subtitle extraction completed for {InputPath} to {OutputPath}", inputPath, outputPath);
  653. if (string.Equals(outputCodec, "ass", StringComparison.OrdinalIgnoreCase))
  654. {
  655. await SetAssFont(outputPath, cancellationToken).ConfigureAwait(false);
  656. }
  657. }
  658. /// <summary>
  659. /// Sets the ass font.
  660. /// </summary>
  661. /// <param name="file">The file.</param>
  662. /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <c>System.Threading.CancellationToken.None</c>.</param>
  663. /// <returns>Task.</returns>
  664. private async Task SetAssFont(string file, CancellationToken cancellationToken = default)
  665. {
  666. _logger.LogInformation("Setting ass font within {File}", file);
  667. string text;
  668. Encoding encoding;
  669. using (var fileStream = AsyncFile.OpenRead(file))
  670. using (var reader = new StreamReader(fileStream, true))
  671. {
  672. encoding = reader.CurrentEncoding;
  673. text = await reader.ReadToEndAsync(cancellationToken).ConfigureAwait(false);
  674. }
  675. var newText = text.Replace(",Arial,", ",Arial Unicode MS,", StringComparison.Ordinal);
  676. if (!string.Equals(text, newText, StringComparison.Ordinal))
  677. {
  678. var fileStream = new FileStream(file, FileMode.Create, FileAccess.Write, FileShare.None, IODefaults.FileStreamBufferSize, FileOptions.Asynchronous);
  679. await using (fileStream.ConfigureAwait(false))
  680. {
  681. var writer = new StreamWriter(fileStream, encoding);
  682. await using (writer.ConfigureAwait(false))
  683. {
  684. await writer.WriteAsync(newText.AsMemory(), cancellationToken).ConfigureAwait(false);
  685. }
  686. }
  687. }
  688. }
  689. private string GetSubtitleCachePath(MediaSourceInfo mediaSource, int subtitleStreamIndex, string outputSubtitleExtension)
  690. {
  691. if (mediaSource.Protocol == MediaProtocol.File)
  692. {
  693. var ticksParam = string.Empty;
  694. var date = _fileSystem.GetLastWriteTimeUtc(mediaSource.Path);
  695. ReadOnlySpan<char> filename = (mediaSource.Path + "_" + subtitleStreamIndex.ToString(CultureInfo.InvariantCulture) + "_" + date.Ticks.ToString(CultureInfo.InvariantCulture) + ticksParam).GetMD5() + outputSubtitleExtension;
  696. var prefix = filename.Slice(0, 1);
  697. return Path.Join(SubtitleCachePath, prefix, filename);
  698. }
  699. else
  700. {
  701. ReadOnlySpan<char> filename = (mediaSource.Path + "_" + subtitleStreamIndex.ToString(CultureInfo.InvariantCulture)).GetMD5() + outputSubtitleExtension;
  702. var prefix = filename.Slice(0, 1);
  703. return Path.Join(SubtitleCachePath, prefix, filename);
  704. }
  705. }
  706. /// <inheritdoc />
  707. public async Task<string> GetSubtitleFileCharacterSet(MediaStream subtitleStream, string language, MediaSourceInfo mediaSource, CancellationToken cancellationToken)
  708. {
  709. var subtitleCodec = subtitleStream.Codec;
  710. var path = subtitleStream.Path;
  711. if (path.EndsWith(".mks", StringComparison.OrdinalIgnoreCase))
  712. {
  713. path = GetSubtitleCachePath(mediaSource, subtitleStream.Index, "." + subtitleCodec);
  714. await ExtractTextSubtitle(mediaSource, subtitleStream, subtitleCodec, path, cancellationToken)
  715. .ConfigureAwait(false);
  716. }
  717. using (var stream = await GetStream(path, mediaSource.Protocol, cancellationToken).ConfigureAwait(false))
  718. {
  719. var charset = CharsetDetector.DetectFromStream(stream).Detected?.EncodingName ?? string.Empty;
  720. // UTF16 is automatically converted to UTF8 by FFmpeg, do not specify a character encoding
  721. if ((path.EndsWith(".ass", StringComparison.Ordinal) || path.EndsWith(".ssa", StringComparison.Ordinal) || path.EndsWith(".srt", StringComparison.Ordinal))
  722. && (string.Equals(charset, "utf-16le", StringComparison.OrdinalIgnoreCase)
  723. || string.Equals(charset, "utf-16be", StringComparison.OrdinalIgnoreCase)))
  724. {
  725. charset = string.Empty;
  726. }
  727. _logger.LogDebug("charset {0} detected for {Path}", charset, path);
  728. return charset;
  729. }
  730. }
  731. private async Task<Stream> GetStream(string path, MediaProtocol protocol, CancellationToken cancellationToken)
  732. {
  733. switch (protocol)
  734. {
  735. case MediaProtocol.Http:
  736. {
  737. using var response = await _httpClientFactory.CreateClient(NamedClient.Default)
  738. .GetAsync(new Uri(path), cancellationToken)
  739. .ConfigureAwait(false);
  740. return await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
  741. }
  742. case MediaProtocol.File:
  743. return AsyncFile.OpenRead(path);
  744. default:
  745. throw new ArgumentOutOfRangeException(nameof(protocol));
  746. }
  747. }
  748. /// <inheritdoc />
  749. public void Dispose()
  750. {
  751. _semaphoreLocks.Dispose();
  752. }
  753. #pragma warning disable CA1034 // Nested types should not be visible
  754. // Only public for the unit tests
  755. public readonly record struct SubtitleInfo
  756. {
  757. public string Path { get; init; }
  758. public MediaProtocol Protocol { get; init; }
  759. public string Format { get; init; }
  760. public bool IsExternal { get; init; }
  761. }
  762. }
  763. }