2
0

SubtitleEncoder.cs 31 KB

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