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. 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 (_fileSystem.FileExists(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 (!_fileSystem.FileExists(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 (!_fileSystem.FileExists(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. _fileSystem.CreateDirectory(_fileSystem.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. FileName = _mediaEncoder.EncoderPath,
  488. Arguments = processArgs,
  489. IsHidden = true,
  490. ErrorDialog = false
  491. });
  492. _logger.LogInformation("{File} {Arguments}", process.StartInfo.FileName, process.StartInfo.Arguments);
  493. try
  494. {
  495. process.Start();
  496. }
  497. catch (Exception ex)
  498. {
  499. _logger.LogError(ex, "Error starting ffmpeg");
  500. throw;
  501. }
  502. var ranToCompletion = await process.WaitForExitAsync(300000).ConfigureAwait(false);
  503. if (!ranToCompletion)
  504. {
  505. try
  506. {
  507. _logger.LogWarning("Killing ffmpeg subtitle extraction process");
  508. process.Kill();
  509. }
  510. catch (Exception ex)
  511. {
  512. _logger.LogError(ex, "Error killing subtitle extraction process");
  513. }
  514. }
  515. var exitCode = ranToCompletion ? process.ExitCode : -1;
  516. process.Dispose();
  517. var failed = false;
  518. if (exitCode == -1)
  519. {
  520. failed = true;
  521. try
  522. {
  523. _logger.LogWarning("Deleting extracted subtitle due to failure: {Path}", outputPath);
  524. _fileSystem.DeleteFile(outputPath);
  525. }
  526. catch (FileNotFoundException)
  527. {
  528. }
  529. catch (IOException ex)
  530. {
  531. _logger.LogError(ex, "Error deleting extracted subtitle {Path}", outputPath);
  532. }
  533. }
  534. else if (!_fileSystem.FileExists(outputPath))
  535. {
  536. failed = true;
  537. }
  538. if (failed)
  539. {
  540. var msg = $"ffmpeg subtitle extraction failed for {inputPath} to {outputPath}";
  541. _logger.LogError(msg);
  542. throw new Exception(msg);
  543. }
  544. else
  545. {
  546. var msg = $"ffmpeg subtitle extraction completed for {inputPath} to {outputPath}";
  547. _logger.LogInformation(msg);
  548. }
  549. if (string.Equals(outputCodec, "ass", StringComparison.OrdinalIgnoreCase))
  550. {
  551. await SetAssFont(outputPath).ConfigureAwait(false);
  552. }
  553. }
  554. /// <summary>
  555. /// Sets the ass font.
  556. /// </summary>
  557. /// <param name="file">The file.</param>
  558. /// <returns>Task.</returns>
  559. private async Task SetAssFont(string file)
  560. {
  561. _logger.LogInformation("Setting ass font within {File}", file);
  562. string text;
  563. Encoding encoding;
  564. using (var fileStream = _fileSystem.OpenRead(file))
  565. using (var reader = new StreamReader(fileStream, true))
  566. {
  567. encoding = reader.CurrentEncoding;
  568. text = await reader.ReadToEndAsync().ConfigureAwait(false);
  569. }
  570. var newText = text.Replace(",Arial,", ",Arial Unicode MS,");
  571. if (!string.Equals(text, newText))
  572. {
  573. using (var fileStream = _fileSystem.GetFileStream(file, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read))
  574. using (var writer = new StreamWriter(fileStream, encoding))
  575. {
  576. writer.Write(newText);
  577. }
  578. }
  579. }
  580. private string GetSubtitleCachePath(string mediaPath, MediaProtocol protocol, int subtitleStreamIndex, string outputSubtitleExtension)
  581. {
  582. if (protocol == MediaProtocol.File)
  583. {
  584. var ticksParam = string.Empty;
  585. var date = _fileSystem.GetLastWriteTimeUtc(mediaPath);
  586. var filename = (mediaPath + "_" + subtitleStreamIndex.ToString(CultureInfo.InvariantCulture) + "_" + date.Ticks.ToString(CultureInfo.InvariantCulture) + ticksParam).GetMD5() + outputSubtitleExtension;
  587. var prefix = filename.Substring(0, 1);
  588. return Path.Combine(SubtitleCachePath, prefix, filename);
  589. }
  590. else
  591. {
  592. var filename = (mediaPath + "_" + subtitleStreamIndex.ToString(CultureInfo.InvariantCulture)).GetMD5() + outputSubtitleExtension;
  593. var prefix = filename.Substring(0, 1);
  594. return Path.Combine(SubtitleCachePath, prefix, filename);
  595. }
  596. }
  597. public async Task<string> GetSubtitleFileCharacterSet(string path, string language, MediaProtocol protocol, CancellationToken cancellationToken)
  598. {
  599. var bytes = await GetBytes(path, protocol, cancellationToken).ConfigureAwait(false);
  600. var charset = CharsetDetector.DetectFromBytes(bytes).Detected?.EncodingName;
  601. _logger.LogDebug("charset {0} detected for {Path}", charset ?? "null", path);
  602. return charset;
  603. }
  604. private async Task<byte[]> GetBytes(string path, MediaProtocol protocol, CancellationToken cancellationToken)
  605. {
  606. if (protocol == MediaProtocol.Http)
  607. {
  608. var opts = new HttpRequestOptions()
  609. {
  610. Url = path,
  611. CancellationToken = cancellationToken
  612. };
  613. using (var file = await _httpClient.Get(opts).ConfigureAwait(false))
  614. using (var memoryStream = new MemoryStream())
  615. {
  616. await file.CopyToAsync(memoryStream).ConfigureAwait(false);
  617. memoryStream.Position = 0;
  618. return memoryStream.ToArray();
  619. }
  620. }
  621. if (protocol == MediaProtocol.File)
  622. {
  623. return _fileSystem.ReadAllBytes(path);
  624. }
  625. throw new ArgumentOutOfRangeException(nameof(protocol));
  626. }
  627. }
  628. }