SubtitleEncoder.cs 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852
  1. using MediaBrowser.Common.Configuration;
  2. using MediaBrowser.Common.Extensions;
  3. using MediaBrowser.Common.Net;
  4. using MediaBrowser.Controller.Entities;
  5. using MediaBrowser.Controller.Library;
  6. using MediaBrowser.Controller.MediaEncoding;
  7. using MediaBrowser.Model.Entities;
  8. using MediaBrowser.Model.Logging;
  9. using MediaBrowser.Model.MediaInfo;
  10. using MediaBrowser.Model.Serialization;
  11. using System;
  12. using System.Collections.Concurrent;
  13. using System.Diagnostics;
  14. using System.Globalization;
  15. using System.IO;
  16. using System.Linq;
  17. using System.Text;
  18. using System.Threading;
  19. using System.Threading.Tasks;
  20. using MediaBrowser.Model.IO;
  21. using MediaBrowser.Model.Diagnostics;
  22. using MediaBrowser.Model.Dto;
  23. using MediaBrowser.Model.Text;
  24. using UniversalDetector;
  25. namespace MediaBrowser.MediaEncoding.Subtitles
  26. {
  27. public class SubtitleEncoder : ISubtitleEncoder
  28. {
  29. private readonly ILibraryManager _libraryManager;
  30. private readonly ILogger _logger;
  31. private readonly IApplicationPaths _appPaths;
  32. private readonly IFileSystem _fileSystem;
  33. private readonly IMediaEncoder _mediaEncoder;
  34. private readonly IJsonSerializer _json;
  35. private readonly IHttpClient _httpClient;
  36. private readonly IMediaSourceManager _mediaSourceManager;
  37. private readonly IMemoryStreamFactory _memoryStreamProvider;
  38. private readonly IProcessFactory _processFactory;
  39. private readonly ITextEncoding _textEncoding;
  40. public SubtitleEncoder(ILibraryManager libraryManager, ILogger logger, IApplicationPaths appPaths, IFileSystem fileSystem, IMediaEncoder mediaEncoder, IJsonSerializer json, IHttpClient httpClient, IMediaSourceManager mediaSourceManager, IMemoryStreamFactory memoryStreamProvider, IProcessFactory processFactory, ITextEncoding textEncoding)
  41. {
  42. _libraryManager = libraryManager;
  43. _logger = logger;
  44. _appPaths = appPaths;
  45. _fileSystem = fileSystem;
  46. _mediaEncoder = mediaEncoder;
  47. _json = json;
  48. _httpClient = httpClient;
  49. _mediaSourceManager = mediaSourceManager;
  50. _memoryStreamProvider = memoryStreamProvider;
  51. _processFactory = processFactory;
  52. _textEncoding = textEncoding;
  53. }
  54. private string SubtitleCachePath
  55. {
  56. get
  57. {
  58. return Path.Combine(_appPaths.DataPath, "subtitles");
  59. }
  60. }
  61. private async Task<Stream> ConvertSubtitles(Stream stream,
  62. string inputFormat,
  63. string outputFormat,
  64. long startTimeTicks,
  65. long? endTimeTicks,
  66. bool preserveOriginalTimestamps,
  67. CancellationToken cancellationToken)
  68. {
  69. var ms = _memoryStreamProvider.CreateNew();
  70. try
  71. {
  72. var reader = GetReader(inputFormat, true);
  73. var trackInfo = reader.Parse(stream, cancellationToken);
  74. FilterEvents(trackInfo, startTimeTicks, endTimeTicks, preserveOriginalTimestamps);
  75. var writer = GetWriter(outputFormat);
  76. writer.Write(trackInfo, ms, cancellationToken);
  77. ms.Position = 0;
  78. }
  79. catch
  80. {
  81. ms.Dispose();
  82. throw;
  83. }
  84. return ms;
  85. }
  86. private void FilterEvents(SubtitleTrackInfo track, long startPositionTicks, long? endTimeTicks, bool preserveTimestamps)
  87. {
  88. // Drop subs that are earlier than what we're looking for
  89. track.TrackEvents = track.TrackEvents
  90. .SkipWhile(i => (i.StartPositionTicks - startPositionTicks) < 0 || (i.EndPositionTicks - startPositionTicks) < 0)
  91. .ToList();
  92. if (endTimeTicks.HasValue)
  93. {
  94. var endTime = endTimeTicks.Value;
  95. track.TrackEvents = track.TrackEvents
  96. .TakeWhile(i => i.StartPositionTicks <= endTime)
  97. .ToList();
  98. }
  99. if (!preserveTimestamps)
  100. {
  101. foreach (var trackEvent in track.TrackEvents)
  102. {
  103. trackEvent.EndPositionTicks -= startPositionTicks;
  104. trackEvent.StartPositionTicks -= startPositionTicks;
  105. }
  106. }
  107. }
  108. public async Task<Stream> GetSubtitles(string itemId,
  109. string mediaSourceId,
  110. int subtitleStreamIndex,
  111. string outputFormat,
  112. long startTimeTicks,
  113. long? endTimeTicks,
  114. bool preserveOriginalTimestamps,
  115. CancellationToken cancellationToken)
  116. {
  117. if (string.IsNullOrWhiteSpace(itemId))
  118. {
  119. throw new ArgumentNullException("itemId");
  120. }
  121. if (string.IsNullOrWhiteSpace(mediaSourceId))
  122. {
  123. throw new ArgumentNullException("mediaSourceId");
  124. }
  125. var mediaSources = await _mediaSourceManager.GetPlayackMediaSources(itemId, null, false, new[] { MediaType.Audio, MediaType.Video }, cancellationToken).ConfigureAwait(false);
  126. var mediaSource = mediaSources
  127. .First(i => string.Equals(i.Id, mediaSourceId, StringComparison.OrdinalIgnoreCase));
  128. var subtitleStream = mediaSource.MediaStreams
  129. .First(i => i.Type == MediaStreamType.Subtitle && i.Index == subtitleStreamIndex);
  130. var subtitle = await GetSubtitleStream(mediaSource, subtitleStream, cancellationToken)
  131. .ConfigureAwait(false);
  132. var inputFormat = subtitle.Item2;
  133. var writer = TryGetWriter(outputFormat);
  134. // Return the original if we don't have any way of converting it
  135. if (writer == null)
  136. {
  137. return subtitle.Item1;
  138. }
  139. // Return the original if the same format is being requested
  140. // Character encoding was already handled in GetSubtitleStream
  141. if (string.Equals(inputFormat, outputFormat, StringComparison.OrdinalIgnoreCase))
  142. {
  143. return subtitle.Item1;
  144. }
  145. using (var stream = subtitle.Item1)
  146. {
  147. return await ConvertSubtitles(stream, inputFormat, outputFormat, startTimeTicks, endTimeTicks, preserveOriginalTimestamps, cancellationToken).ConfigureAwait(false);
  148. }
  149. }
  150. private async Task<Tuple<Stream, string>> GetSubtitleStream(MediaSourceInfo mediaSource,
  151. MediaStream subtitleStream,
  152. CancellationToken cancellationToken)
  153. {
  154. var inputFiles = new[] { mediaSource.Path };
  155. if (mediaSource.VideoType.HasValue)
  156. {
  157. if (mediaSource.VideoType.Value == VideoType.BluRay || mediaSource.VideoType.Value == VideoType.Dvd)
  158. {
  159. var mediaSourceItem = (Video)_libraryManager.GetItemById(new Guid(mediaSource.Id));
  160. inputFiles = mediaSourceItem.GetPlayableStreamFiles().ToArray();
  161. }
  162. }
  163. var fileInfo = await GetReadableFile(mediaSource.Path, inputFiles, mediaSource.Protocol, subtitleStream, cancellationToken).ConfigureAwait(false);
  164. var stream = await GetSubtitleStream(fileInfo.Item1, subtitleStream.Language, fileInfo.Item2, fileInfo.Item4, cancellationToken).ConfigureAwait(false);
  165. return new Tuple<Stream, string>(stream, fileInfo.Item3);
  166. }
  167. private async Task<Stream> GetSubtitleStream(string path, string language, MediaProtocol protocol, bool requiresCharset, CancellationToken cancellationToken)
  168. {
  169. if (requiresCharset)
  170. {
  171. var charset = await GetSubtitleFileCharacterSet(path, language, protocol, cancellationToken).ConfigureAwait(false);
  172. if (!string.IsNullOrEmpty(charset))
  173. {
  174. using (var fs = await GetStream(path, protocol, cancellationToken).ConfigureAwait(false))
  175. {
  176. using (var reader = new StreamReader(fs, GetEncoding(charset)))
  177. {
  178. var text = await reader.ReadToEndAsync().ConfigureAwait(false);
  179. var bytes = Encoding.UTF8.GetBytes(text);
  180. return _memoryStreamProvider.CreateNew(bytes);
  181. }
  182. }
  183. }
  184. }
  185. return _fileSystem.OpenRead(path);
  186. }
  187. private Encoding GetEncoding(string charset)
  188. {
  189. if (string.IsNullOrWhiteSpace(charset))
  190. {
  191. throw new ArgumentNullException("charset");
  192. }
  193. _logger.Debug("Getting encoding object for character set: {0}", charset);
  194. try
  195. {
  196. return Encoding.GetEncoding(charset);
  197. }
  198. catch (ArgumentException)
  199. {
  200. charset = charset.Replace("-", string.Empty);
  201. _logger.Debug("Getting encoding object for character set: {0}", charset);
  202. return Encoding.GetEncoding(charset);
  203. }
  204. }
  205. private async Task<Tuple<string, MediaProtocol, string, bool>> GetReadableFile(string mediaPath,
  206. string[] inputFiles,
  207. MediaProtocol protocol,
  208. MediaStream subtitleStream,
  209. CancellationToken cancellationToken)
  210. {
  211. if (!subtitleStream.IsExternal)
  212. {
  213. string outputFormat;
  214. string outputCodec;
  215. if (string.Equals(subtitleStream.Codec, "ass", StringComparison.OrdinalIgnoreCase) ||
  216. string.Equals(subtitleStream.Codec, "ssa", StringComparison.OrdinalIgnoreCase) ||
  217. string.Equals(subtitleStream.Codec, "srt", StringComparison.OrdinalIgnoreCase))
  218. {
  219. // Extract
  220. outputCodec = "copy";
  221. outputFormat = subtitleStream.Codec;
  222. }
  223. else if (string.Equals(subtitleStream.Codec, "subrip", StringComparison.OrdinalIgnoreCase))
  224. {
  225. // Extract
  226. outputCodec = "copy";
  227. outputFormat = "srt";
  228. }
  229. else
  230. {
  231. // Extract
  232. outputCodec = "srt";
  233. outputFormat = "srt";
  234. }
  235. // Extract
  236. var outputPath = GetSubtitleCachePath(mediaPath, protocol, subtitleStream.Index, "." + outputFormat);
  237. await ExtractTextSubtitle(inputFiles, protocol, subtitleStream.Index, outputCodec, outputPath, cancellationToken)
  238. .ConfigureAwait(false);
  239. return new Tuple<string, MediaProtocol, string, bool>(outputPath, MediaProtocol.File, outputFormat, false);
  240. }
  241. var currentFormat = (Path.GetExtension(subtitleStream.Path) ?? subtitleStream.Codec)
  242. .TrimStart('.');
  243. if (GetReader(currentFormat, false) == null)
  244. {
  245. // Convert
  246. var outputPath = GetSubtitleCachePath(mediaPath, protocol, subtitleStream.Index, ".srt");
  247. await ConvertTextSubtitleToSrt(subtitleStream.Path, subtitleStream.Language, protocol, outputPath, cancellationToken).ConfigureAwait(false);
  248. return new Tuple<string, MediaProtocol, string, bool>(outputPath, MediaProtocol.File, "srt", true);
  249. }
  250. return new Tuple<string, MediaProtocol, string, bool>(subtitleStream.Path, protocol, currentFormat, true);
  251. }
  252. private ISubtitleParser GetReader(string format, bool throwIfMissing)
  253. {
  254. if (string.IsNullOrEmpty(format))
  255. {
  256. throw new ArgumentNullException("format");
  257. }
  258. if (string.Equals(format, SubtitleFormat.SRT, StringComparison.OrdinalIgnoreCase))
  259. {
  260. return new SrtParser(_logger);
  261. }
  262. if (string.Equals(format, SubtitleFormat.SSA, StringComparison.OrdinalIgnoreCase))
  263. {
  264. return new SsaParser();
  265. }
  266. if (string.Equals(format, SubtitleFormat.ASS, StringComparison.OrdinalIgnoreCase))
  267. {
  268. return new AssParser();
  269. }
  270. if (throwIfMissing)
  271. {
  272. throw new ArgumentException("Unsupported format: " + format);
  273. }
  274. return null;
  275. }
  276. private ISubtitleWriter TryGetWriter(string format)
  277. {
  278. if (string.IsNullOrEmpty(format))
  279. {
  280. throw new ArgumentNullException("format");
  281. }
  282. if (string.Equals(format, "json", StringComparison.OrdinalIgnoreCase))
  283. {
  284. return new JsonWriter(_json);
  285. }
  286. if (string.Equals(format, SubtitleFormat.SRT, StringComparison.OrdinalIgnoreCase))
  287. {
  288. return new SrtWriter();
  289. }
  290. if (string.Equals(format, SubtitleFormat.VTT, StringComparison.OrdinalIgnoreCase))
  291. {
  292. return new VttWriter();
  293. }
  294. if (string.Equals(format, SubtitleFormat.TTML, StringComparison.OrdinalIgnoreCase))
  295. {
  296. return new TtmlWriter();
  297. }
  298. return null;
  299. }
  300. private ISubtitleWriter GetWriter(string format)
  301. {
  302. var writer = TryGetWriter(format);
  303. if (writer != null)
  304. {
  305. return writer;
  306. }
  307. throw new ArgumentException("Unsupported format: " + format);
  308. }
  309. /// <summary>
  310. /// The _semaphoreLocks
  311. /// </summary>
  312. private readonly ConcurrentDictionary<string, SemaphoreSlim> _semaphoreLocks =
  313. new ConcurrentDictionary<string, SemaphoreSlim>();
  314. /// <summary>
  315. /// Gets the lock.
  316. /// </summary>
  317. /// <param name="filename">The filename.</param>
  318. /// <returns>System.Object.</returns>
  319. private SemaphoreSlim GetLock(string filename)
  320. {
  321. return _semaphoreLocks.GetOrAdd(filename, key => new SemaphoreSlim(1, 1));
  322. }
  323. /// <summary>
  324. /// Converts the text subtitle to SRT.
  325. /// </summary>
  326. /// <param name="inputPath">The input path.</param>
  327. /// <param name="inputProtocol">The input protocol.</param>
  328. /// <param name="outputPath">The output path.</param>
  329. /// <param name="cancellationToken">The cancellation token.</param>
  330. /// <returns>Task.</returns>
  331. private async Task ConvertTextSubtitleToSrt(string inputPath, string language, MediaProtocol inputProtocol, string outputPath, CancellationToken cancellationToken)
  332. {
  333. var semaphore = GetLock(outputPath);
  334. await semaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
  335. try
  336. {
  337. if (!_fileSystem.FileExists(outputPath))
  338. {
  339. await ConvertTextSubtitleToSrtInternal(inputPath, language, inputProtocol, outputPath, cancellationToken).ConfigureAwait(false);
  340. }
  341. }
  342. finally
  343. {
  344. semaphore.Release();
  345. }
  346. }
  347. /// <summary>
  348. /// Converts the text subtitle to SRT internal.
  349. /// </summary>
  350. /// <param name="inputPath">The input path.</param>
  351. /// <param name="inputProtocol">The input protocol.</param>
  352. /// <param name="outputPath">The output path.</param>
  353. /// <param name="cancellationToken">The cancellation token.</param>
  354. /// <returns>Task.</returns>
  355. /// <exception cref="System.ArgumentNullException">
  356. /// inputPath
  357. /// or
  358. /// outputPath
  359. /// </exception>
  360. private async Task ConvertTextSubtitleToSrtInternal(string inputPath, string language, MediaProtocol inputProtocol, string outputPath, CancellationToken cancellationToken)
  361. {
  362. if (string.IsNullOrEmpty(inputPath))
  363. {
  364. throw new ArgumentNullException("inputPath");
  365. }
  366. if (string.IsNullOrEmpty(outputPath))
  367. {
  368. throw new ArgumentNullException("outputPath");
  369. }
  370. _fileSystem.CreateDirectory(Path.GetDirectoryName(outputPath));
  371. var encodingParam = await GetSubtitleFileCharacterSet(inputPath, language, inputProtocol, cancellationToken).ConfigureAwait(false);
  372. if (!string.IsNullOrEmpty(encodingParam))
  373. {
  374. encodingParam = " -sub_charenc " + encodingParam;
  375. }
  376. var process = _processFactory.Create(new ProcessOptions
  377. {
  378. CreateNoWindow = true,
  379. UseShellExecute = false,
  380. FileName = _mediaEncoder.EncoderPath,
  381. Arguments = string.Format("{0} -i \"{1}\" -c:s srt \"{2}\"", encodingParam, inputPath, outputPath),
  382. IsHidden = true,
  383. ErrorDialog = false
  384. });
  385. _logger.Info("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments);
  386. try
  387. {
  388. process.Start();
  389. }
  390. catch (Exception ex)
  391. {
  392. _logger.ErrorException("Error starting ffmpeg", ex);
  393. throw;
  394. }
  395. var ranToCompletion = process.WaitForExit(60000);
  396. if (!ranToCompletion)
  397. {
  398. try
  399. {
  400. _logger.Info("Killing ffmpeg subtitle conversion process");
  401. process.Kill();
  402. }
  403. catch (Exception ex)
  404. {
  405. _logger.ErrorException("Error killing subtitle conversion process", ex);
  406. }
  407. }
  408. var exitCode = ranToCompletion ? process.ExitCode : -1;
  409. process.Dispose();
  410. var failed = false;
  411. if (exitCode == -1)
  412. {
  413. failed = true;
  414. if (_fileSystem.FileExists(outputPath))
  415. {
  416. try
  417. {
  418. _logger.Info("Deleting converted subtitle due to failure: ", outputPath);
  419. _fileSystem.DeleteFile(outputPath);
  420. }
  421. catch (IOException ex)
  422. {
  423. _logger.ErrorException("Error deleting converted subtitle {0}", ex, outputPath);
  424. }
  425. }
  426. }
  427. else if (!_fileSystem.FileExists(outputPath))
  428. {
  429. failed = true;
  430. }
  431. if (failed)
  432. {
  433. var msg = string.Format("ffmpeg subtitle conversion failed for {0}", inputPath);
  434. _logger.Error(msg);
  435. throw new Exception(msg);
  436. }
  437. await SetAssFont(outputPath).ConfigureAwait(false);
  438. _logger.Info("ffmpeg subtitle conversion succeeded for {0}", inputPath);
  439. }
  440. /// <summary>
  441. /// Extracts the text subtitle.
  442. /// </summary>
  443. /// <param name="inputFiles">The input files.</param>
  444. /// <param name="protocol">The protocol.</param>
  445. /// <param name="subtitleStreamIndex">Index of the subtitle stream.</param>
  446. /// <param name="outputCodec">The output codec.</param>
  447. /// <param name="outputPath">The output path.</param>
  448. /// <param name="cancellationToken">The cancellation token.</param>
  449. /// <returns>Task.</returns>
  450. /// <exception cref="System.ArgumentException">Must use inputPath list overload</exception>
  451. private async Task ExtractTextSubtitle(string[] inputFiles, MediaProtocol protocol, int subtitleStreamIndex,
  452. string outputCodec, string outputPath, CancellationToken cancellationToken)
  453. {
  454. var semaphore = GetLock(outputPath);
  455. await semaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
  456. try
  457. {
  458. if (!_fileSystem.FileExists(outputPath))
  459. {
  460. await ExtractTextSubtitleInternal(_mediaEncoder.GetInputArgument(inputFiles, protocol), subtitleStreamIndex,
  461. outputCodec, outputPath, cancellationToken).ConfigureAwait(false);
  462. }
  463. }
  464. finally
  465. {
  466. semaphore.Release();
  467. }
  468. }
  469. private async Task ExtractTextSubtitleInternal(string inputPath, int subtitleStreamIndex,
  470. string outputCodec, string outputPath, CancellationToken cancellationToken)
  471. {
  472. if (string.IsNullOrEmpty(inputPath))
  473. {
  474. throw new ArgumentNullException("inputPath");
  475. }
  476. if (string.IsNullOrEmpty(outputPath))
  477. {
  478. throw new ArgumentNullException("outputPath");
  479. }
  480. _fileSystem.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. FileName = _mediaEncoder.EncoderPath,
  488. Arguments = processArgs,
  489. IsHidden = true,
  490. ErrorDialog = false
  491. });
  492. _logger.Info("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments);
  493. try
  494. {
  495. process.Start();
  496. }
  497. catch (Exception ex)
  498. {
  499. _logger.ErrorException("Error starting ffmpeg", ex);
  500. throw;
  501. }
  502. var ranToCompletion = process.WaitForExit(300000);
  503. if (!ranToCompletion)
  504. {
  505. try
  506. {
  507. _logger.Info("Killing ffmpeg subtitle extraction process");
  508. process.Kill();
  509. }
  510. catch (Exception ex)
  511. {
  512. _logger.ErrorException("Error killing subtitle extraction process", ex);
  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.Info("Deleting extracted subtitle due to failure: {0}", outputPath);
  524. _fileSystem.DeleteFile(outputPath);
  525. }
  526. catch (FileNotFoundException)
  527. {
  528. }
  529. catch (IOException ex)
  530. {
  531. _logger.ErrorException("Error deleting extracted subtitle {0}", ex, outputPath);
  532. }
  533. }
  534. else if (!_fileSystem.FileExists(outputPath))
  535. {
  536. failed = true;
  537. }
  538. if (failed)
  539. {
  540. var msg = string.Format("ffmpeg subtitle extraction failed for {0} to {1}", inputPath, outputPath);
  541. _logger.Error(msg);
  542. throw new Exception(msg);
  543. }
  544. else
  545. {
  546. var msg = string.Format("ffmpeg subtitle extraction completed for {0} to {1}", inputPath, outputPath);
  547. _logger.Info(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.Info("Setting ass font within {0}", file);
  562. string text;
  563. Encoding encoding;
  564. using (var fileStream = _fileSystem.OpenRead(file))
  565. {
  566. using (var reader = new StreamReader(fileStream, true))
  567. {
  568. encoding = reader.CurrentEncoding;
  569. text = await reader.ReadToEndAsync().ConfigureAwait(false);
  570. }
  571. }
  572. var newText = text.Replace(",Arial,", ",Arial Unicode MS,");
  573. if (!string.Equals(text, newText))
  574. {
  575. using (var fileStream = _fileSystem.GetFileStream(file, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read))
  576. {
  577. using (var writer = new StreamWriter(fileStream, encoding))
  578. {
  579. writer.Write(newText);
  580. }
  581. }
  582. }
  583. }
  584. private string GetSubtitleCachePath(string mediaPath, MediaProtocol protocol, int subtitleStreamIndex, string outputSubtitleExtension)
  585. {
  586. if (protocol == MediaProtocol.File)
  587. {
  588. var ticksParam = string.Empty;
  589. var date = _fileSystem.GetLastWriteTimeUtc(mediaPath);
  590. var filename = (mediaPath + "_" + subtitleStreamIndex.ToString(CultureInfo.InvariantCulture) + "_" + date.Ticks.ToString(CultureInfo.InvariantCulture) + ticksParam).GetMD5() + outputSubtitleExtension;
  591. var prefix = filename.Substring(0, 1);
  592. return Path.Combine(SubtitleCachePath, prefix, filename);
  593. }
  594. else
  595. {
  596. var filename = (mediaPath + "_" + subtitleStreamIndex.ToString(CultureInfo.InvariantCulture)).GetMD5() + outputSubtitleExtension;
  597. var prefix = filename.Substring(0, 1);
  598. return Path.Combine(SubtitleCachePath, prefix, filename);
  599. }
  600. }
  601. public async Task<string> GetSubtitleFileCharacterSet(string path, string language, MediaProtocol protocol, CancellationToken cancellationToken)
  602. {
  603. if (protocol == MediaProtocol.File)
  604. {
  605. var fileEncoding = _textEncoding.GetFileEncoding(path);
  606. if (fileEncoding != null && fileEncoding.Equals(Encoding.UTF8))
  607. {
  608. return string.Empty;
  609. }
  610. }
  611. var charset = await DetectCharset(path, language, protocol, cancellationToken).ConfigureAwait(false);
  612. if (!string.IsNullOrWhiteSpace(charset))
  613. {
  614. if (string.Equals(charset, "utf-8", StringComparison.OrdinalIgnoreCase))
  615. {
  616. return null;
  617. }
  618. return charset;
  619. }
  620. if (!string.IsNullOrWhiteSpace(language))
  621. {
  622. return GetSubtitleFileCharacterSetFromLanguage(language);
  623. }
  624. return null;
  625. }
  626. public string GetSubtitleFileCharacterSetFromLanguage(string language)
  627. {
  628. // https://developer.xamarin.com/api/type/System.Text.Encoding/
  629. switch (language.ToLower())
  630. {
  631. case "hun":
  632. return "windows-1252";
  633. case "pol":
  634. case "cze":
  635. case "ces":
  636. case "slo":
  637. case "slk":
  638. case "slv":
  639. case "srp":
  640. case "hrv":
  641. case "rum":
  642. case "ron":
  643. case "rup":
  644. case "alb":
  645. case "sqi":
  646. return "windows-1250";
  647. case "ara":
  648. return "windows-1256";
  649. case "heb":
  650. return "windows-1255";
  651. case "grc":
  652. case "gre":
  653. return "windows-1253";
  654. case "crh":
  655. case "ota":
  656. case "tur":
  657. return "windows-1254";
  658. case "rus":
  659. return "windows-1251";
  660. case "vie":
  661. return "windows-1258";
  662. case "kor":
  663. return "cp949";
  664. default:
  665. return "windows-1252";
  666. }
  667. }
  668. private async Task<string> DetectCharset(string path, string language, MediaProtocol protocol, CancellationToken cancellationToken)
  669. {
  670. try
  671. {
  672. using (var file = await GetStream(path, protocol, cancellationToken).ConfigureAwait(false))
  673. {
  674. var detector = new CharsetDetector();
  675. detector.Feed(file);
  676. detector.DataEnd();
  677. var charset = detector.Charset;
  678. if (!string.IsNullOrWhiteSpace(charset))
  679. {
  680. _logger.Info("UniversalDetector detected charset {0} for {1}", charset, path);
  681. }
  682. // This is often incorrectly indetected. If this happens, try to use other techniques instead
  683. if (string.Equals("x-mac-cyrillic", charset, StringComparison.OrdinalIgnoreCase))
  684. {
  685. if (!string.IsNullOrWhiteSpace(language))
  686. {
  687. return null;
  688. }
  689. }
  690. return charset;
  691. }
  692. }
  693. catch (IOException ex)
  694. {
  695. _logger.ErrorException("Error attempting to determine subtitle charset from {0}", ex, path);
  696. }
  697. return null;
  698. }
  699. private async Task<Stream> GetStream(string path, MediaProtocol protocol, CancellationToken cancellationToken)
  700. {
  701. if (protocol == MediaProtocol.Http)
  702. {
  703. return await _httpClient.Get(path, cancellationToken).ConfigureAwait(false);
  704. }
  705. if (protocol == MediaProtocol.File)
  706. {
  707. return _fileSystem.GetFileStream(path, FileOpenMode.Open, FileAccessMode.Read, FileShareMode.ReadWrite);
  708. }
  709. throw new ArgumentOutOfRangeException("protocol");
  710. }
  711. }
  712. }