SubtitleEncoder.cs 30 KB

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