SubtitleEncoder.cs 28 KB

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