SubtitleEncoder.cs 28 KB

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