SubtitleEncoder.cs 27 KB

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