SubtitleEncoder.cs 30 KB

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