SubtitleEncoder.cs 28 KB

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