SubtitleEncoder.cs 30 KB

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