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(ILibraryManager libraryManager,
  37. ILogger logger,
  38. IApplicationPaths appPaths,
  39. IFileSystem fileSystem,
  40. IMediaEncoder mediaEncoder,
  41. IJsonSerializer json,
  42. IHttpClient httpClient,
  43. IMediaSourceManager mediaSourceManager,
  44. IProcessFactory processFactory)
  45. {
  46. _libraryManager = libraryManager;
  47. _logger = logger;
  48. _appPaths = appPaths;
  49. _fileSystem = fileSystem;
  50. _mediaEncoder = mediaEncoder;
  51. _json = json;
  52. _httpClient = httpClient;
  53. _mediaSourceManager = mediaSourceManager;
  54. _processFactory = processFactory;
  55. }
  56. private string SubtitleCachePath => Path.Combine(_appPaths.DataPath, "subtitles");
  57. private Stream ConvertSubtitles(Stream stream,
  58. string inputFormat,
  59. string outputFormat,
  60. long startTimeTicks,
  61. long endTimeTicks,
  62. bool preserveOriginalTimestamps,
  63. CancellationToken cancellationToken)
  64. {
  65. var ms = new MemoryStream();
  66. try
  67. {
  68. var reader = GetReader(inputFormat, true);
  69. var trackInfo = reader.Parse(stream, cancellationToken);
  70. FilterEvents(trackInfo, startTimeTicks, endTimeTicks, preserveOriginalTimestamps);
  71. var writer = GetWriter(outputFormat);
  72. writer.Write(trackInfo, ms, cancellationToken);
  73. ms.Position = 0;
  74. }
  75. catch
  76. {
  77. ms.Dispose();
  78. throw;
  79. }
  80. return ms;
  81. }
  82. private void FilterEvents(SubtitleTrackInfo track, long startPositionTicks, long endTimeTicks, bool preserveTimestamps)
  83. {
  84. // Drop subs that are earlier than what we're looking for
  85. track.TrackEvents = track.TrackEvents
  86. .SkipWhile(i => (i.StartPositionTicks - startPositionTicks) < 0 || (i.EndPositionTicks - startPositionTicks) < 0)
  87. .ToArray();
  88. if (endTimeTicks > 0)
  89. {
  90. track.TrackEvents = track.TrackEvents
  91. .TakeWhile(i => i.StartPositionTicks <= endTimeTicks)
  92. .ToArray();
  93. }
  94. if (!preserveTimestamps)
  95. {
  96. foreach (var trackEvent in track.TrackEvents)
  97. {
  98. trackEvent.EndPositionTicks -= startPositionTicks;
  99. trackEvent.StartPositionTicks -= startPositionTicks;
  100. }
  101. }
  102. }
  103. async Task<Stream> ISubtitleEncoder.GetSubtitles(BaseItem item, string mediaSourceId, int subtitleStreamIndex, string outputFormat, long startTimeTicks, long endTimeTicks, bool preserveOriginalTimestamps, CancellationToken cancellationToken)
  104. {
  105. if (item == null)
  106. {
  107. throw new ArgumentNullException(nameof(item));
  108. }
  109. if (string.IsNullOrWhiteSpace(mediaSourceId))
  110. {
  111. throw new ArgumentNullException(nameof(mediaSourceId));
  112. }
  113. // TODO network path substition useful ?
  114. var mediaSources = await _mediaSourceManager.GetPlayackMediaSources(item, null, true, true, 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 _fileSystem.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 (!_fileSystem.FileExists(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. _fileSystem.CreateDirectory(_fileSystem.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. IsHidden = true,
  374. ErrorDialog = false
  375. });
  376. _logger.LogInformation("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments);
  377. try
  378. {
  379. process.Start();
  380. }
  381. catch (Exception ex)
  382. {
  383. _logger.LogError(ex, "Error starting ffmpeg");
  384. throw;
  385. }
  386. var ranToCompletion = await process.WaitForExitAsync(300000).ConfigureAwait(false);
  387. if (!ranToCompletion)
  388. {
  389. try
  390. {
  391. _logger.LogInformation("Killing ffmpeg subtitle conversion process");
  392. process.Kill();
  393. }
  394. catch (Exception ex)
  395. {
  396. _logger.LogError(ex, "Error killing subtitle conversion process");
  397. }
  398. }
  399. var exitCode = ranToCompletion ? process.ExitCode : -1;
  400. process.Dispose();
  401. var failed = false;
  402. if (exitCode == -1)
  403. {
  404. failed = true;
  405. if (_fileSystem.FileExists(outputPath))
  406. {
  407. try
  408. {
  409. _logger.LogInformation("Deleting converted subtitle due to failure: ", outputPath);
  410. _fileSystem.DeleteFile(outputPath);
  411. }
  412. catch (IOException ex)
  413. {
  414. _logger.LogError(ex, "Error deleting converted subtitle {Path}", outputPath);
  415. }
  416. }
  417. }
  418. else if (!_fileSystem.FileExists(outputPath))
  419. {
  420. failed = true;
  421. }
  422. if (failed)
  423. {
  424. var msg = string.Format("ffmpeg subtitle conversion failed for {Path}", inputPath);
  425. _logger.LogError(msg);
  426. throw new Exception(msg);
  427. }
  428. await SetAssFont(outputPath).ConfigureAwait(false);
  429. _logger.LogInformation("ffmpeg subtitle conversion succeeded for {Path}", inputPath);
  430. }
  431. /// <summary>
  432. /// Extracts the text subtitle.
  433. /// </summary>
  434. /// <param name="inputFiles">The input files.</param>
  435. /// <param name="protocol">The protocol.</param>
  436. /// <param name="subtitleStreamIndex">Index of the subtitle stream.</param>
  437. /// <param name="outputCodec">The output codec.</param>
  438. /// <param name="outputPath">The output path.</param>
  439. /// <param name="cancellationToken">The cancellation token.</param>
  440. /// <returns>Task.</returns>
  441. /// <exception cref="ArgumentException">Must use inputPath list overload</exception>
  442. private async Task ExtractTextSubtitle(
  443. string[] inputFiles,
  444. MediaProtocol protocol,
  445. int subtitleStreamIndex,
  446. string outputCodec,
  447. string outputPath,
  448. CancellationToken cancellationToken)
  449. {
  450. var semaphore = GetLock(outputPath);
  451. await semaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
  452. try
  453. {
  454. if (!_fileSystem.FileExists(outputPath))
  455. {
  456. await ExtractTextSubtitleInternal(_mediaEncoder.GetInputArgument(inputFiles, protocol), subtitleStreamIndex, outputCodec, outputPath, cancellationToken).ConfigureAwait(false);
  457. }
  458. }
  459. finally
  460. {
  461. semaphore.Release();
  462. }
  463. }
  464. private async Task ExtractTextSubtitleInternal(
  465. string inputPath,
  466. int subtitleStreamIndex,
  467. string outputCodec,
  468. string outputPath,
  469. CancellationToken cancellationToken)
  470. {
  471. if (string.IsNullOrEmpty(inputPath))
  472. {
  473. throw new ArgumentNullException(nameof(inputPath));
  474. }
  475. if (string.IsNullOrEmpty(outputPath))
  476. {
  477. throw new ArgumentNullException(nameof(outputPath));
  478. }
  479. _fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(outputPath));
  480. var processArgs = string.Format("-i {0} -map 0:{1} -an -vn -c:s {2} \"{3}\"", inputPath,
  481. subtitleStreamIndex, outputCodec, outputPath);
  482. var process = _processFactory.Create(new ProcessOptions
  483. {
  484. CreateNoWindow = true,
  485. UseShellExecute = false,
  486. FileName = _mediaEncoder.EncoderPath,
  487. Arguments = processArgs,
  488. IsHidden = true,
  489. ErrorDialog = false
  490. });
  491. _logger.LogInformation("{File} {Arguments}", process.StartInfo.FileName, process.StartInfo.Arguments);
  492. try
  493. {
  494. process.Start();
  495. }
  496. catch (Exception ex)
  497. {
  498. _logger.LogError(ex, "Error starting ffmpeg");
  499. throw;
  500. }
  501. var ranToCompletion = await process.WaitForExitAsync(300000).ConfigureAwait(false);
  502. if (!ranToCompletion)
  503. {
  504. try
  505. {
  506. _logger.LogWarning("Killing ffmpeg subtitle extraction process");
  507. process.Kill();
  508. }
  509. catch (Exception ex)
  510. {
  511. _logger.LogError(ex, "Error killing subtitle extraction process");
  512. }
  513. }
  514. var exitCode = ranToCompletion ? process.ExitCode : -1;
  515. process.Dispose();
  516. var failed = false;
  517. if (exitCode == -1)
  518. {
  519. failed = true;
  520. try
  521. {
  522. _logger.LogWarning("Deleting extracted subtitle due to failure: {Path}", outputPath);
  523. _fileSystem.DeleteFile(outputPath);
  524. }
  525. catch (FileNotFoundException)
  526. {
  527. }
  528. catch (IOException ex)
  529. {
  530. _logger.LogError(ex, "Error deleting extracted subtitle {Path}", outputPath);
  531. }
  532. }
  533. else if (!_fileSystem.FileExists(outputPath))
  534. {
  535. failed = true;
  536. }
  537. if (failed)
  538. {
  539. var msg = $"ffmpeg subtitle extraction failed for {inputPath} to {outputPath}";
  540. _logger.LogError(msg);
  541. throw new Exception(msg);
  542. }
  543. else
  544. {
  545. var msg = $"ffmpeg subtitle extraction completed for {inputPath} to {outputPath}";
  546. _logger.LogInformation(msg);
  547. }
  548. if (string.Equals(outputCodec, "ass", StringComparison.OrdinalIgnoreCase))
  549. {
  550. await SetAssFont(outputPath).ConfigureAwait(false);
  551. }
  552. }
  553. /// <summary>
  554. /// Sets the ass font.
  555. /// </summary>
  556. /// <param name="file">The file.</param>
  557. /// <returns>Task.</returns>
  558. private async Task SetAssFont(string file)
  559. {
  560. _logger.LogInformation("Setting ass font within {File}", file);
  561. string text;
  562. Encoding encoding;
  563. using (var fileStream = _fileSystem.OpenRead(file))
  564. using (var reader = new StreamReader(fileStream, true))
  565. {
  566. encoding = reader.CurrentEncoding;
  567. text = await reader.ReadToEndAsync().ConfigureAwait(false);
  568. }
  569. var newText = text.Replace(",Arial,", ",Arial Unicode MS,");
  570. if (!string.Equals(text, newText))
  571. {
  572. using (var fileStream = _fileSystem.GetFileStream(file, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read))
  573. using (var writer = new StreamWriter(fileStream, encoding))
  574. {
  575. writer.Write(newText);
  576. }
  577. }
  578. }
  579. private string GetSubtitleCachePath(string mediaPath, MediaProtocol protocol, int subtitleStreamIndex, string outputSubtitleExtension)
  580. {
  581. if (protocol == MediaProtocol.File)
  582. {
  583. var ticksParam = string.Empty;
  584. var date = _fileSystem.GetLastWriteTimeUtc(mediaPath);
  585. var filename = (mediaPath + "_" + subtitleStreamIndex.ToString(CultureInfo.InvariantCulture) + "_" + date.Ticks.ToString(CultureInfo.InvariantCulture) + ticksParam).GetMD5() + outputSubtitleExtension;
  586. var prefix = filename.Substring(0, 1);
  587. return Path.Combine(SubtitleCachePath, prefix, filename);
  588. }
  589. else
  590. {
  591. var filename = (mediaPath + "_" + subtitleStreamIndex.ToString(CultureInfo.InvariantCulture)).GetMD5() + outputSubtitleExtension;
  592. var prefix = filename.Substring(0, 1);
  593. return Path.Combine(SubtitleCachePath, prefix, filename);
  594. }
  595. }
  596. public async Task<string> GetSubtitleFileCharacterSet(string path, string language, MediaProtocol protocol, CancellationToken cancellationToken)
  597. {
  598. var bytes = await GetBytes(path, protocol, cancellationToken).ConfigureAwait(false);
  599. var charset = CharsetDetector.DetectFromBytes(bytes).Detected?.EncodingName;
  600. _logger.LogDebug("charset {0} detected for {Path}", charset ?? "null", path);
  601. return charset;
  602. }
  603. private async Task<byte[]> GetBytes(string path, MediaProtocol protocol, CancellationToken cancellationToken)
  604. {
  605. if (protocol == MediaProtocol.Http)
  606. {
  607. var opts = new HttpRequestOptions()
  608. {
  609. Url = path,
  610. CancellationToken = cancellationToken
  611. };
  612. using (var file = await _httpClient.Get(opts).ConfigureAwait(false))
  613. using (var memoryStream = new MemoryStream())
  614. {
  615. await file.CopyToAsync(memoryStream).ConfigureAwait(false);
  616. memoryStream.Position = 0;
  617. return memoryStream.ToArray();
  618. }
  619. }
  620. if (protocol == MediaProtocol.File)
  621. {
  622. return _fileSystem.ReadAllBytes(path);
  623. }
  624. throw new ArgumentOutOfRangeException(nameof(protocol));
  625. }
  626. }
  627. }