SubtitleEncoder.cs 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774
  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 we don't have any way of converting it
  123. if (!TryGetWriter(outputFormat, out var writer))
  124. {
  125. return subtitle.stream;
  126. }
  127. // Return the original if the same format is being requested
  128. // Character encoding was already handled in GetSubtitleStream
  129. if (string.Equals(inputFormat, outputFormat, StringComparison.OrdinalIgnoreCase))
  130. {
  131. return subtitle.stream;
  132. }
  133. using (var stream = subtitle.stream)
  134. {
  135. return ConvertSubtitles(stream, inputFormat, outputFormat, startTimeTicks, endTimeTicks, preserveOriginalTimestamps, cancellationToken);
  136. }
  137. }
  138. private async Task<(Stream stream, string format)> GetSubtitleStream(
  139. MediaSourceInfo mediaSource,
  140. MediaStream subtitleStream,
  141. CancellationToken cancellationToken)
  142. {
  143. var fileInfo = await GetReadableFile(mediaSource, subtitleStream, cancellationToken).ConfigureAwait(false);
  144. var stream = await GetSubtitleStream(fileInfo, cancellationToken).ConfigureAwait(false);
  145. return (stream, fileInfo.Format);
  146. }
  147. private async Task<Stream> GetSubtitleStream(SubtitleInfo fileInfo, CancellationToken cancellationToken)
  148. {
  149. if (fileInfo.IsExternal)
  150. {
  151. using (var stream = await GetStream(fileInfo.Path, fileInfo.Protocol, cancellationToken).ConfigureAwait(false))
  152. {
  153. var result = CharsetDetector.DetectFromStream(stream).Detected;
  154. stream.Position = 0;
  155. if (result != null)
  156. {
  157. _logger.LogDebug("charset {CharSet} detected for {Path}", result.EncodingName, fileInfo.Path);
  158. using var reader = new StreamReader(stream, result.Encoding);
  159. var text = await reader.ReadToEndAsync().ConfigureAwait(false);
  160. return new MemoryStream(Encoding.UTF8.GetBytes(text));
  161. }
  162. }
  163. }
  164. return AsyncFile.OpenRead(fileInfo.Path);
  165. }
  166. internal async Task<SubtitleInfo> GetReadableFile(
  167. MediaSourceInfo mediaSource,
  168. MediaStream subtitleStream,
  169. CancellationToken cancellationToken)
  170. {
  171. if (!subtitleStream.IsExternal)
  172. {
  173. string outputFormat;
  174. string outputCodec;
  175. if (string.Equals(subtitleStream.Codec, "ass", StringComparison.OrdinalIgnoreCase)
  176. || string.Equals(subtitleStream.Codec, "ssa", StringComparison.OrdinalIgnoreCase)
  177. || string.Equals(subtitleStream.Codec, "srt", StringComparison.OrdinalIgnoreCase))
  178. {
  179. // Extract
  180. outputCodec = "copy";
  181. outputFormat = subtitleStream.Codec;
  182. }
  183. else if (string.Equals(subtitleStream.Codec, "subrip", StringComparison.OrdinalIgnoreCase))
  184. {
  185. // Extract
  186. outputCodec = "copy";
  187. outputFormat = "srt";
  188. }
  189. else
  190. {
  191. // Extract
  192. outputCodec = "srt";
  193. outputFormat = "srt";
  194. }
  195. // Extract
  196. var outputPath = GetSubtitleCachePath(mediaSource, subtitleStream.Index, "." + outputFormat);
  197. await ExtractTextSubtitle(mediaSource, subtitleStream.Index, outputCodec, outputPath, cancellationToken)
  198. .ConfigureAwait(false);
  199. return new SubtitleInfo(outputPath, MediaProtocol.File, outputFormat, false);
  200. }
  201. var currentFormat = (Path.GetExtension(subtitleStream.Path) ?? subtitleStream.Codec)
  202. .TrimStart('.');
  203. if (!TryGetReader(currentFormat, out _))
  204. {
  205. // Convert
  206. var outputPath = GetSubtitleCachePath(mediaSource, subtitleStream.Index, ".srt");
  207. await ConvertTextSubtitleToSrt(subtitleStream.Path, subtitleStream.Language, mediaSource, outputPath, cancellationToken).ConfigureAwait(false);
  208. return new SubtitleInfo(outputPath, MediaProtocol.File, "srt", true);
  209. }
  210. // It's possbile that the subtitleStream and mediaSource don't share the same protocol (e.g. .STRM file with local subs)
  211. return new SubtitleInfo(subtitleStream.Path, _mediaSourceManager.GetPathProtocol(subtitleStream.Path), currentFormat, true);
  212. }
  213. private bool TryGetReader(string format, [NotNullWhen(true)] out ISubtitleParser? value)
  214. {
  215. if (string.Equals(format, SubtitleFormat.SRT, StringComparison.OrdinalIgnoreCase))
  216. {
  217. value = new SrtParser(_logger);
  218. return true;
  219. }
  220. if (string.Equals(format, SubtitleFormat.SSA, StringComparison.OrdinalIgnoreCase))
  221. {
  222. value = new SsaParser(_logger);
  223. return true;
  224. }
  225. if (string.Equals(format, SubtitleFormat.ASS, StringComparison.OrdinalIgnoreCase))
  226. {
  227. value = new AssParser(_logger);
  228. return true;
  229. }
  230. value = null;
  231. return false;
  232. }
  233. private ISubtitleParser GetReader(string format)
  234. {
  235. if (TryGetReader(format, out var reader))
  236. {
  237. return reader;
  238. }
  239. throw new ArgumentException("Unsupported format: " + format);
  240. }
  241. private bool TryGetWriter(string format, [NotNullWhen(true)] out ISubtitleWriter? value)
  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))
  253. {
  254. value = new SrtWriter();
  255. return true;
  256. }
  257. if (string.Equals(format, SubtitleFormat.VTT, StringComparison.OrdinalIgnoreCase))
  258. {
  259. value = new VttWriter();
  260. return true;
  261. }
  262. if (string.Equals(format, SubtitleFormat.TTML, StringComparison.OrdinalIgnoreCase))
  263. {
  264. value = new TtmlWriter();
  265. return true;
  266. }
  267. value = null;
  268. return false;
  269. }
  270. private ISubtitleWriter GetWriter(string format)
  271. {
  272. if (TryGetWriter(format, out var writer))
  273. {
  274. return writer;
  275. }
  276. throw new ArgumentException("Unsupported format: " + format);
  277. }
  278. /// <summary>
  279. /// Gets the lock.
  280. /// </summary>
  281. /// <param name="filename">The filename.</param>
  282. /// <returns>System.Object.</returns>
  283. private SemaphoreSlim GetLock(string filename)
  284. {
  285. return _semaphoreLocks.GetOrAdd(filename, _ => new SemaphoreSlim(1, 1));
  286. }
  287. /// <summary>
  288. /// Converts the text subtitle to SRT.
  289. /// </summary>
  290. /// <param name="inputPath">The input path.</param>
  291. /// <param name="language">The language.</param>
  292. /// <param name="mediaSource">The input mediaSource.</param>
  293. /// <param name="outputPath">The output path.</param>
  294. /// <param name="cancellationToken">The cancellation token.</param>
  295. /// <returns>Task.</returns>
  296. private async Task ConvertTextSubtitleToSrt(string inputPath, string language, MediaSourceInfo mediaSource, string outputPath, CancellationToken cancellationToken)
  297. {
  298. var semaphore = GetLock(outputPath);
  299. await semaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
  300. try
  301. {
  302. if (!File.Exists(outputPath))
  303. {
  304. await ConvertTextSubtitleToSrtInternal(inputPath, language, mediaSource, outputPath, cancellationToken).ConfigureAwait(false);
  305. }
  306. }
  307. finally
  308. {
  309. semaphore.Release();
  310. }
  311. }
  312. /// <summary>
  313. /// Converts the text subtitle to SRT internal.
  314. /// </summary>
  315. /// <param name="inputPath">The input path.</param>
  316. /// <param name="language">The language.</param>
  317. /// <param name="mediaSource">The input mediaSource.</param>
  318. /// <param name="outputPath">The output path.</param>
  319. /// <param name="cancellationToken">The cancellation token.</param>
  320. /// <returns>Task.</returns>
  321. /// <exception cref="ArgumentNullException">
  322. /// The <c>inputPath</c> or <c>outputPath</c> is <c>null</c>.
  323. /// </exception>
  324. private async Task ConvertTextSubtitleToSrtInternal(string inputPath, string language, MediaSourceInfo mediaSource, string outputPath, CancellationToken cancellationToken)
  325. {
  326. if (string.IsNullOrEmpty(inputPath))
  327. {
  328. throw new ArgumentNullException(nameof(inputPath));
  329. }
  330. if (string.IsNullOrEmpty(outputPath))
  331. {
  332. throw new ArgumentNullException(nameof(outputPath));
  333. }
  334. Directory.CreateDirectory(Path.GetDirectoryName(outputPath) ?? throw new ArgumentException($"Provided path ({outputPath}) is not valid.", nameof(outputPath)));
  335. var encodingParam = await GetSubtitleFileCharacterSet(inputPath, language, mediaSource.Protocol, cancellationToken).ConfigureAwait(false);
  336. // FFmpeg automatically convert character encoding when it is UTF-16
  337. // If we specify character encoding, it rejects with "do not specify a character encoding" and "Unable to recode subtitle event"
  338. if ((inputPath.EndsWith(".smi", StringComparison.Ordinal) || inputPath.EndsWith(".sami", StringComparison.Ordinal)) &&
  339. (encodingParam.Equals("UTF-16BE", StringComparison.OrdinalIgnoreCase) ||
  340. encodingParam.Equals("UTF-16LE", StringComparison.OrdinalIgnoreCase)))
  341. {
  342. encodingParam = string.Empty;
  343. }
  344. else if (!string.IsNullOrEmpty(encodingParam))
  345. {
  346. encodingParam = " -sub_charenc " + encodingParam;
  347. }
  348. int exitCode;
  349. using (var process = new Process
  350. {
  351. StartInfo = new ProcessStartInfo
  352. {
  353. CreateNoWindow = true,
  354. UseShellExecute = false,
  355. FileName = _mediaEncoder.EncoderPath,
  356. Arguments = string.Format(CultureInfo.InvariantCulture, "{0} -i \"{1}\" -c:s srt \"{2}\"", encodingParam, inputPath, outputPath),
  357. WindowStyle = ProcessWindowStyle.Hidden,
  358. ErrorDialog = false
  359. },
  360. EnableRaisingEvents = true
  361. })
  362. {
  363. _logger.LogInformation("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments);
  364. try
  365. {
  366. process.Start();
  367. }
  368. catch (Exception ex)
  369. {
  370. _logger.LogError(ex, "Error starting ffmpeg");
  371. throw;
  372. }
  373. var ranToCompletion = await process.WaitForExitAsync(TimeSpan.FromMinutes(5)).ConfigureAwait(false);
  374. if (!ranToCompletion)
  375. {
  376. try
  377. {
  378. _logger.LogInformation("Killing ffmpeg subtitle conversion process");
  379. process.Kill();
  380. }
  381. catch (Exception ex)
  382. {
  383. _logger.LogError(ex, "Error killing subtitle conversion process");
  384. }
  385. }
  386. exitCode = ranToCompletion ? process.ExitCode : -1;
  387. }
  388. var failed = false;
  389. if (exitCode == -1)
  390. {
  391. failed = true;
  392. if (File.Exists(outputPath))
  393. {
  394. try
  395. {
  396. _logger.LogInformation("Deleting converted subtitle due to failure: ", outputPath);
  397. _fileSystem.DeleteFile(outputPath);
  398. }
  399. catch (IOException ex)
  400. {
  401. _logger.LogError(ex, "Error deleting converted subtitle {Path}", outputPath);
  402. }
  403. }
  404. }
  405. else if (!File.Exists(outputPath))
  406. {
  407. failed = true;
  408. }
  409. if (failed)
  410. {
  411. _logger.LogError("ffmpeg subtitle conversion failed for {Path}", inputPath);
  412. throw new FfmpegException(
  413. string.Format(CultureInfo.InvariantCulture, "ffmpeg subtitle conversion failed for {0}", inputPath));
  414. }
  415. await SetAssFont(outputPath, cancellationToken).ConfigureAwait(false);
  416. _logger.LogInformation("ffmpeg subtitle conversion succeeded for {Path}", inputPath);
  417. }
  418. /// <summary>
  419. /// Extracts the text subtitle.
  420. /// </summary>
  421. /// <param name="mediaSource">The mediaSource.</param>
  422. /// <param name="subtitleStreamIndex">Index of the subtitle stream.</param>
  423. /// <param name="outputCodec">The output codec.</param>
  424. /// <param name="outputPath">The output path.</param>
  425. /// <param name="cancellationToken">The cancellation token.</param>
  426. /// <returns>Task.</returns>
  427. /// <exception cref="ArgumentException">Must use inputPath list overload.</exception>
  428. private async Task ExtractTextSubtitle(
  429. MediaSourceInfo mediaSource,
  430. int subtitleStreamIndex,
  431. string outputCodec,
  432. string outputPath,
  433. CancellationToken cancellationToken)
  434. {
  435. var semaphore = GetLock(outputPath);
  436. await semaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
  437. try
  438. {
  439. if (!File.Exists(outputPath))
  440. {
  441. await ExtractTextSubtitleInternal(
  442. _mediaEncoder.GetInputArgument(mediaSource.Path, mediaSource),
  443. subtitleStreamIndex,
  444. outputCodec,
  445. outputPath,
  446. cancellationToken).ConfigureAwait(false);
  447. }
  448. }
  449. finally
  450. {
  451. semaphore.Release();
  452. }
  453. }
  454. private async Task ExtractTextSubtitleInternal(
  455. string inputPath,
  456. int subtitleStreamIndex,
  457. string outputCodec,
  458. string outputPath,
  459. CancellationToken cancellationToken)
  460. {
  461. if (string.IsNullOrEmpty(inputPath))
  462. {
  463. throw new ArgumentNullException(nameof(inputPath));
  464. }
  465. if (string.IsNullOrEmpty(outputPath))
  466. {
  467. throw new ArgumentNullException(nameof(outputPath));
  468. }
  469. Directory.CreateDirectory(Path.GetDirectoryName(outputPath) ?? throw new ArgumentException($"Provided path ({outputPath}) is not valid.", nameof(outputPath)));
  470. var processArgs = string.Format(
  471. CultureInfo.InvariantCulture,
  472. "-i {0} -map 0:{1} -an -vn -c:s {2} \"{3}\"",
  473. inputPath,
  474. subtitleStreamIndex,
  475. outputCodec,
  476. outputPath);
  477. int exitCode;
  478. using (var process = new Process
  479. {
  480. StartInfo = new ProcessStartInfo
  481. {
  482. CreateNoWindow = true,
  483. UseShellExecute = false,
  484. FileName = _mediaEncoder.EncoderPath,
  485. Arguments = processArgs,
  486. WindowStyle = ProcessWindowStyle.Hidden,
  487. ErrorDialog = false
  488. },
  489. EnableRaisingEvents = true
  490. })
  491. {
  492. _logger.LogInformation("{File} {Arguments}", process.StartInfo.FileName, process.StartInfo.Arguments);
  493. try
  494. {
  495. process.Start();
  496. }
  497. catch (Exception ex)
  498. {
  499. _logger.LogError(ex, "Error starting ffmpeg");
  500. throw;
  501. }
  502. var ranToCompletion = await process.WaitForExitAsync(TimeSpan.FromMinutes(5)).ConfigureAwait(false);
  503. if (!ranToCompletion)
  504. {
  505. try
  506. {
  507. _logger.LogWarning("Killing ffmpeg subtitle extraction process");
  508. process.Kill();
  509. }
  510. catch (Exception ex)
  511. {
  512. _logger.LogError(ex, "Error killing subtitle extraction process");
  513. }
  514. }
  515. exitCode = ranToCompletion ? process.ExitCode : -1;
  516. }
  517. var failed = false;
  518. if (exitCode == -1)
  519. {
  520. failed = true;
  521. try
  522. {
  523. _logger.LogWarning("Deleting extracted subtitle due to failure: {Path}", outputPath);
  524. _fileSystem.DeleteFile(outputPath);
  525. }
  526. catch (FileNotFoundException)
  527. {
  528. }
  529. catch (IOException ex)
  530. {
  531. _logger.LogError(ex, "Error deleting extracted subtitle {Path}", outputPath);
  532. }
  533. }
  534. else if (!File.Exists(outputPath))
  535. {
  536. failed = true;
  537. }
  538. if (failed)
  539. {
  540. var msg = $"ffmpeg subtitle extraction failed for {inputPath} to {outputPath}";
  541. _logger.LogError(msg);
  542. throw new FfmpegException(msg);
  543. }
  544. else
  545. {
  546. var msg = $"ffmpeg subtitle extraction completed for {inputPath} to {outputPath}";
  547. _logger.LogInformation(msg);
  548. }
  549. if (string.Equals(outputCodec, "ass", StringComparison.OrdinalIgnoreCase))
  550. {
  551. await SetAssFont(outputPath, cancellationToken).ConfigureAwait(false);
  552. }
  553. }
  554. /// <summary>
  555. /// Sets the ass font.
  556. /// </summary>
  557. /// <param name="file">The file.</param>
  558. /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <c>System.Threading.CancellationToken.None</c>.</param>
  559. /// <returns>Task.</returns>
  560. private async Task SetAssFont(string file, CancellationToken cancellationToken = default)
  561. {
  562. _logger.LogInformation("Setting ass font within {File}", file);
  563. string text;
  564. Encoding encoding;
  565. using (var fileStream = AsyncFile.OpenRead(file))
  566. using (var reader = new StreamReader(fileStream, true))
  567. {
  568. encoding = reader.CurrentEncoding;
  569. text = await reader.ReadToEndAsync().ConfigureAwait(false);
  570. }
  571. var newText = text.Replace(",Arial,", ",Arial Unicode MS,", StringComparison.Ordinal);
  572. if (!string.Equals(text, newText, StringComparison.Ordinal))
  573. {
  574. using (var fileStream = new FileStream(file, FileMode.Create, FileAccess.Write, FileShare.None, IODefaults.FileStreamBufferSize, FileOptions.Asynchronous))
  575. using (var writer = new StreamWriter(fileStream, encoding))
  576. {
  577. await writer.WriteAsync(newText.AsMemory(), cancellationToken).ConfigureAwait(false);
  578. }
  579. }
  580. }
  581. private string GetSubtitleCachePath(MediaSourceInfo mediaSource, int subtitleStreamIndex, string outputSubtitleExtension)
  582. {
  583. if (mediaSource.Protocol == MediaProtocol.File)
  584. {
  585. var ticksParam = string.Empty;
  586. var date = _fileSystem.GetLastWriteTimeUtc(mediaSource.Path);
  587. ReadOnlySpan<char> filename = (mediaSource.Path + "_" + subtitleStreamIndex.ToString(CultureInfo.InvariantCulture) + "_" + date.Ticks.ToString(CultureInfo.InvariantCulture) + ticksParam).GetMD5() + outputSubtitleExtension;
  588. var prefix = filename.Slice(0, 1);
  589. return Path.Join(SubtitleCachePath, prefix, filename);
  590. }
  591. else
  592. {
  593. ReadOnlySpan<char> filename = (mediaSource.Path + "_" + subtitleStreamIndex.ToString(CultureInfo.InvariantCulture)).GetMD5() + outputSubtitleExtension;
  594. var prefix = filename.Slice(0, 1);
  595. return Path.Join(SubtitleCachePath, prefix, filename);
  596. }
  597. }
  598. /// <inheritdoc />
  599. public async Task<string> GetSubtitleFileCharacterSet(string path, string language, MediaProtocol protocol, CancellationToken cancellationToken)
  600. {
  601. using (var stream = await GetStream(path, protocol, cancellationToken).ConfigureAwait(false))
  602. {
  603. var charset = CharsetDetector.DetectFromStream(stream).Detected?.EncodingName ?? string.Empty;
  604. // UTF16 is automatically converted to UTF8 by FFmpeg, do not specify a character encoding
  605. if ((path.EndsWith(".ass", StringComparison.Ordinal) || path.EndsWith(".ssa", StringComparison.Ordinal) || path.EndsWith(".srt", StringComparison.Ordinal))
  606. && (string.Equals(charset, "utf-16le", StringComparison.OrdinalIgnoreCase)
  607. || string.Equals(charset, "utf-16be", StringComparison.OrdinalIgnoreCase)))
  608. {
  609. charset = string.Empty;
  610. }
  611. _logger.LogDebug("charset {0} detected for {Path}", charset, path);
  612. return charset;
  613. }
  614. }
  615. private async Task<Stream> GetStream(string path, MediaProtocol protocol, CancellationToken cancellationToken)
  616. {
  617. switch (protocol)
  618. {
  619. case MediaProtocol.Http:
  620. {
  621. using var response = await _httpClientFactory.CreateClient(NamedClient.Default)
  622. .GetAsync(new Uri(path), cancellationToken)
  623. .ConfigureAwait(false);
  624. return await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
  625. }
  626. case MediaProtocol.File:
  627. return AsyncFile.OpenRead(path);
  628. default:
  629. throw new ArgumentOutOfRangeException(nameof(protocol));
  630. }
  631. }
  632. internal readonly struct SubtitleInfo
  633. {
  634. public SubtitleInfo(string path, MediaProtocol protocol, string format, bool isExternal)
  635. {
  636. Path = path;
  637. Protocol = protocol;
  638. Format = format;
  639. IsExternal = isExternal;
  640. }
  641. public string Path { get; }
  642. public MediaProtocol Protocol { get; }
  643. public string Format { get; }
  644. public bool IsExternal { get; }
  645. }
  646. }
  647. }