SubtitleEncoder.cs 30 KB

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