SubtitleEncoder.cs 27 KB

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