SubtitleEncoder.cs 28 KB

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