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.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 AsyncFile.OpenRead(fileInfo.Path);
  164. }
  165. internal 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. // It's possbile that the subtitleStream and mediaSource don't share the same protocol (e.g. .STRM file with local subs)
  210. return new SubtitleInfo(subtitleStream.Path, _mediaSourceManager.GetPathProtocol(subtitleStream.Path), currentFormat, true);
  211. }
  212. private bool TryGetReader(string format, [NotNullWhen(true)] out ISubtitleParser? value)
  213. {
  214. if (string.Equals(format, SubtitleFormat.SRT, StringComparison.OrdinalIgnoreCase))
  215. {
  216. value = new SrtParser(_logger);
  217. return true;
  218. }
  219. if (string.Equals(format, SubtitleFormat.SSA, StringComparison.OrdinalIgnoreCase))
  220. {
  221. value = new SsaParser(_logger);
  222. return true;
  223. }
  224. if (string.Equals(format, SubtitleFormat.ASS, StringComparison.OrdinalIgnoreCase))
  225. {
  226. value = new AssParser(_logger);
  227. return true;
  228. }
  229. value = null;
  230. return false;
  231. }
  232. private ISubtitleParser GetReader(string format)
  233. {
  234. if (TryGetReader(format, out var reader))
  235. {
  236. return reader;
  237. }
  238. throw new ArgumentException("Unsupported format: " + format);
  239. }
  240. private bool TryGetWriter(string format, [NotNullWhen(true)] out ISubtitleWriter? value)
  241. {
  242. if (string.IsNullOrEmpty(format))
  243. {
  244. throw new ArgumentNullException(nameof(format));
  245. }
  246. if (string.Equals(format, "json", StringComparison.OrdinalIgnoreCase))
  247. {
  248. value = new JsonWriter();
  249. return true;
  250. }
  251. if (string.Equals(format, SubtitleFormat.SRT, StringComparison.OrdinalIgnoreCase))
  252. {
  253. value = new SrtWriter();
  254. return true;
  255. }
  256. if (string.Equals(format, SubtitleFormat.VTT, StringComparison.OrdinalIgnoreCase))
  257. {
  258. value = new VttWriter();
  259. return true;
  260. }
  261. if (string.Equals(format, SubtitleFormat.TTML, StringComparison.OrdinalIgnoreCase))
  262. {
  263. value = new TtmlWriter();
  264. return true;
  265. }
  266. value = null;
  267. return false;
  268. }
  269. private ISubtitleWriter GetWriter(string format)
  270. {
  271. if (TryGetWriter(format, out var writer))
  272. {
  273. return writer;
  274. }
  275. throw new ArgumentException("Unsupported format: " + format);
  276. }
  277. /// <summary>
  278. /// Gets the lock.
  279. /// </summary>
  280. /// <param name="filename">The filename.</param>
  281. /// <returns>System.Object.</returns>
  282. private SemaphoreSlim GetLock(string filename)
  283. {
  284. return _semaphoreLocks.GetOrAdd(filename, _ => new SemaphoreSlim(1, 1));
  285. }
  286. /// <summary>
  287. /// Converts the text subtitle to SRT.
  288. /// </summary>
  289. /// <param name="inputPath">The input path.</param>
  290. /// <param name="language">The language.</param>
  291. /// <param name="mediaSource">The input mediaSource.</param>
  292. /// <param name="outputPath">The output path.</param>
  293. /// <param name="cancellationToken">The cancellation token.</param>
  294. /// <returns>Task.</returns>
  295. private async Task ConvertTextSubtitleToSrt(string inputPath, string language, MediaSourceInfo mediaSource, string outputPath, CancellationToken cancellationToken)
  296. {
  297. var semaphore = GetLock(outputPath);
  298. await semaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
  299. try
  300. {
  301. if (!File.Exists(outputPath))
  302. {
  303. await ConvertTextSubtitleToSrtInternal(inputPath, language, mediaSource, outputPath, cancellationToken).ConfigureAwait(false);
  304. }
  305. }
  306. finally
  307. {
  308. semaphore.Release();
  309. }
  310. }
  311. /// <summary>
  312. /// Converts the text subtitle to SRT internal.
  313. /// </summary>
  314. /// <param name="inputPath">The input path.</param>
  315. /// <param name="language">The language.</param>
  316. /// <param name="mediaSource">The input mediaSource.</param>
  317. /// <param name="outputPath">The output path.</param>
  318. /// <param name="cancellationToken">The cancellation token.</param>
  319. /// <returns>Task.</returns>
  320. /// <exception cref="ArgumentNullException">
  321. /// The <c>inputPath</c> or <c>outputPath</c> is <c>null</c>.
  322. /// </exception>
  323. private async Task ConvertTextSubtitleToSrtInternal(string inputPath, string language, MediaSourceInfo mediaSource, string outputPath, CancellationToken cancellationToken)
  324. {
  325. if (string.IsNullOrEmpty(inputPath))
  326. {
  327. throw new ArgumentNullException(nameof(inputPath));
  328. }
  329. if (string.IsNullOrEmpty(outputPath))
  330. {
  331. throw new ArgumentNullException(nameof(outputPath));
  332. }
  333. Directory.CreateDirectory(Path.GetDirectoryName(outputPath) ?? throw new ArgumentException($"Provided path ({outputPath}) is not valid.", nameof(outputPath)));
  334. var encodingParam = await GetSubtitleFileCharacterSet(inputPath, language, mediaSource.Protocol, cancellationToken).ConfigureAwait(false);
  335. // FFmpeg automatically convert character encoding when it is UTF-16
  336. // If we specify character encoding, it rejects with "do not specify a character encoding" and "Unable to recode subtitle event"
  337. if ((inputPath.EndsWith(".smi", StringComparison.Ordinal) || inputPath.EndsWith(".sami", StringComparison.Ordinal)) &&
  338. (encodingParam.Equals("UTF-16BE", StringComparison.OrdinalIgnoreCase) ||
  339. encodingParam.Equals("UTF-16LE", StringComparison.OrdinalIgnoreCase)))
  340. {
  341. encodingParam = string.Empty;
  342. }
  343. else if (!string.IsNullOrEmpty(encodingParam))
  344. {
  345. encodingParam = " -sub_charenc " + encodingParam;
  346. }
  347. int exitCode;
  348. using (var process = new Process
  349. {
  350. StartInfo = new ProcessStartInfo
  351. {
  352. CreateNoWindow = true,
  353. UseShellExecute = false,
  354. FileName = _mediaEncoder.EncoderPath,
  355. Arguments = string.Format(CultureInfo.InvariantCulture, "{0} -i \"{1}\" -c:s srt \"{2}\"", encodingParam, inputPath, outputPath),
  356. WindowStyle = ProcessWindowStyle.Hidden,
  357. ErrorDialog = false
  358. },
  359. EnableRaisingEvents = true
  360. })
  361. {
  362. _logger.LogInformation("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments);
  363. try
  364. {
  365. process.Start();
  366. }
  367. catch (Exception ex)
  368. {
  369. _logger.LogError(ex, "Error starting ffmpeg");
  370. throw;
  371. }
  372. var ranToCompletion = await process.WaitForExitAsync(TimeSpan.FromMinutes(5)).ConfigureAwait(false);
  373. if (!ranToCompletion)
  374. {
  375. try
  376. {
  377. _logger.LogInformation("Killing ffmpeg subtitle conversion process");
  378. process.Kill();
  379. }
  380. catch (Exception ex)
  381. {
  382. _logger.LogError(ex, "Error killing subtitle conversion process");
  383. }
  384. }
  385. exitCode = ranToCompletion ? process.ExitCode : -1;
  386. }
  387. var failed = false;
  388. if (exitCode == -1)
  389. {
  390. failed = true;
  391. if (File.Exists(outputPath))
  392. {
  393. try
  394. {
  395. _logger.LogInformation("Deleting converted subtitle due to failure: ", outputPath);
  396. _fileSystem.DeleteFile(outputPath);
  397. }
  398. catch (IOException ex)
  399. {
  400. _logger.LogError(ex, "Error deleting converted subtitle {Path}", outputPath);
  401. }
  402. }
  403. }
  404. else if (!File.Exists(outputPath))
  405. {
  406. failed = true;
  407. }
  408. if (failed)
  409. {
  410. _logger.LogError("ffmpeg subtitle conversion failed for {Path}", inputPath);
  411. throw new FfmpegException(
  412. string.Format(CultureInfo.InvariantCulture, "ffmpeg subtitle conversion failed for {0}", inputPath));
  413. }
  414. await SetAssFont(outputPath, cancellationToken).ConfigureAwait(false);
  415. _logger.LogInformation("ffmpeg subtitle conversion succeeded for {Path}", inputPath);
  416. }
  417. /// <summary>
  418. /// Extracts the text subtitle.
  419. /// </summary>
  420. /// <param name="mediaSource">The mediaSource.</param>
  421. /// <param name="subtitleStreamIndex">Index of the subtitle stream.</param>
  422. /// <param name="outputCodec">The output codec.</param>
  423. /// <param name="outputPath">The output path.</param>
  424. /// <param name="cancellationToken">The cancellation token.</param>
  425. /// <returns>Task.</returns>
  426. /// <exception cref="ArgumentException">Must use inputPath list overload.</exception>
  427. private async Task ExtractTextSubtitle(
  428. MediaSourceInfo mediaSource,
  429. int subtitleStreamIndex,
  430. string outputCodec,
  431. string outputPath,
  432. CancellationToken cancellationToken)
  433. {
  434. var semaphore = GetLock(outputPath);
  435. await semaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
  436. try
  437. {
  438. if (!File.Exists(outputPath))
  439. {
  440. await ExtractTextSubtitleInternal(
  441. _mediaEncoder.GetInputArgument(mediaSource.Path, mediaSource),
  442. subtitleStreamIndex,
  443. outputCodec,
  444. outputPath,
  445. cancellationToken).ConfigureAwait(false);
  446. }
  447. }
  448. finally
  449. {
  450. semaphore.Release();
  451. }
  452. }
  453. private async Task ExtractTextSubtitleInternal(
  454. string inputPath,
  455. int subtitleStreamIndex,
  456. string outputCodec,
  457. string outputPath,
  458. CancellationToken cancellationToken)
  459. {
  460. if (string.IsNullOrEmpty(inputPath))
  461. {
  462. throw new ArgumentNullException(nameof(inputPath));
  463. }
  464. if (string.IsNullOrEmpty(outputPath))
  465. {
  466. throw new ArgumentNullException(nameof(outputPath));
  467. }
  468. Directory.CreateDirectory(Path.GetDirectoryName(outputPath) ?? throw new ArgumentException($"Provided path ({outputPath}) is not valid.", nameof(outputPath)));
  469. var processArgs = string.Format(
  470. CultureInfo.InvariantCulture,
  471. "-i {0} -map 0:{1} -an -vn -c:s {2} \"{3}\"",
  472. inputPath,
  473. subtitleStreamIndex,
  474. outputCodec,
  475. outputPath);
  476. int exitCode;
  477. using (var process = new Process
  478. {
  479. StartInfo = new ProcessStartInfo
  480. {
  481. CreateNoWindow = true,
  482. UseShellExecute = false,
  483. FileName = _mediaEncoder.EncoderPath,
  484. Arguments = processArgs,
  485. WindowStyle = ProcessWindowStyle.Hidden,
  486. ErrorDialog = false
  487. },
  488. EnableRaisingEvents = true
  489. })
  490. {
  491. _logger.LogInformation("{File} {Arguments}", process.StartInfo.FileName, process.StartInfo.Arguments);
  492. try
  493. {
  494. process.Start();
  495. }
  496. catch (Exception ex)
  497. {
  498. _logger.LogError(ex, "Error starting ffmpeg");
  499. throw;
  500. }
  501. var ranToCompletion = await process.WaitForExitAsync(TimeSpan.FromMinutes(5)).ConfigureAwait(false);
  502. if (!ranToCompletion)
  503. {
  504. try
  505. {
  506. _logger.LogWarning("Killing ffmpeg subtitle extraction process");
  507. process.Kill();
  508. }
  509. catch (Exception ex)
  510. {
  511. _logger.LogError(ex, "Error killing subtitle extraction process");
  512. }
  513. }
  514. exitCode = ranToCompletion ? process.ExitCode : -1;
  515. }
  516. var failed = false;
  517. if (exitCode == -1)
  518. {
  519. failed = true;
  520. try
  521. {
  522. _logger.LogWarning("Deleting extracted subtitle due to failure: {Path}", outputPath);
  523. _fileSystem.DeleteFile(outputPath);
  524. }
  525. catch (FileNotFoundException)
  526. {
  527. }
  528. catch (IOException ex)
  529. {
  530. _logger.LogError(ex, "Error deleting extracted subtitle {Path}", outputPath);
  531. }
  532. }
  533. else if (!File.Exists(outputPath))
  534. {
  535. failed = true;
  536. }
  537. if (failed)
  538. {
  539. var msg = $"ffmpeg subtitle extraction failed for {inputPath} to {outputPath}";
  540. _logger.LogError(msg);
  541. throw new FfmpegException(msg);
  542. }
  543. else
  544. {
  545. var msg = $"ffmpeg subtitle extraction completed for {inputPath} to {outputPath}";
  546. _logger.LogInformation(msg);
  547. }
  548. if (string.Equals(outputCodec, "ass", StringComparison.OrdinalIgnoreCase))
  549. {
  550. await SetAssFont(outputPath, cancellationToken).ConfigureAwait(false);
  551. }
  552. }
  553. /// <summary>
  554. /// Sets the ass font.
  555. /// </summary>
  556. /// <param name="file">The file.</param>
  557. /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <c>System.Threading.CancellationToken.None</c>.</param>
  558. /// <returns>Task.</returns>
  559. private async Task SetAssFont(string file, CancellationToken cancellationToken = default)
  560. {
  561. _logger.LogInformation("Setting ass font within {File}", file);
  562. string text;
  563. Encoding encoding;
  564. using (var fileStream = AsyncFile.OpenRead(file))
  565. using (var reader = new StreamReader(fileStream, true))
  566. {
  567. encoding = reader.CurrentEncoding;
  568. text = await reader.ReadToEndAsync().ConfigureAwait(false);
  569. }
  570. var newText = text.Replace(",Arial,", ",Arial Unicode MS,", StringComparison.Ordinal);
  571. if (!string.Equals(text, newText, StringComparison.Ordinal))
  572. {
  573. // use FileShare.None as this bypasses dotnet bug dotnet/runtime#42790 .
  574. using (var fileStream = new FileStream(file, FileMode.Create, FileAccess.Write, FileShare.None, IODefaults.FileStreamBufferSize, AsyncFile.UseAsyncIO))
  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. }