SubtitleEncoder.cs 30 KB

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