SubtitleEncoder.cs 29 KB

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