SubtitleEncoder.cs 29 KB

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