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