SubtitleEncoder.cs 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772
  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 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 (GetReader(currentFormat, false) == null)
  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 ISubtitleParser GetReader(string format, bool throwIfMissing)
  216. {
  217. if (string.IsNullOrEmpty(format))
  218. {
  219. throw new ArgumentNullException(nameof(format));
  220. }
  221. if (string.Equals(format, SubtitleFormat.SRT, StringComparison.OrdinalIgnoreCase))
  222. {
  223. return new SrtParser(_logger);
  224. }
  225. if (string.Equals(format, SubtitleFormat.SSA, StringComparison.OrdinalIgnoreCase))
  226. {
  227. return new SsaParser(_logger);
  228. }
  229. if (string.Equals(format, SubtitleFormat.ASS, StringComparison.OrdinalIgnoreCase))
  230. {
  231. return new AssParser(_logger);
  232. }
  233. if (throwIfMissing)
  234. {
  235. throw new ArgumentException("Unsupported format: " + format);
  236. }
  237. return null;
  238. }
  239. private ISubtitleWriter TryGetWriter(string format)
  240. {
  241. if (string.IsNullOrEmpty(format))
  242. {
  243. throw new ArgumentNullException(nameof(format));
  244. }
  245. if (string.Equals(format, "json", StringComparison.OrdinalIgnoreCase))
  246. {
  247. return new JsonWriter();
  248. }
  249. if (string.Equals(format, SubtitleFormat.SRT, StringComparison.OrdinalIgnoreCase))
  250. {
  251. return new SrtWriter();
  252. }
  253. if (string.Equals(format, SubtitleFormat.VTT, StringComparison.OrdinalIgnoreCase))
  254. {
  255. return new VttWriter();
  256. }
  257. if (string.Equals(format, SubtitleFormat.TTML, StringComparison.OrdinalIgnoreCase))
  258. {
  259. return new TtmlWriter();
  260. }
  261. return null;
  262. }
  263. private ISubtitleWriter GetWriter(string format)
  264. {
  265. var writer = TryGetWriter(format);
  266. if (writer != null)
  267. {
  268. return writer;
  269. }
  270. throw new ArgumentException("Unsupported format: " + format);
  271. }
  272. /// <summary>
  273. /// Gets the lock.
  274. /// </summary>
  275. /// <param name="filename">The filename.</param>
  276. /// <returns>System.Object.</returns>
  277. private SemaphoreSlim GetLock(string filename)
  278. {
  279. return _semaphoreLocks.GetOrAdd(filename, _ => new SemaphoreSlim(1, 1));
  280. }
  281. /// <summary>
  282. /// Converts the text subtitle to SRT.
  283. /// </summary>
  284. /// <param name="inputPath">The input path.</param>
  285. /// <param name="language">The language.</param>
  286. /// <param name="mediaSource">The input mediaSource.</param>
  287. /// <param name="outputPath">The output path.</param>
  288. /// <param name="cancellationToken">The cancellation token.</param>
  289. /// <returns>Task.</returns>
  290. private async Task ConvertTextSubtitleToSrt(string inputPath, string language, MediaSourceInfo mediaSource, string outputPath, CancellationToken cancellationToken)
  291. {
  292. var semaphore = GetLock(outputPath);
  293. await semaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
  294. try
  295. {
  296. if (!File.Exists(outputPath))
  297. {
  298. await ConvertTextSubtitleToSrtInternal(inputPath, language, mediaSource, outputPath, cancellationToken).ConfigureAwait(false);
  299. }
  300. }
  301. finally
  302. {
  303. semaphore.Release();
  304. }
  305. }
  306. /// <summary>
  307. /// Converts the text subtitle to SRT internal.
  308. /// </summary>
  309. /// <param name="inputPath">The input path.</param>
  310. /// <param name="language">The language.</param>
  311. /// <param name="mediaSource">The input mediaSource.</param>
  312. /// <param name="outputPath">The output path.</param>
  313. /// <param name="cancellationToken">The cancellation token.</param>
  314. /// <returns>Task.</returns>
  315. /// <exception cref="ArgumentNullException">
  316. /// The <c>inputPath</c> or <c>outputPath</c> is <c>null</c>.
  317. /// </exception>
  318. private async Task ConvertTextSubtitleToSrtInternal(string inputPath, string language, MediaSourceInfo mediaSource, string outputPath, CancellationToken cancellationToken)
  319. {
  320. if (string.IsNullOrEmpty(inputPath))
  321. {
  322. throw new ArgumentNullException(nameof(inputPath));
  323. }
  324. if (string.IsNullOrEmpty(outputPath))
  325. {
  326. throw new ArgumentNullException(nameof(outputPath));
  327. }
  328. Directory.CreateDirectory(Path.GetDirectoryName(outputPath));
  329. var encodingParam = await GetSubtitleFileCharacterSet(inputPath, language, mediaSource.Protocol, cancellationToken).ConfigureAwait(false);
  330. // FFmpeg automatically convert character encoding when it is UTF-16
  331. // If we specify character encoding, it rejects with "do not specify a character encoding" and "Unable to recode subtitle event"
  332. if ((inputPath.EndsWith(".smi", StringComparison.Ordinal) || inputPath.EndsWith(".sami", StringComparison.Ordinal)) &&
  333. (encodingParam.Equals("UTF-16BE", StringComparison.OrdinalIgnoreCase) ||
  334. encodingParam.Equals("UTF-16LE", StringComparison.OrdinalIgnoreCase)))
  335. {
  336. encodingParam = string.Empty;
  337. }
  338. else if (!string.IsNullOrEmpty(encodingParam))
  339. {
  340. encodingParam = " -sub_charenc " + encodingParam;
  341. }
  342. int exitCode;
  343. using (var process = new Process
  344. {
  345. StartInfo = new ProcessStartInfo
  346. {
  347. CreateNoWindow = true,
  348. UseShellExecute = false,
  349. FileName = _mediaEncoder.EncoderPath,
  350. Arguments = string.Format(CultureInfo.InvariantCulture, "{0} -i \"{1}\" -c:s srt \"{2}\"", encodingParam, inputPath, outputPath),
  351. WindowStyle = ProcessWindowStyle.Hidden,
  352. ErrorDialog = false
  353. },
  354. EnableRaisingEvents = true
  355. })
  356. {
  357. _logger.LogInformation("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments);
  358. try
  359. {
  360. process.Start();
  361. }
  362. catch (Exception ex)
  363. {
  364. _logger.LogError(ex, "Error starting ffmpeg");
  365. throw;
  366. }
  367. var ranToCompletion = await process.WaitForExitAsync(TimeSpan.FromMinutes(5)).ConfigureAwait(false);
  368. if (!ranToCompletion)
  369. {
  370. try
  371. {
  372. _logger.LogInformation("Killing ffmpeg subtitle conversion process");
  373. process.Kill();
  374. }
  375. catch (Exception ex)
  376. {
  377. _logger.LogError(ex, "Error killing subtitle conversion process");
  378. }
  379. }
  380. exitCode = ranToCompletion ? process.ExitCode : -1;
  381. }
  382. var failed = false;
  383. if (exitCode == -1)
  384. {
  385. failed = true;
  386. if (File.Exists(outputPath))
  387. {
  388. try
  389. {
  390. _logger.LogInformation("Deleting converted subtitle due to failure: ", outputPath);
  391. _fileSystem.DeleteFile(outputPath);
  392. }
  393. catch (IOException ex)
  394. {
  395. _logger.LogError(ex, "Error deleting converted subtitle {Path}", outputPath);
  396. }
  397. }
  398. }
  399. else if (!File.Exists(outputPath))
  400. {
  401. failed = true;
  402. }
  403. if (failed)
  404. {
  405. _logger.LogError("ffmpeg subtitle conversion failed for {Path}", inputPath);
  406. throw new Exception(
  407. string.Format(CultureInfo.InvariantCulture, "ffmpeg subtitle conversion failed for {0}", inputPath));
  408. }
  409. await SetAssFont(outputPath, cancellationToken).ConfigureAwait(false);
  410. _logger.LogInformation("ffmpeg subtitle conversion succeeded for {Path}", inputPath);
  411. }
  412. /// <summary>
  413. /// Extracts the text subtitle.
  414. /// </summary>
  415. /// <param name="mediaSource">The mediaSource.</param>
  416. /// <param name="subtitleStreamIndex">Index of the subtitle stream.</param>
  417. /// <param name="outputCodec">The output codec.</param>
  418. /// <param name="outputPath">The output path.</param>
  419. /// <param name="cancellationToken">The cancellation token.</param>
  420. /// <returns>Task.</returns>
  421. /// <exception cref="ArgumentException">Must use inputPath list overload.</exception>
  422. private async Task ExtractTextSubtitle(
  423. MediaSourceInfo mediaSource,
  424. int subtitleStreamIndex,
  425. string outputCodec,
  426. string outputPath,
  427. CancellationToken cancellationToken)
  428. {
  429. var semaphore = GetLock(outputPath);
  430. await semaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
  431. try
  432. {
  433. if (!File.Exists(outputPath))
  434. {
  435. await ExtractTextSubtitleInternal(
  436. _mediaEncoder.GetInputArgument(mediaSource.Path, mediaSource),
  437. subtitleStreamIndex,
  438. outputCodec,
  439. outputPath,
  440. cancellationToken).ConfigureAwait(false);
  441. }
  442. }
  443. finally
  444. {
  445. semaphore.Release();
  446. }
  447. }
  448. private async Task ExtractTextSubtitleInternal(
  449. string inputPath,
  450. int subtitleStreamIndex,
  451. string outputCodec,
  452. string outputPath,
  453. CancellationToken cancellationToken)
  454. {
  455. if (string.IsNullOrEmpty(inputPath))
  456. {
  457. throw new ArgumentNullException(nameof(inputPath));
  458. }
  459. if (string.IsNullOrEmpty(outputPath))
  460. {
  461. throw new ArgumentNullException(nameof(outputPath));
  462. }
  463. Directory.CreateDirectory(Path.GetDirectoryName(outputPath));
  464. var processArgs = string.Format(
  465. CultureInfo.InvariantCulture,
  466. "-i {0} -map 0:{1} -an -vn -c:s {2} \"{3}\"",
  467. inputPath,
  468. subtitleStreamIndex,
  469. outputCodec,
  470. outputPath);
  471. int exitCode;
  472. using (var process = new Process
  473. {
  474. StartInfo = new ProcessStartInfo
  475. {
  476. CreateNoWindow = true,
  477. UseShellExecute = false,
  478. FileName = _mediaEncoder.EncoderPath,
  479. Arguments = processArgs,
  480. WindowStyle = ProcessWindowStyle.Hidden,
  481. ErrorDialog = false
  482. },
  483. EnableRaisingEvents = true
  484. })
  485. {
  486. _logger.LogInformation("{File} {Arguments}", process.StartInfo.FileName, process.StartInfo.Arguments);
  487. try
  488. {
  489. process.Start();
  490. }
  491. catch (Exception ex)
  492. {
  493. _logger.LogError(ex, "Error starting ffmpeg");
  494. throw;
  495. }
  496. var ranToCompletion = await process.WaitForExitAsync(TimeSpan.FromMinutes(5)).ConfigureAwait(false);
  497. if (!ranToCompletion)
  498. {
  499. try
  500. {
  501. _logger.LogWarning("Killing ffmpeg subtitle extraction process");
  502. process.Kill();
  503. }
  504. catch (Exception ex)
  505. {
  506. _logger.LogError(ex, "Error killing subtitle extraction process");
  507. }
  508. }
  509. exitCode = ranToCompletion ? process.ExitCode : -1;
  510. }
  511. var failed = false;
  512. if (exitCode == -1)
  513. {
  514. failed = true;
  515. try
  516. {
  517. _logger.LogWarning("Deleting extracted subtitle due to failure: {Path}", outputPath);
  518. _fileSystem.DeleteFile(outputPath);
  519. }
  520. catch (FileNotFoundException)
  521. {
  522. }
  523. catch (IOException ex)
  524. {
  525. _logger.LogError(ex, "Error deleting extracted subtitle {Path}", outputPath);
  526. }
  527. }
  528. else if (!File.Exists(outputPath))
  529. {
  530. failed = true;
  531. }
  532. if (failed)
  533. {
  534. var msg = $"ffmpeg subtitle extraction failed for {inputPath} to {outputPath}";
  535. _logger.LogError(msg);
  536. throw new Exception(msg);
  537. }
  538. else
  539. {
  540. var msg = $"ffmpeg subtitle extraction completed for {inputPath} to {outputPath}";
  541. _logger.LogInformation(msg);
  542. }
  543. if (string.Equals(outputCodec, "ass", StringComparison.OrdinalIgnoreCase))
  544. {
  545. await SetAssFont(outputPath, cancellationToken).ConfigureAwait(false);
  546. }
  547. }
  548. /// <summary>
  549. /// Sets the ass font.
  550. /// </summary>
  551. /// <param name="file">The file.</param>
  552. /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <c>System.Threading.CancellationToken.None</c>.</param>
  553. /// <returns>Task.</returns>
  554. private async Task SetAssFont(string file, CancellationToken cancellationToken = default)
  555. {
  556. _logger.LogInformation("Setting ass font within {File}", file);
  557. string text;
  558. Encoding encoding;
  559. using (var fileStream = File.OpenRead(file))
  560. using (var reader = new StreamReader(fileStream, true))
  561. {
  562. encoding = reader.CurrentEncoding;
  563. text = await reader.ReadToEndAsync().ConfigureAwait(false);
  564. }
  565. var newText = text.Replace(",Arial,", ",Arial Unicode MS,", StringComparison.Ordinal);
  566. if (!string.Equals(text, newText, StringComparison.Ordinal))
  567. {
  568. // use FileShare.None as this bypasses dotnet bug dotnet/runtime#42790 .
  569. using (var fileStream = new FileStream(file, FileMode.Create, FileAccess.Write, FileShare.None))
  570. using (var writer = new StreamWriter(fileStream, encoding))
  571. {
  572. await writer.WriteAsync(newText.AsMemory(), cancellationToken).ConfigureAwait(false);
  573. }
  574. }
  575. }
  576. private string GetSubtitleCachePath(MediaSourceInfo mediaSource, int subtitleStreamIndex, string outputSubtitleExtension)
  577. {
  578. if (mediaSource.Protocol == MediaProtocol.File)
  579. {
  580. var ticksParam = string.Empty;
  581. var date = _fileSystem.GetLastWriteTimeUtc(mediaSource.Path);
  582. ReadOnlySpan<char> filename = (mediaSource.Path + "_" + subtitleStreamIndex.ToString(CultureInfo.InvariantCulture) + "_" + date.Ticks.ToString(CultureInfo.InvariantCulture) + ticksParam).GetMD5() + outputSubtitleExtension;
  583. var prefix = filename.Slice(0, 1);
  584. return Path.Join(SubtitleCachePath, prefix, filename);
  585. }
  586. else
  587. {
  588. ReadOnlySpan<char> filename = (mediaSource.Path + "_" + subtitleStreamIndex.ToString(CultureInfo.InvariantCulture)).GetMD5() + outputSubtitleExtension;
  589. var prefix = filename.Slice(0, 1);
  590. return Path.Join(SubtitleCachePath, prefix, filename);
  591. }
  592. }
  593. /// <inheritdoc />
  594. public async Task<string> GetSubtitleFileCharacterSet(string path, string language, MediaProtocol protocol, CancellationToken cancellationToken)
  595. {
  596. using (var stream = await GetStream(path, protocol, cancellationToken).ConfigureAwait(false))
  597. {
  598. var charset = CharsetDetector.DetectFromStream(stream).Detected?.EncodingName;
  599. // UTF16 is automatically converted to UTF8 by FFmpeg, do not specify a character encoding
  600. if ((path.EndsWith(".ass", StringComparison.Ordinal) || path.EndsWith(".ssa", StringComparison.Ordinal) || path.EndsWith(".srt", StringComparison.Ordinal))
  601. && (string.Equals(charset, "utf-16le", StringComparison.OrdinalIgnoreCase)
  602. || string.Equals(charset, "utf-16be", StringComparison.OrdinalIgnoreCase)))
  603. {
  604. charset = string.Empty;
  605. }
  606. _logger.LogDebug("charset {0} detected for {Path}", charset ?? "null", path);
  607. return charset;
  608. }
  609. }
  610. private async Task<Stream> GetStream(string path, MediaProtocol protocol, CancellationToken cancellationToken)
  611. {
  612. switch (protocol)
  613. {
  614. case MediaProtocol.Http:
  615. {
  616. using var response = await _httpClientFactory.CreateClient(NamedClient.Default)
  617. .GetAsync(new Uri(path), cancellationToken)
  618. .ConfigureAwait(false);
  619. return await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
  620. }
  621. case MediaProtocol.File:
  622. return File.OpenRead(path);
  623. default:
  624. throw new ArgumentOutOfRangeException(nameof(protocol));
  625. }
  626. }
  627. private struct SubtitleInfo
  628. {
  629. public SubtitleInfo(string path, MediaProtocol protocol, string format, bool isExternal)
  630. {
  631. Path = path;
  632. Protocol = protocol;
  633. Format = format;
  634. IsExternal = isExternal;
  635. }
  636. public string Path { get; set; }
  637. public MediaProtocol Protocol { get; set; }
  638. public string Format { get; set; }
  639. public bool IsExternal { get; set; }
  640. }
  641. }
  642. }