SubtitleEncoder.cs 33 KB

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