SubtitleEncoder.cs 30 KB

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