2
0

SubtitleEncoder.cs 30 KB

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