SubtitleEncoder.cs 27 KB

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