SubtitleEncoder.cs 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738
  1. using MediaBrowser.Common.Configuration;
  2. using MediaBrowser.Common.Extensions;
  3. using MediaBrowser.Common.Net;
  4. using MediaBrowser.Controller.Entities;
  5. using MediaBrowser.Controller.Library;
  6. using MediaBrowser.Controller.MediaEncoding;
  7. using MediaBrowser.Model.Entities;
  8. using MediaBrowser.Model.Logging;
  9. using MediaBrowser.Model.MediaInfo;
  10. using MediaBrowser.Model.Serialization;
  11. using System;
  12. using System.Collections.Concurrent;
  13. using System.Diagnostics;
  14. using System.Globalization;
  15. using System.IO;
  16. using System.Linq;
  17. using System.Text;
  18. using System.Threading;
  19. using System.Threading.Tasks;
  20. using MediaBrowser.Model.IO;
  21. using MediaBrowser.Model.Diagnostics;
  22. using MediaBrowser.Model.Dto;
  23. using MediaBrowser.Model.Text;
  24. namespace MediaBrowser.MediaEncoding.Subtitles
  25. {
  26. public class SubtitleEncoder : ISubtitleEncoder
  27. {
  28. private readonly ILibraryManager _libraryManager;
  29. private readonly ILogger _logger;
  30. private readonly IApplicationPaths _appPaths;
  31. private readonly IFileSystem _fileSystem;
  32. private readonly IMediaEncoder _mediaEncoder;
  33. private readonly IJsonSerializer _json;
  34. private readonly IHttpClient _httpClient;
  35. private readonly IMediaSourceManager _mediaSourceManager;
  36. private readonly IMemoryStreamFactory _memoryStreamProvider;
  37. private readonly IProcessFactory _processFactory;
  38. private readonly ITextEncoding _textEncoding;
  39. public SubtitleEncoder(ILibraryManager libraryManager, ILogger logger, IApplicationPaths appPaths, IFileSystem fileSystem, IMediaEncoder mediaEncoder, IJsonSerializer json, IHttpClient httpClient, IMediaSourceManager mediaSourceManager, IMemoryStreamFactory memoryStreamProvider, IProcessFactory processFactory, ITextEncoding textEncoding)
  40. {
  41. _libraryManager = libraryManager;
  42. _logger = logger;
  43. _appPaths = appPaths;
  44. _fileSystem = fileSystem;
  45. _mediaEncoder = mediaEncoder;
  46. _json = json;
  47. _httpClient = httpClient;
  48. _mediaSourceManager = mediaSourceManager;
  49. _memoryStreamProvider = memoryStreamProvider;
  50. _processFactory = processFactory;
  51. _textEncoding = textEncoding;
  52. }
  53. private string SubtitleCachePath
  54. {
  55. get
  56. {
  57. return Path.Combine(_appPaths.DataPath, "subtitles");
  58. }
  59. }
  60. private Stream ConvertSubtitles(Stream stream,
  61. string inputFormat,
  62. string outputFormat,
  63. long startTimeTicks,
  64. long? endTimeTicks,
  65. bool preserveOriginalTimestamps,
  66. CancellationToken cancellationToken)
  67. {
  68. var ms = _memoryStreamProvider.CreateNew();
  69. try
  70. {
  71. var reader = GetReader(inputFormat, true);
  72. var trackInfo = reader.Parse(stream, cancellationToken);
  73. FilterEvents(trackInfo, startTimeTicks, endTimeTicks, preserveOriginalTimestamps);
  74. var writer = GetWriter(outputFormat);
  75. writer.Write(trackInfo, ms, cancellationToken);
  76. ms.Position = 0;
  77. }
  78. catch
  79. {
  80. ms.Dispose();
  81. throw;
  82. }
  83. return ms;
  84. }
  85. private void FilterEvents(SubtitleTrackInfo track, long startPositionTicks, long? endTimeTicks, bool preserveTimestamps)
  86. {
  87. // Drop subs that are earlier than what we're looking for
  88. track.TrackEvents = track.TrackEvents
  89. .SkipWhile(i => (i.StartPositionTicks - startPositionTicks) < 0 || (i.EndPositionTicks - startPositionTicks) < 0)
  90. .ToList();
  91. if (endTimeTicks.HasValue)
  92. {
  93. var endTime = endTimeTicks.Value;
  94. track.TrackEvents = track.TrackEvents
  95. .TakeWhile(i => i.StartPositionTicks <= endTime)
  96. .ToList();
  97. }
  98. if (!preserveTimestamps)
  99. {
  100. foreach (var trackEvent in track.TrackEvents)
  101. {
  102. trackEvent.EndPositionTicks -= startPositionTicks;
  103. trackEvent.StartPositionTicks -= startPositionTicks;
  104. }
  105. }
  106. }
  107. public async Task<Stream> GetSubtitles(string itemId,
  108. string mediaSourceId,
  109. int subtitleStreamIndex,
  110. string outputFormat,
  111. long startTimeTicks,
  112. long? endTimeTicks,
  113. bool preserveOriginalTimestamps,
  114. CancellationToken cancellationToken)
  115. {
  116. if (string.IsNullOrWhiteSpace(itemId))
  117. {
  118. throw new ArgumentNullException("itemId");
  119. }
  120. if (string.IsNullOrWhiteSpace(mediaSourceId))
  121. {
  122. throw new ArgumentNullException("mediaSourceId");
  123. }
  124. var mediaSources = await _mediaSourceManager.GetPlayackMediaSources(itemId, null, false, new[] { MediaType.Audio, MediaType.Video }, cancellationToken).ConfigureAwait(false);
  125. var mediaSource = mediaSources
  126. .First(i => string.Equals(i.Id, mediaSourceId, StringComparison.OrdinalIgnoreCase));
  127. var subtitleStream = mediaSource.MediaStreams
  128. .First(i => i.Type == MediaStreamType.Subtitle && i.Index == subtitleStreamIndex);
  129. var subtitle = await GetSubtitleStream(mediaSource, subtitleStream, cancellationToken)
  130. .ConfigureAwait(false);
  131. var inputFormat = subtitle.Item2;
  132. var writer = TryGetWriter(outputFormat);
  133. // Return the original if we don't have any way of converting it
  134. if (writer == null)
  135. {
  136. return subtitle.Item1;
  137. }
  138. // Return the original if the same format is being requested
  139. // Character encoding was already handled in GetSubtitleStream
  140. if (string.Equals(inputFormat, outputFormat, StringComparison.OrdinalIgnoreCase))
  141. {
  142. return subtitle.Item1;
  143. }
  144. using (var stream = subtitle.Item1)
  145. {
  146. return ConvertSubtitles(stream, inputFormat, outputFormat, startTimeTicks, endTimeTicks, preserveOriginalTimestamps, cancellationToken);
  147. }
  148. }
  149. private async Task<Tuple<Stream, string>> GetSubtitleStream(MediaSourceInfo mediaSource,
  150. MediaStream subtitleStream,
  151. CancellationToken cancellationToken)
  152. {
  153. var inputFiles = new[] { mediaSource.Path };
  154. if (mediaSource.VideoType.HasValue)
  155. {
  156. if (mediaSource.VideoType.Value == VideoType.BluRay || mediaSource.VideoType.Value == VideoType.Dvd)
  157. {
  158. var mediaSourceItem = (Video)_libraryManager.GetItemById(new Guid(mediaSource.Id));
  159. inputFiles = mediaSourceItem.GetPlayableStreamFiles().ToArray();
  160. }
  161. }
  162. var fileInfo = await GetReadableFile(mediaSource.Path, inputFiles, mediaSource.Protocol, subtitleStream, cancellationToken).ConfigureAwait(false);
  163. var stream = await GetSubtitleStream(fileInfo.Item1, subtitleStream.Language, fileInfo.Item2, fileInfo.Item4, cancellationToken).ConfigureAwait(false);
  164. return new Tuple<Stream, string>(stream, fileInfo.Item3);
  165. }
  166. private async Task<Stream> GetSubtitleStream(string path, string language, MediaProtocol protocol, bool requiresCharset, CancellationToken cancellationToken)
  167. {
  168. if (requiresCharset)
  169. {
  170. var bytes = await GetBytes(path, protocol, cancellationToken).ConfigureAwait(false);
  171. var charset = _textEncoding.GetDetectedEncodingName(bytes, language);
  172. _logger.Debug("charset {0} detected for {1}", charset ?? "null", path);
  173. if (!string.IsNullOrEmpty(charset))
  174. {
  175. using (var inputStream = _memoryStreamProvider.CreateNew(bytes))
  176. {
  177. using (var reader = new StreamReader(inputStream, _textEncoding.GetEncodingFromCharset(charset)))
  178. {
  179. var text = await reader.ReadToEndAsync().ConfigureAwait(false);
  180. bytes = Encoding.UTF8.GetBytes(text);
  181. return _memoryStreamProvider.CreateNew(bytes);
  182. }
  183. }
  184. }
  185. }
  186. return _fileSystem.OpenRead(path);
  187. }
  188. private async Task<Tuple<string, MediaProtocol, string, bool>> GetReadableFile(string mediaPath,
  189. string[] inputFiles,
  190. MediaProtocol protocol,
  191. MediaStream subtitleStream,
  192. CancellationToken cancellationToken)
  193. {
  194. if (!subtitleStream.IsExternal)
  195. {
  196. string outputFormat;
  197. string outputCodec;
  198. if (string.Equals(subtitleStream.Codec, "ass", StringComparison.OrdinalIgnoreCase) ||
  199. string.Equals(subtitleStream.Codec, "ssa", StringComparison.OrdinalIgnoreCase) ||
  200. string.Equals(subtitleStream.Codec, "srt", StringComparison.OrdinalIgnoreCase))
  201. {
  202. // Extract
  203. outputCodec = "copy";
  204. outputFormat = subtitleStream.Codec;
  205. }
  206. else if (string.Equals(subtitleStream.Codec, "subrip", StringComparison.OrdinalIgnoreCase))
  207. {
  208. // Extract
  209. outputCodec = "copy";
  210. outputFormat = "srt";
  211. }
  212. else
  213. {
  214. // Extract
  215. outputCodec = "srt";
  216. outputFormat = "srt";
  217. }
  218. // Extract
  219. var outputPath = GetSubtitleCachePath(mediaPath, protocol, subtitleStream.Index, "." + outputFormat);
  220. await ExtractTextSubtitle(inputFiles, protocol, subtitleStream.Index, outputCodec, outputPath, cancellationToken)
  221. .ConfigureAwait(false);
  222. return new Tuple<string, MediaProtocol, string, bool>(outputPath, MediaProtocol.File, outputFormat, false);
  223. }
  224. var currentFormat = (Path.GetExtension(subtitleStream.Path) ?? subtitleStream.Codec)
  225. .TrimStart('.');
  226. if (GetReader(currentFormat, false) == null)
  227. {
  228. // Convert
  229. var outputPath = GetSubtitleCachePath(mediaPath, protocol, subtitleStream.Index, ".srt");
  230. await ConvertTextSubtitleToSrt(subtitleStream.Path, subtitleStream.Language, protocol, outputPath, cancellationToken).ConfigureAwait(false);
  231. return new Tuple<string, MediaProtocol, string, bool>(outputPath, MediaProtocol.File, "srt", true);
  232. }
  233. return new Tuple<string, MediaProtocol, string, bool>(subtitleStream.Path, protocol, currentFormat, true);
  234. }
  235. private ISubtitleParser GetReader(string format, bool throwIfMissing)
  236. {
  237. if (string.IsNullOrEmpty(format))
  238. {
  239. throw new ArgumentNullException("format");
  240. }
  241. if (string.Equals(format, SubtitleFormat.SRT, StringComparison.OrdinalIgnoreCase))
  242. {
  243. return new SrtParser(_logger);
  244. }
  245. if (string.Equals(format, SubtitleFormat.SSA, StringComparison.OrdinalIgnoreCase))
  246. {
  247. return new SsaParser();
  248. }
  249. if (string.Equals(format, SubtitleFormat.ASS, StringComparison.OrdinalIgnoreCase))
  250. {
  251. return new AssParser();
  252. }
  253. if (throwIfMissing)
  254. {
  255. throw new ArgumentException("Unsupported format: " + format);
  256. }
  257. return null;
  258. }
  259. private ISubtitleWriter TryGetWriter(string format)
  260. {
  261. if (string.IsNullOrEmpty(format))
  262. {
  263. throw new ArgumentNullException("format");
  264. }
  265. if (string.Equals(format, "json", StringComparison.OrdinalIgnoreCase))
  266. {
  267. return new JsonWriter(_json);
  268. }
  269. if (string.Equals(format, SubtitleFormat.SRT, StringComparison.OrdinalIgnoreCase))
  270. {
  271. return new SrtWriter();
  272. }
  273. if (string.Equals(format, SubtitleFormat.VTT, StringComparison.OrdinalIgnoreCase))
  274. {
  275. return new VttWriter();
  276. }
  277. if (string.Equals(format, SubtitleFormat.TTML, StringComparison.OrdinalIgnoreCase))
  278. {
  279. return new TtmlWriter();
  280. }
  281. return null;
  282. }
  283. private ISubtitleWriter GetWriter(string format)
  284. {
  285. var writer = TryGetWriter(format);
  286. if (writer != null)
  287. {
  288. return writer;
  289. }
  290. throw new ArgumentException("Unsupported format: " + format);
  291. }
  292. /// <summary>
  293. /// The _semaphoreLocks
  294. /// </summary>
  295. private readonly ConcurrentDictionary<string, SemaphoreSlim> _semaphoreLocks =
  296. new ConcurrentDictionary<string, SemaphoreSlim>();
  297. /// <summary>
  298. /// Gets the lock.
  299. /// </summary>
  300. /// <param name="filename">The filename.</param>
  301. /// <returns>System.Object.</returns>
  302. private SemaphoreSlim GetLock(string filename)
  303. {
  304. return _semaphoreLocks.GetOrAdd(filename, key => new SemaphoreSlim(1, 1));
  305. }
  306. /// <summary>
  307. /// Converts the text subtitle to SRT.
  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. private async Task ConvertTextSubtitleToSrt(string inputPath, string language, MediaProtocol inputProtocol, string outputPath, CancellationToken cancellationToken)
  315. {
  316. var semaphore = GetLock(outputPath);
  317. await semaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
  318. try
  319. {
  320. if (!_fileSystem.FileExists(outputPath))
  321. {
  322. await ConvertTextSubtitleToSrtInternal(inputPath, language, inputProtocol, outputPath, cancellationToken).ConfigureAwait(false);
  323. }
  324. }
  325. finally
  326. {
  327. semaphore.Release();
  328. }
  329. }
  330. /// <summary>
  331. /// Converts the text subtitle to SRT internal.
  332. /// </summary>
  333. /// <param name="inputPath">The input path.</param>
  334. /// <param name="inputProtocol">The input protocol.</param>
  335. /// <param name="outputPath">The output path.</param>
  336. /// <param name="cancellationToken">The cancellation token.</param>
  337. /// <returns>Task.</returns>
  338. /// <exception cref="System.ArgumentNullException">
  339. /// inputPath
  340. /// or
  341. /// outputPath
  342. /// </exception>
  343. private async Task ConvertTextSubtitleToSrtInternal(string inputPath, string language, MediaProtocol inputProtocol, string outputPath, CancellationToken cancellationToken)
  344. {
  345. if (string.IsNullOrEmpty(inputPath))
  346. {
  347. throw new ArgumentNullException("inputPath");
  348. }
  349. if (string.IsNullOrEmpty(outputPath))
  350. {
  351. throw new ArgumentNullException("outputPath");
  352. }
  353. _fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(outputPath));
  354. var encodingParam = await GetSubtitleFileCharacterSet(inputPath, language, inputProtocol, cancellationToken).ConfigureAwait(false);
  355. if (!string.IsNullOrEmpty(encodingParam))
  356. {
  357. encodingParam = " -sub_charenc " + encodingParam;
  358. }
  359. var process = _processFactory.Create(new ProcessOptions
  360. {
  361. CreateNoWindow = true,
  362. UseShellExecute = false,
  363. FileName = _mediaEncoder.EncoderPath,
  364. Arguments = string.Format("{0} -i \"{1}\" -c:s srt \"{2}\"", encodingParam, inputPath, outputPath),
  365. IsHidden = true,
  366. ErrorDialog = false
  367. });
  368. _logger.Info("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments);
  369. try
  370. {
  371. process.Start();
  372. }
  373. catch (Exception ex)
  374. {
  375. _logger.ErrorException("Error starting ffmpeg", ex);
  376. throw;
  377. }
  378. var ranToCompletion = await process.WaitForExitAsync(300000).ConfigureAwait(false);
  379. if (!ranToCompletion)
  380. {
  381. try
  382. {
  383. _logger.Info("Killing ffmpeg subtitle conversion process");
  384. process.Kill();
  385. }
  386. catch (Exception ex)
  387. {
  388. _logger.ErrorException("Error killing subtitle conversion process", ex);
  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 (_fileSystem.FileExists(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 (!_fileSystem.FileExists(outputPath))
  411. {
  412. failed = true;
  413. }
  414. if (failed)
  415. {
  416. var msg = string.Format("ffmpeg subtitle conversion failed for {0}", inputPath);
  417. _logger.Error(msg);
  418. throw new Exception(msg);
  419. }
  420. await SetAssFont(outputPath).ConfigureAwait(false);
  421. _logger.Info("ffmpeg subtitle conversion succeeded for {0}", inputPath);
  422. }
  423. /// <summary>
  424. /// Extracts the text subtitle.
  425. /// </summary>
  426. /// <param name="inputFiles">The input files.</param>
  427. /// <param name="protocol">The protocol.</param>
  428. /// <param name="subtitleStreamIndex">Index of the subtitle stream.</param>
  429. /// <param name="outputCodec">The output codec.</param>
  430. /// <param name="outputPath">The output path.</param>
  431. /// <param name="cancellationToken">The cancellation token.</param>
  432. /// <returns>Task.</returns>
  433. /// <exception cref="System.ArgumentException">Must use inputPath list overload</exception>
  434. private async Task ExtractTextSubtitle(string[] inputFiles, MediaProtocol protocol, int subtitleStreamIndex,
  435. string outputCodec, string outputPath, CancellationToken cancellationToken)
  436. {
  437. var semaphore = GetLock(outputPath);
  438. await semaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
  439. try
  440. {
  441. if (!_fileSystem.FileExists(outputPath))
  442. {
  443. await ExtractTextSubtitleInternal(_mediaEncoder.GetInputArgument(inputFiles, protocol), subtitleStreamIndex, 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. _fileSystem.CreateDirectory(_fileSystem.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 = _processFactory.Create(new ProcessOptions
  466. {
  467. CreateNoWindow = true,
  468. UseShellExecute = false,
  469. FileName = _mediaEncoder.EncoderPath,
  470. Arguments = processArgs,
  471. IsHidden = true,
  472. ErrorDialog = false
  473. });
  474. _logger.Info("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments);
  475. try
  476. {
  477. process.Start();
  478. }
  479. catch (Exception ex)
  480. {
  481. _logger.ErrorException("Error starting ffmpeg", ex);
  482. throw;
  483. }
  484. var ranToCompletion = await process.WaitForExitAsync(300000).ConfigureAwait(false);
  485. if (!ranToCompletion)
  486. {
  487. try
  488. {
  489. _logger.Info("Killing ffmpeg subtitle extraction process");
  490. process.Kill();
  491. }
  492. catch (Exception ex)
  493. {
  494. _logger.ErrorException("Error killing subtitle extraction process", ex);
  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. _fileSystem.DeleteFile(outputPath);
  507. }
  508. catch (FileNotFoundException)
  509. {
  510. }
  511. catch (IOException ex)
  512. {
  513. _logger.ErrorException("Error deleting extracted subtitle {0}", ex, outputPath);
  514. }
  515. }
  516. else if (!_fileSystem.FileExists(outputPath))
  517. {
  518. failed = true;
  519. }
  520. if (failed)
  521. {
  522. var msg = string.Format("ffmpeg subtitle extraction failed for {0} to {1}", inputPath, outputPath);
  523. _logger.Error(msg);
  524. throw new Exception(msg);
  525. }
  526. else
  527. {
  528. var msg = string.Format("ffmpeg subtitle extraction completed for {0} to {1}", inputPath, outputPath);
  529. _logger.Info(msg);
  530. }
  531. if (string.Equals(outputCodec, "ass", StringComparison.OrdinalIgnoreCase))
  532. {
  533. await SetAssFont(outputPath).ConfigureAwait(false);
  534. }
  535. }
  536. /// <summary>
  537. /// Sets the ass font.
  538. /// </summary>
  539. /// <param name="file">The file.</param>
  540. /// <returns>Task.</returns>
  541. private async Task SetAssFont(string file)
  542. {
  543. _logger.Info("Setting ass font within {0}", file);
  544. string text;
  545. Encoding encoding;
  546. using (var fileStream = _fileSystem.OpenRead(file))
  547. {
  548. using (var reader = new StreamReader(fileStream, true))
  549. {
  550. encoding = reader.CurrentEncoding;
  551. text = await reader.ReadToEndAsync().ConfigureAwait(false);
  552. }
  553. }
  554. var newText = text.Replace(",Arial,", ",Arial Unicode MS,");
  555. if (!string.Equals(text, newText))
  556. {
  557. using (var fileStream = _fileSystem.GetFileStream(file, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read))
  558. {
  559. using (var writer = new StreamWriter(fileStream, encoding))
  560. {
  561. writer.Write(newText);
  562. }
  563. }
  564. }
  565. }
  566. private string GetSubtitleCachePath(string mediaPath, MediaProtocol protocol, int subtitleStreamIndex, string outputSubtitleExtension)
  567. {
  568. if (protocol == MediaProtocol.File)
  569. {
  570. var ticksParam = string.Empty;
  571. var date = _fileSystem.GetLastWriteTimeUtc(mediaPath);
  572. var filename = (mediaPath + "_" + subtitleStreamIndex.ToString(CultureInfo.InvariantCulture) + "_" + date.Ticks.ToString(CultureInfo.InvariantCulture) + ticksParam).GetMD5() + outputSubtitleExtension;
  573. var prefix = filename.Substring(0, 1);
  574. return Path.Combine(SubtitleCachePath, prefix, filename);
  575. }
  576. else
  577. {
  578. var filename = (mediaPath + "_" + subtitleStreamIndex.ToString(CultureInfo.InvariantCulture)).GetMD5() + outputSubtitleExtension;
  579. var prefix = filename.Substring(0, 1);
  580. return Path.Combine(SubtitleCachePath, prefix, filename);
  581. }
  582. }
  583. public async Task<string> GetSubtitleFileCharacterSet(string path, string language, MediaProtocol protocol, CancellationToken cancellationToken)
  584. {
  585. var bytes = await GetBytes(path, protocol, cancellationToken).ConfigureAwait(false);
  586. var charset = _textEncoding.GetDetectedEncodingName(bytes, language);
  587. _logger.Debug("charset {0} detected for {1}", charset ?? "null", path);
  588. return charset;
  589. }
  590. private async Task<byte[]> GetBytes(string path, MediaProtocol protocol, CancellationToken cancellationToken)
  591. {
  592. if (protocol == MediaProtocol.Http)
  593. {
  594. using (var file = await _httpClient.Get(path, cancellationToken).ConfigureAwait(false))
  595. {
  596. using (var memoryStream = new MemoryStream())
  597. {
  598. await file.CopyToAsync(memoryStream).ConfigureAwait(false);
  599. memoryStream.Position = 0;
  600. return memoryStream.ToArray();
  601. }
  602. }
  603. }
  604. if (protocol == MediaProtocol.File)
  605. {
  606. return _fileSystem.ReadAllBytes(path);
  607. }
  608. throw new ArgumentOutOfRangeException("protocol");
  609. }
  610. }
  611. }