SubtitleEncoder.cs 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786
  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")) &&
  357. (encodingParam.Equals("UTF-16BE", StringComparison.OrdinalIgnoreCase) ||
  358. encodingParam.Equals("UTF-16LE", StringComparison.OrdinalIgnoreCase)))
  359. {
  360. encodingParam = "";
  361. }
  362. else if (!string.IsNullOrEmpty(encodingParam))
  363. {
  364. encodingParam = " -sub_charenc " + encodingParam;
  365. }
  366. int exitCode;
  367. using (var process = new Process
  368. {
  369. StartInfo = new ProcessStartInfo
  370. {
  371. CreateNoWindow = true,
  372. UseShellExecute = false,
  373. FileName = _mediaEncoder.EncoderPath,
  374. Arguments = string.Format("{0} -i \"{1}\" -c:s srt \"{2}\"", encodingParam, inputPath, outputPath),
  375. WindowStyle = ProcessWindowStyle.Hidden,
  376. ErrorDialog = false
  377. },
  378. EnableRaisingEvents = true
  379. })
  380. {
  381. _logger.LogInformation("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments);
  382. try
  383. {
  384. process.Start();
  385. }
  386. catch (Exception ex)
  387. {
  388. _logger.LogError(ex, "Error starting ffmpeg");
  389. throw;
  390. }
  391. var ranToCompletion = await process.WaitForExitAsync(TimeSpan.FromMinutes(5)).ConfigureAwait(false);
  392. if (!ranToCompletion)
  393. {
  394. try
  395. {
  396. _logger.LogInformation("Killing ffmpeg subtitle conversion process");
  397. process.Kill();
  398. }
  399. catch (Exception ex)
  400. {
  401. _logger.LogError(ex, "Error killing subtitle conversion process");
  402. }
  403. }
  404. exitCode = ranToCompletion ? process.ExitCode : -1;
  405. }
  406. var failed = false;
  407. if (exitCode == -1)
  408. {
  409. failed = true;
  410. if (File.Exists(outputPath))
  411. {
  412. try
  413. {
  414. _logger.LogInformation("Deleting converted subtitle due to failure: ", outputPath);
  415. _fileSystem.DeleteFile(outputPath);
  416. }
  417. catch (IOException ex)
  418. {
  419. _logger.LogError(ex, "Error deleting converted subtitle {Path}", outputPath);
  420. }
  421. }
  422. }
  423. else if (!File.Exists(outputPath))
  424. {
  425. failed = true;
  426. }
  427. if (failed)
  428. {
  429. _logger.LogError("ffmpeg subtitle conversion failed for {Path}", inputPath);
  430. throw new Exception(
  431. string.Format(CultureInfo.InvariantCulture, "ffmpeg subtitle conversion failed for {0}", inputPath));
  432. }
  433. await SetAssFont(outputPath).ConfigureAwait(false);
  434. _logger.LogInformation("ffmpeg subtitle conversion succeeded for {Path}", inputPath);
  435. }
  436. /// <summary>
  437. /// Extracts the text subtitle.
  438. /// </summary>
  439. /// <param name="inputFiles">The input files.</param>
  440. /// <param name="protocol">The protocol.</param>
  441. /// <param name="subtitleStreamIndex">Index of the subtitle stream.</param>
  442. /// <param name="outputCodec">The output codec.</param>
  443. /// <param name="outputPath">The output path.</param>
  444. /// <param name="cancellationToken">The cancellation token.</param>
  445. /// <returns>Task.</returns>
  446. /// <exception cref="ArgumentException">Must use inputPath list overload</exception>
  447. private async Task ExtractTextSubtitle(
  448. string[] inputFiles,
  449. MediaProtocol protocol,
  450. int subtitleStreamIndex,
  451. string outputCodec,
  452. string outputPath,
  453. CancellationToken cancellationToken)
  454. {
  455. var semaphore = GetLock(outputPath);
  456. await semaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
  457. try
  458. {
  459. if (!File.Exists(outputPath))
  460. {
  461. await ExtractTextSubtitleInternal(
  462. _mediaEncoder.GetInputArgument(inputFiles, protocol),
  463. subtitleStreamIndex,
  464. outputCodec,
  465. outputPath,
  466. cancellationToken).ConfigureAwait(false);
  467. }
  468. }
  469. finally
  470. {
  471. semaphore.Release();
  472. }
  473. }
  474. private async Task ExtractTextSubtitleInternal(
  475. string inputPath,
  476. int subtitleStreamIndex,
  477. string outputCodec,
  478. string outputPath,
  479. CancellationToken cancellationToken)
  480. {
  481. if (string.IsNullOrEmpty(inputPath))
  482. {
  483. throw new ArgumentNullException(nameof(inputPath));
  484. }
  485. if (string.IsNullOrEmpty(outputPath))
  486. {
  487. throw new ArgumentNullException(nameof(outputPath));
  488. }
  489. Directory.CreateDirectory(Path.GetDirectoryName(outputPath));
  490. var processArgs = string.Format(
  491. CultureInfo.InvariantCulture,
  492. "-i {0} -map 0:{1} -an -vn -c:s {2} \"{3}\"",
  493. inputPath,
  494. subtitleStreamIndex,
  495. outputCodec,
  496. outputPath);
  497. int exitCode;
  498. using (var process = new Process
  499. {
  500. StartInfo = new ProcessStartInfo
  501. {
  502. CreateNoWindow = true,
  503. UseShellExecute = false,
  504. FileName = _mediaEncoder.EncoderPath,
  505. Arguments = processArgs,
  506. WindowStyle = ProcessWindowStyle.Hidden,
  507. ErrorDialog = false
  508. },
  509. EnableRaisingEvents = true
  510. })
  511. {
  512. _logger.LogInformation("{File} {Arguments}", process.StartInfo.FileName, process.StartInfo.Arguments);
  513. try
  514. {
  515. process.Start();
  516. }
  517. catch (Exception ex)
  518. {
  519. _logger.LogError(ex, "Error starting ffmpeg");
  520. throw;
  521. }
  522. var ranToCompletion = await process.WaitForExitAsync(TimeSpan.FromMinutes(5)).ConfigureAwait(false);
  523. if (!ranToCompletion)
  524. {
  525. try
  526. {
  527. _logger.LogWarning("Killing ffmpeg subtitle extraction process");
  528. process.Kill();
  529. }
  530. catch (Exception ex)
  531. {
  532. _logger.LogError(ex, "Error killing subtitle extraction process");
  533. }
  534. }
  535. exitCode = ranToCompletion ? process.ExitCode : -1;
  536. }
  537. var failed = false;
  538. if (exitCode == -1)
  539. {
  540. failed = true;
  541. try
  542. {
  543. _logger.LogWarning("Deleting extracted subtitle due to failure: {Path}", outputPath);
  544. _fileSystem.DeleteFile(outputPath);
  545. }
  546. catch (FileNotFoundException)
  547. {
  548. }
  549. catch (IOException ex)
  550. {
  551. _logger.LogError(ex, "Error deleting extracted subtitle {Path}", outputPath);
  552. }
  553. }
  554. else if (!File.Exists(outputPath))
  555. {
  556. failed = true;
  557. }
  558. if (failed)
  559. {
  560. var msg = $"ffmpeg subtitle extraction failed for {inputPath} to {outputPath}";
  561. _logger.LogError(msg);
  562. throw new Exception(msg);
  563. }
  564. else
  565. {
  566. var msg = $"ffmpeg subtitle extraction completed for {inputPath} to {outputPath}";
  567. _logger.LogInformation(msg);
  568. }
  569. if (string.Equals(outputCodec, "ass", StringComparison.OrdinalIgnoreCase))
  570. {
  571. await SetAssFont(outputPath).ConfigureAwait(false);
  572. }
  573. }
  574. /// <summary>
  575. /// Sets the ass font.
  576. /// </summary>
  577. /// <param name="file">The file.</param>
  578. /// <returns>Task.</returns>
  579. private async Task SetAssFont(string file)
  580. {
  581. _logger.LogInformation("Setting ass font within {File}", file);
  582. string text;
  583. Encoding encoding;
  584. using (var fileStream = File.OpenRead(file))
  585. using (var reader = new StreamReader(fileStream, true))
  586. {
  587. encoding = reader.CurrentEncoding;
  588. text = await reader.ReadToEndAsync().ConfigureAwait(false);
  589. }
  590. var newText = text.Replace(",Arial,", ",Arial Unicode MS,");
  591. if (!string.Equals(text, newText))
  592. {
  593. using (var fileStream = new FileStream(file, FileMode.Create, FileAccess.Write, FileShare.Read))
  594. using (var writer = new StreamWriter(fileStream, encoding))
  595. {
  596. writer.Write(newText);
  597. }
  598. }
  599. }
  600. private string GetSubtitleCachePath(string mediaPath, MediaProtocol protocol, int subtitleStreamIndex, string outputSubtitleExtension)
  601. {
  602. if (protocol == MediaProtocol.File)
  603. {
  604. var ticksParam = string.Empty;
  605. var date = _fileSystem.GetLastWriteTimeUtc(mediaPath);
  606. var filename = (mediaPath + "_" + subtitleStreamIndex.ToString(CultureInfo.InvariantCulture) + "_" + date.Ticks.ToString(CultureInfo.InvariantCulture) + ticksParam).GetMD5() + outputSubtitleExtension;
  607. var prefix = filename.Substring(0, 1);
  608. return Path.Combine(SubtitleCachePath, prefix, filename);
  609. }
  610. else
  611. {
  612. var filename = (mediaPath + "_" + subtitleStreamIndex.ToString(CultureInfo.InvariantCulture)).GetMD5() + outputSubtitleExtension;
  613. var prefix = filename.Substring(0, 1);
  614. return Path.Combine(SubtitleCachePath, prefix, filename);
  615. }
  616. }
  617. /// <inheritdoc />
  618. public async Task<string> GetSubtitleFileCharacterSet(string path, string language, MediaProtocol protocol, CancellationToken cancellationToken)
  619. {
  620. using (var stream = await GetStream(path, protocol, cancellationToken).ConfigureAwait(false))
  621. {
  622. var charset = CharsetDetector.DetectFromStream(stream).Detected?.EncodingName;
  623. // UTF16 is automatically converted to UTF8 by FFmpeg, do not specify a character encoding
  624. if ((path.EndsWith(".ass") || path.EndsWith(".ssa") || path.EndsWith(".srt"))
  625. && (string.Equals(charset, "utf-16le", StringComparison.OrdinalIgnoreCase)
  626. || string.Equals(charset, "utf-16be", StringComparison.OrdinalIgnoreCase)))
  627. {
  628. charset = "";
  629. }
  630. _logger.LogDebug("charset {0} detected for {Path}", charset ?? "null", path);
  631. return charset;
  632. }
  633. }
  634. private Task<Stream> GetStream(string path, MediaProtocol protocol, CancellationToken cancellationToken)
  635. {
  636. switch (protocol)
  637. {
  638. case MediaProtocol.Http:
  639. var opts = new HttpRequestOptions()
  640. {
  641. Url = path,
  642. CancellationToken = cancellationToken,
  643. // Needed for seeking
  644. BufferContent = true
  645. };
  646. return _httpClient.Get(opts);
  647. case MediaProtocol.File:
  648. return Task.FromResult<Stream>(File.OpenRead(path));
  649. default:
  650. throw new ArgumentOutOfRangeException(nameof(protocol));
  651. }
  652. }
  653. }
  654. }