SubtitleEncoder.cs 30 KB

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