SubtitleEncoder.cs 28 KB

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