SubtitleEncoder.cs 28 KB

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