SubtitleEncoder.cs 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778
  1. #pragma warning disable CS1591
  2. using System;
  3. using System.Collections.Concurrent;
  4. using System.Diagnostics;
  5. using System.Globalization;
  6. using System.IO;
  7. using System.Linq;
  8. using System.Net.Http;
  9. using System.Text;
  10. using System.Threading;
  11. using System.Threading.Tasks;
  12. using MediaBrowser.Common.Configuration;
  13. using MediaBrowser.Common.Extensions;
  14. using MediaBrowser.Common.Net;
  15. using MediaBrowser.Controller.Entities;
  16. using MediaBrowser.Controller.Library;
  17. using MediaBrowser.Controller.MediaEncoding;
  18. using MediaBrowser.Model.Dto;
  19. using MediaBrowser.Model.Entities;
  20. using MediaBrowser.Model.IO;
  21. using MediaBrowser.Model.MediaInfo;
  22. using Microsoft.Extensions.Logging;
  23. using UtfUnknown;
  24. namespace MediaBrowser.MediaEncoding.Subtitles
  25. {
  26. public class SubtitleEncoder : ISubtitleEncoder
  27. {
  28. private readonly ILogger<SubtitleEncoder> _logger;
  29. private readonly IApplicationPaths _appPaths;
  30. private readonly IFileSystem _fileSystem;
  31. private readonly IMediaEncoder _mediaEncoder;
  32. private readonly IHttpClientFactory _httpClientFactory;
  33. private readonly IMediaSourceManager _mediaSourceManager;
  34. /// <summary>
  35. /// The _semaphoreLocks.
  36. /// </summary>
  37. private readonly ConcurrentDictionary<string, SemaphoreSlim> _semaphoreLocks =
  38. new ConcurrentDictionary<string, SemaphoreSlim>();
  39. public SubtitleEncoder(
  40. ILogger<SubtitleEncoder> logger,
  41. IApplicationPaths appPaths,
  42. IFileSystem fileSystem,
  43. IMediaEncoder mediaEncoder,
  44. IHttpClientFactory httpClientFactory,
  45. IMediaSourceManager mediaSourceManager)
  46. {
  47. _logger = logger;
  48. _appPaths = appPaths;
  49. _fileSystem = fileSystem;
  50. _mediaEncoder = mediaEncoder;
  51. _httpClientFactory = httpClientFactory;
  52. _mediaSourceManager = mediaSourceManager;
  53. }
  54. private string SubtitleCachePath => Path.Combine(_appPaths.DataPath, "subtitles");
  55. private Stream ConvertSubtitles(
  56. Stream stream,
  57. string inputFormat,
  58. string outputFormat,
  59. long startTimeTicks,
  60. long endTimeTicks,
  61. bool preserveOriginalTimestamps,
  62. CancellationToken cancellationToken)
  63. {
  64. var ms = new MemoryStream();
  65. try
  66. {
  67. var reader = GetReader(inputFormat, true);
  68. var trackInfo = reader.Parse(stream, cancellationToken);
  69. FilterEvents(trackInfo, startTimeTicks, endTimeTicks, preserveOriginalTimestamps);
  70. var writer = GetWriter(outputFormat);
  71. writer.Write(trackInfo, ms, cancellationToken);
  72. ms.Position = 0;
  73. }
  74. catch
  75. {
  76. ms.Dispose();
  77. throw;
  78. }
  79. return ms;
  80. }
  81. private void FilterEvents(SubtitleTrackInfo track, long startPositionTicks, long endTimeTicks, bool preserveTimestamps)
  82. {
  83. // Drop subs that are earlier than what we're looking for
  84. track.TrackEvents = track.TrackEvents
  85. .SkipWhile(i => (i.StartPositionTicks - startPositionTicks) < 0 || (i.EndPositionTicks - startPositionTicks) < 0)
  86. .ToArray();
  87. if (endTimeTicks > 0)
  88. {
  89. track.TrackEvents = track.TrackEvents
  90. .TakeWhile(i => i.StartPositionTicks <= endTimeTicks)
  91. .ToArray();
  92. }
  93. if (!preserveTimestamps)
  94. {
  95. foreach (var trackEvent in track.TrackEvents)
  96. {
  97. trackEvent.EndPositionTicks -= startPositionTicks;
  98. trackEvent.StartPositionTicks -= startPositionTicks;
  99. }
  100. }
  101. }
  102. async Task<Stream> ISubtitleEncoder.GetSubtitles(BaseItem item, string mediaSourceId, int subtitleStreamIndex, string outputFormat, long startTimeTicks, long endTimeTicks, bool preserveOriginalTimestamps, CancellationToken cancellationToken)
  103. {
  104. if (item == null)
  105. {
  106. throw new ArgumentNullException(nameof(item));
  107. }
  108. if (string.IsNullOrWhiteSpace(mediaSourceId))
  109. {
  110. throw new ArgumentNullException(nameof(mediaSourceId));
  111. }
  112. var mediaSources = await _mediaSourceManager.GetPlaybackMediaSources(item, null, true, false, cancellationToken).ConfigureAwait(false);
  113. var mediaSource = mediaSources
  114. .First(i => string.Equals(i.Id, mediaSourceId, StringComparison.OrdinalIgnoreCase));
  115. var subtitleStream = mediaSource.MediaStreams
  116. .First(i => i.Type == MediaStreamType.Subtitle && i.Index == subtitleStreamIndex);
  117. var subtitle = await GetSubtitleStream(mediaSource, subtitleStream, cancellationToken)
  118. .ConfigureAwait(false);
  119. var inputFormat = subtitle.format;
  120. var writer = TryGetWriter(outputFormat);
  121. // Return the original if we don't have any way of converting it
  122. if (writer == null)
  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 inputFile = mediaSource.Path;
  143. var protocol = mediaSource.Protocol;
  144. if (subtitleStream.IsExternal)
  145. {
  146. protocol = _mediaSourceManager.GetPathProtocol(subtitleStream.Path);
  147. }
  148. var fileInfo = await GetReadableFile(mediaSource.Path, inputFile, mediaSource, subtitleStream, cancellationToken).ConfigureAwait(false);
  149. var stream = await GetSubtitleStream(fileInfo.Path, fileInfo.Protocol, fileInfo.IsExternal, cancellationToken).ConfigureAwait(false);
  150. return (stream, fileInfo.Format);
  151. }
  152. private async Task<Stream> GetSubtitleStream(string path, MediaProtocol protocol, bool requiresCharset, CancellationToken cancellationToken)
  153. {
  154. if (requiresCharset)
  155. {
  156. using (var stream = await GetStream(path, protocol, cancellationToken).ConfigureAwait(false))
  157. {
  158. var result = CharsetDetector.DetectFromStream(stream).Detected;
  159. stream.Position = 0;
  160. if (result != null)
  161. {
  162. _logger.LogDebug("charset {CharSet} detected for {Path}", result.EncodingName, path);
  163. using var reader = new StreamReader(stream, result.Encoding);
  164. var text = await reader.ReadToEndAsync().ConfigureAwait(false);
  165. return new MemoryStream(Encoding.UTF8.GetBytes(text));
  166. }
  167. }
  168. }
  169. return File.OpenRead(path);
  170. }
  171. private async Task<SubtitleInfo> GetReadableFile(
  172. string mediaPath,
  173. string inputFile,
  174. MediaSourceInfo mediaSource,
  175. MediaStream subtitleStream,
  176. CancellationToken cancellationToken)
  177. {
  178. if (!subtitleStream.IsExternal)
  179. {
  180. string outputFormat;
  181. string outputCodec;
  182. if (string.Equals(subtitleStream.Codec, "ass", StringComparison.OrdinalIgnoreCase) ||
  183. string.Equals(subtitleStream.Codec, "ssa", StringComparison.OrdinalIgnoreCase) ||
  184. string.Equals(subtitleStream.Codec, "srt", StringComparison.OrdinalIgnoreCase))
  185. {
  186. // Extract
  187. outputCodec = "copy";
  188. outputFormat = subtitleStream.Codec;
  189. }
  190. else if (string.Equals(subtitleStream.Codec, "subrip", StringComparison.OrdinalIgnoreCase))
  191. {
  192. // Extract
  193. outputCodec = "copy";
  194. outputFormat = "srt";
  195. }
  196. else
  197. {
  198. // Extract
  199. outputCodec = "srt";
  200. outputFormat = "srt";
  201. }
  202. // Extract
  203. var outputPath = GetSubtitleCachePath(mediaPath, mediaSource, subtitleStream.Index, "." + outputFormat);
  204. await ExtractTextSubtitle(inputFile, mediaSource, subtitleStream.Index, outputCodec, outputPath, cancellationToken)
  205. .ConfigureAwait(false);
  206. return new SubtitleInfo(outputPath, MediaProtocol.File, outputFormat, false);
  207. }
  208. var currentFormat = (Path.GetExtension(subtitleStream.Path) ?? subtitleStream.Codec)
  209. .TrimStart('.');
  210. if (GetReader(currentFormat, false) == null)
  211. {
  212. // Convert
  213. var outputPath = GetSubtitleCachePath(mediaPath, mediaSource, subtitleStream.Index, ".srt");
  214. await ConvertTextSubtitleToSrt(subtitleStream.Path, subtitleStream.Language, mediaSource, outputPath, cancellationToken).ConfigureAwait(false);
  215. return new SubtitleInfo(outputPath, MediaProtocol.File, "srt", true);
  216. }
  217. return new SubtitleInfo(subtitleStream.Path, mediaSource.Protocol, currentFormat, true);
  218. }
  219. private ISubtitleParser GetReader(string format, bool throwIfMissing)
  220. {
  221. if (string.IsNullOrEmpty(format))
  222. {
  223. throw new ArgumentNullException(nameof(format));
  224. }
  225. if (string.Equals(format, SubtitleFormat.SRT, StringComparison.OrdinalIgnoreCase))
  226. {
  227. return new SrtParser(_logger);
  228. }
  229. if (string.Equals(format, SubtitleFormat.SSA, StringComparison.OrdinalIgnoreCase))
  230. {
  231. return new SsaParser(_logger);
  232. }
  233. if (string.Equals(format, SubtitleFormat.ASS, StringComparison.OrdinalIgnoreCase))
  234. {
  235. return new AssParser(_logger);
  236. }
  237. if (throwIfMissing)
  238. {
  239. throw new ArgumentException("Unsupported format: " + format);
  240. }
  241. return null;
  242. }
  243. private ISubtitleWriter TryGetWriter(string format)
  244. {
  245. if (string.IsNullOrEmpty(format))
  246. {
  247. throw new ArgumentNullException(nameof(format));
  248. }
  249. if (string.Equals(format, "json", StringComparison.OrdinalIgnoreCase))
  250. {
  251. return new JsonWriter();
  252. }
  253. if (string.Equals(format, SubtitleFormat.SRT, StringComparison.OrdinalIgnoreCase))
  254. {
  255. return new SrtWriter();
  256. }
  257. if (string.Equals(format, SubtitleFormat.VTT, StringComparison.OrdinalIgnoreCase))
  258. {
  259. return new VttWriter();
  260. }
  261. if (string.Equals(format, SubtitleFormat.TTML, StringComparison.OrdinalIgnoreCase))
  262. {
  263. return new TtmlWriter();
  264. }
  265. return null;
  266. }
  267. private ISubtitleWriter GetWriter(string format)
  268. {
  269. var writer = TryGetWriter(format);
  270. if (writer != null)
  271. {
  272. return writer;
  273. }
  274. throw new ArgumentException("Unsupported format: " + format);
  275. }
  276. /// <summary>
  277. /// Gets the lock.
  278. /// </summary>
  279. /// <param name="filename">The filename.</param>
  280. /// <returns>System.Object.</returns>
  281. private SemaphoreSlim GetLock(string filename)
  282. {
  283. return _semaphoreLocks.GetOrAdd(filename, _ => new SemaphoreSlim(1, 1));
  284. }
  285. /// <summary>
  286. /// Converts the text subtitle to SRT.
  287. /// </summary>
  288. /// <param name="inputPath">The input path.</param>
  289. /// <param name="language">The language.</param>
  290. /// <param name="mediaSource">The input mediaSource.</param>
  291. /// <param name="outputPath">The output path.</param>
  292. /// <param name="cancellationToken">The cancellation token.</param>
  293. /// <returns>Task.</returns>
  294. private async Task ConvertTextSubtitleToSrt(string inputPath, string language, MediaSourceInfo mediaSource, string outputPath, CancellationToken cancellationToken)
  295. {
  296. var semaphore = GetLock(outputPath);
  297. await semaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
  298. try
  299. {
  300. if (!File.Exists(outputPath))
  301. {
  302. await ConvertTextSubtitleToSrtInternal(inputPath, language, mediaSource, outputPath, cancellationToken).ConfigureAwait(false);
  303. }
  304. }
  305. finally
  306. {
  307. semaphore.Release();
  308. }
  309. }
  310. /// <summary>
  311. /// Converts the text subtitle to SRT internal.
  312. /// </summary>
  313. /// <param name="inputPath">The input path.</param>
  314. /// <param name="language">The language.</param>
  315. /// <param name="mediaSource">The input mediaSource.</param>
  316. /// <param name="outputPath">The output path.</param>
  317. /// <param name="cancellationToken">The cancellation token.</param>
  318. /// <returns>Task.</returns>
  319. /// <exception cref="ArgumentNullException">
  320. /// The <c>inputPath</c> or <c>outputPath</c> is <c>null</c>.
  321. /// </exception>
  322. private async Task ConvertTextSubtitleToSrtInternal(string inputPath, string language, MediaSourceInfo mediaSource, string outputPath, CancellationToken cancellationToken)
  323. {
  324. if (string.IsNullOrEmpty(inputPath))
  325. {
  326. throw new ArgumentNullException(nameof(inputPath));
  327. }
  328. if (string.IsNullOrEmpty(outputPath))
  329. {
  330. throw new ArgumentNullException(nameof(outputPath));
  331. }
  332. Directory.CreateDirectory(Path.GetDirectoryName(outputPath));
  333. var encodingParam = await GetSubtitleFileCharacterSet(inputPath, language, mediaSource.Protocol, cancellationToken).ConfigureAwait(false);
  334. // FFmpeg automatically convert character encoding when it is UTF-16
  335. // If we specify character encoding, it rejects with "do not specify a character encoding" and "Unable to recode subtitle event"
  336. if ((inputPath.EndsWith(".smi", StringComparison.Ordinal) || inputPath.EndsWith(".sami", StringComparison.Ordinal)) &&
  337. (encodingParam.Equals("UTF-16BE", StringComparison.OrdinalIgnoreCase) ||
  338. encodingParam.Equals("UTF-16LE", StringComparison.OrdinalIgnoreCase)))
  339. {
  340. encodingParam = string.Empty;
  341. }
  342. else if (!string.IsNullOrEmpty(encodingParam))
  343. {
  344. encodingParam = " -sub_charenc " + encodingParam;
  345. }
  346. int exitCode;
  347. using (var process = new Process
  348. {
  349. StartInfo = new ProcessStartInfo
  350. {
  351. CreateNoWindow = true,
  352. UseShellExecute = false,
  353. FileName = _mediaEncoder.EncoderPath,
  354. Arguments = string.Format(CultureInfo.InvariantCulture, "{0} -i \"{1}\" -c:s srt \"{2}\"", encodingParam, inputPath, outputPath),
  355. WindowStyle = ProcessWindowStyle.Hidden,
  356. ErrorDialog = false
  357. },
  358. EnableRaisingEvents = true
  359. })
  360. {
  361. _logger.LogInformation("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments);
  362. try
  363. {
  364. process.Start();
  365. }
  366. catch (Exception ex)
  367. {
  368. _logger.LogError(ex, "Error starting ffmpeg");
  369. throw;
  370. }
  371. var ranToCompletion = await process.WaitForExitAsync(TimeSpan.FromMinutes(5)).ConfigureAwait(false);
  372. if (!ranToCompletion)
  373. {
  374. try
  375. {
  376. _logger.LogInformation("Killing ffmpeg subtitle conversion process");
  377. process.Kill();
  378. }
  379. catch (Exception ex)
  380. {
  381. _logger.LogError(ex, "Error killing subtitle conversion process");
  382. }
  383. }
  384. exitCode = ranToCompletion ? process.ExitCode : -1;
  385. }
  386. var failed = false;
  387. if (exitCode == -1)
  388. {
  389. failed = true;
  390. if (File.Exists(outputPath))
  391. {
  392. try
  393. {
  394. _logger.LogInformation("Deleting converted subtitle due to failure: ", outputPath);
  395. _fileSystem.DeleteFile(outputPath);
  396. }
  397. catch (IOException ex)
  398. {
  399. _logger.LogError(ex, "Error deleting converted subtitle {Path}", outputPath);
  400. }
  401. }
  402. }
  403. else if (!File.Exists(outputPath))
  404. {
  405. failed = true;
  406. }
  407. if (failed)
  408. {
  409. _logger.LogError("ffmpeg subtitle conversion failed for {Path}", inputPath);
  410. throw new Exception(
  411. string.Format(CultureInfo.InvariantCulture, "ffmpeg subtitle conversion failed for {0}", inputPath));
  412. }
  413. await SetAssFont(outputPath, cancellationToken).ConfigureAwait(false);
  414. _logger.LogInformation("ffmpeg subtitle conversion succeeded for {Path}", inputPath);
  415. }
  416. /// <summary>
  417. /// Extracts the text subtitle.
  418. /// </summary>
  419. /// <param name="inputFile">The input file.</param>
  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. string inputFile,
  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(inputFile, 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));
  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 Exception(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 = File.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.Read))
  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(string mediaPath, MediaSourceInfo mediaSource, int subtitleStreamIndex, string outputSubtitleExtension)
  582. {
  583. if (mediaSource.Protocol == MediaProtocol.File)
  584. {
  585. var ticksParam = string.Empty;
  586. var date = _fileSystem.GetLastWriteTimeUtc(mediaPath);
  587. ReadOnlySpan<char> filename = (mediaPath + "_" + 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 = (mediaPath + "_" + 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;
  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 ?? "null", 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 File.OpenRead(path);
  628. default:
  629. throw new ArgumentOutOfRangeException(nameof(protocol));
  630. }
  631. }
  632. private 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; set; }
  642. public MediaProtocol Protocol { get; set; }
  643. public string Format { get; set; }
  644. public bool IsExternal { get; set; }
  645. }
  646. }
  647. }