SubtitleEncoder.cs 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941
  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 CommonIO;
  21. using MediaBrowser.Common.IO;
  22. using MediaBrowser.Controller.IO;
  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 IMemoryStreamProvider _memoryStreamProvider;
  37. public SubtitleEncoder(ILibraryManager libraryManager, ILogger logger, IApplicationPaths appPaths, IFileSystem fileSystem, IMediaEncoder mediaEncoder, IJsonSerializer json, IHttpClient httpClient, IMediaSourceManager mediaSourceManager, IMemoryStreamProvider memoryStreamProvider)
  38. {
  39. _libraryManager = libraryManager;
  40. _logger = logger;
  41. _appPaths = appPaths;
  42. _fileSystem = fileSystem;
  43. _mediaEncoder = mediaEncoder;
  44. _json = json;
  45. _httpClient = httpClient;
  46. _mediaSourceManager = mediaSourceManager;
  47. _memoryStreamProvider = memoryStreamProvider;
  48. }
  49. private string SubtitleCachePath
  50. {
  51. get
  52. {
  53. return Path.Combine(_appPaths.DataPath, "subtitles");
  54. }
  55. }
  56. private async Task<Stream> ConvertSubtitles(Stream stream,
  57. string inputFormat,
  58. string outputFormat,
  59. long startTimeTicks,
  60. long? endTimeTicks,
  61. bool preserveOriginalTimestamps,
  62. CancellationToken cancellationToken)
  63. {
  64. var ms = _memoryStreamProvider.CreateNew();
  65. try
  66. {
  67. var reader = GetReader(inputFormat, true);
  68. var trackInfo = reader.Parse(stream, cancellationToken);
  69. FilterEvents(trackInfo, startTimeTicks, endTimeTicks, preserveOriginalTimestamps);
  70. var writer = GetWriter(outputFormat);
  71. writer.Write(trackInfo, ms, cancellationToken);
  72. ms.Position = 0;
  73. }
  74. catch
  75. {
  76. ms.Dispose();
  77. throw;
  78. }
  79. return ms;
  80. }
  81. private void FilterEvents(SubtitleTrackInfo track, long startPositionTicks, long? endTimeTicks, bool preserveTimestamps)
  82. {
  83. // Drop subs that are earlier than what we're looking for
  84. track.TrackEvents = track.TrackEvents
  85. .SkipWhile(i => (i.StartPositionTicks - startPositionTicks) < 0 || (i.EndPositionTicks - startPositionTicks) < 0)
  86. .ToList();
  87. if (endTimeTicks.HasValue)
  88. {
  89. var endTime = endTimeTicks.Value;
  90. track.TrackEvents = track.TrackEvents
  91. .TakeWhile(i => i.StartPositionTicks <= endTime)
  92. .ToList();
  93. }
  94. if (!preserveTimestamps)
  95. {
  96. foreach (var trackEvent in track.TrackEvents)
  97. {
  98. trackEvent.EndPositionTicks -= startPositionTicks;
  99. trackEvent.StartPositionTicks -= startPositionTicks;
  100. }
  101. }
  102. }
  103. public async Task<Stream> GetSubtitles(string itemId,
  104. string mediaSourceId,
  105. int subtitleStreamIndex,
  106. string outputFormat,
  107. long startTimeTicks,
  108. long? endTimeTicks,
  109. bool preserveOriginalTimestamps,
  110. CancellationToken cancellationToken)
  111. {
  112. if (string.IsNullOrWhiteSpace(itemId))
  113. {
  114. throw new ArgumentNullException("itemId");
  115. }
  116. if (string.IsNullOrWhiteSpace(mediaSourceId))
  117. {
  118. throw new ArgumentNullException("mediaSourceId");
  119. }
  120. var subtitle = await GetSubtitleStream(itemId, mediaSourceId, subtitleStreamIndex, cancellationToken)
  121. .ConfigureAwait(false);
  122. var inputFormat = subtitle.Item2;
  123. if (string.Equals(inputFormat, outputFormat, StringComparison.OrdinalIgnoreCase) && TryGetWriter(outputFormat) == null)
  124. {
  125. return subtitle.Item1;
  126. }
  127. using (var stream = subtitle.Item1)
  128. {
  129. return await ConvertSubtitles(stream, inputFormat, outputFormat, startTimeTicks, endTimeTicks, preserveOriginalTimestamps, cancellationToken).ConfigureAwait(false);
  130. }
  131. }
  132. private async Task<Tuple<Stream, string>> GetSubtitleStream(string itemId,
  133. string mediaSourceId,
  134. int subtitleStreamIndex,
  135. CancellationToken cancellationToken)
  136. {
  137. if (string.IsNullOrWhiteSpace(itemId))
  138. {
  139. throw new ArgumentNullException("itemId");
  140. }
  141. if (string.IsNullOrWhiteSpace(mediaSourceId))
  142. {
  143. throw new ArgumentNullException("mediaSourceId");
  144. }
  145. var mediaSources = await _mediaSourceManager.GetPlayackMediaSources(itemId, null, false, new[] { MediaType.Audio, MediaType.Video }, cancellationToken).ConfigureAwait(false);
  146. var mediaSource = mediaSources
  147. .First(i => string.Equals(i.Id, mediaSourceId, StringComparison.OrdinalIgnoreCase));
  148. var subtitleStream = mediaSource.MediaStreams
  149. .First(i => i.Type == MediaStreamType.Subtitle && i.Index == subtitleStreamIndex);
  150. var inputFiles = new[] { mediaSource.Path };
  151. if (mediaSource.VideoType.HasValue)
  152. {
  153. if (mediaSource.VideoType.Value == VideoType.BluRay ||
  154. mediaSource.VideoType.Value == VideoType.Dvd)
  155. {
  156. var mediaSourceItem = (Video)_libraryManager.GetItemById(new Guid(mediaSourceId));
  157. inputFiles = mediaSourceItem.GetPlayableStreamFiles().ToArray();
  158. }
  159. }
  160. var fileInfo = await GetReadableFile(mediaSource.Path, inputFiles, mediaSource.Protocol, subtitleStream, cancellationToken).ConfigureAwait(false);
  161. var stream = await GetSubtitleStream(fileInfo.Item1, subtitleStream.Language, fileInfo.Item2, fileInfo.Item4, cancellationToken).ConfigureAwait(false);
  162. return new Tuple<Stream, string>(stream, fileInfo.Item3);
  163. }
  164. private async Task<Stream> GetSubtitleStream(string path, string language, MediaProtocol protocol, bool requiresCharset, CancellationToken cancellationToken)
  165. {
  166. if (requiresCharset)
  167. {
  168. var charset = await GetSubtitleFileCharacterSet(path, language, protocol, cancellationToken).ConfigureAwait(false);
  169. if (!string.IsNullOrEmpty(charset))
  170. {
  171. using (var fs = await GetStream(path, protocol, cancellationToken).ConfigureAwait(false))
  172. {
  173. using (var reader = new StreamReader(fs, GetEncoding(charset)))
  174. {
  175. var text = await reader.ReadToEndAsync().ConfigureAwait(false);
  176. var bytes = Encoding.UTF8.GetBytes(text);
  177. return _memoryStreamProvider.CreateNew(bytes);
  178. }
  179. }
  180. }
  181. }
  182. return _fileSystem.OpenRead(path);
  183. }
  184. private Encoding GetEncoding(string charset)
  185. {
  186. if (string.IsNullOrWhiteSpace(charset))
  187. {
  188. throw new ArgumentNullException("charset");
  189. }
  190. _logger.Debug("Getting encoding object for character set: {0}", charset);
  191. try
  192. {
  193. return Encoding.GetEncoding(charset);
  194. }
  195. catch (ArgumentException)
  196. {
  197. charset = charset.Replace("-", string.Empty);
  198. _logger.Debug("Getting encoding object for character set: {0}", charset);
  199. return Encoding.GetEncoding(charset);
  200. }
  201. }
  202. private async Task<Tuple<string, MediaProtocol, string, bool>> GetReadableFile(string mediaPath,
  203. string[] inputFiles,
  204. MediaProtocol protocol,
  205. MediaStream subtitleStream,
  206. CancellationToken cancellationToken)
  207. {
  208. if (!subtitleStream.IsExternal)
  209. {
  210. string outputFormat;
  211. string outputCodec;
  212. if (string.Equals(subtitleStream.Codec, "ass", StringComparison.OrdinalIgnoreCase) ||
  213. string.Equals(subtitleStream.Codec, "ssa", StringComparison.OrdinalIgnoreCase) ||
  214. string.Equals(subtitleStream.Codec, "srt", StringComparison.OrdinalIgnoreCase))
  215. {
  216. // Extract
  217. outputCodec = "copy";
  218. outputFormat = subtitleStream.Codec;
  219. }
  220. else if (string.Equals(subtitleStream.Codec, "subrip", StringComparison.OrdinalIgnoreCase))
  221. {
  222. // Extract
  223. outputCodec = "copy";
  224. outputFormat = "srt";
  225. }
  226. else
  227. {
  228. // Extract
  229. outputCodec = "srt";
  230. outputFormat = "srt";
  231. }
  232. // Extract
  233. var outputPath = GetSubtitleCachePath(mediaPath, protocol, subtitleStream.Index, "." + outputFormat);
  234. await ExtractTextSubtitle(inputFiles, protocol, subtitleStream.Index, outputCodec, outputPath, cancellationToken)
  235. .ConfigureAwait(false);
  236. return new Tuple<string, MediaProtocol, string, bool>(outputPath, MediaProtocol.File, outputFormat, false);
  237. }
  238. var currentFormat = (Path.GetExtension(subtitleStream.Path) ?? subtitleStream.Codec)
  239. .TrimStart('.');
  240. if (GetReader(currentFormat, false) == null)
  241. {
  242. // Convert
  243. var outputPath = GetSubtitleCachePath(mediaPath, protocol, subtitleStream.Index, ".srt");
  244. await ConvertTextSubtitleToSrt(subtitleStream.Path, subtitleStream.Language, protocol, outputPath, cancellationToken).ConfigureAwait(false);
  245. return new Tuple<string, MediaProtocol, string, bool>(outputPath, MediaProtocol.File, "srt", true);
  246. }
  247. return new Tuple<string, MediaProtocol, string, bool>(subtitleStream.Path, protocol, currentFormat, true);
  248. }
  249. private ISubtitleParser GetReader(string format, bool throwIfMissing)
  250. {
  251. if (string.IsNullOrEmpty(format))
  252. {
  253. throw new ArgumentNullException("format");
  254. }
  255. if (string.Equals(format, SubtitleFormat.SRT, StringComparison.OrdinalIgnoreCase))
  256. {
  257. return new SrtParser(_logger);
  258. }
  259. if (string.Equals(format, SubtitleFormat.SSA, StringComparison.OrdinalIgnoreCase))
  260. {
  261. return new SsaParser();
  262. }
  263. if (string.Equals(format, SubtitleFormat.ASS, StringComparison.OrdinalIgnoreCase))
  264. {
  265. return new AssParser();
  266. }
  267. if (throwIfMissing)
  268. {
  269. throw new ArgumentException("Unsupported format: " + format);
  270. }
  271. return null;
  272. }
  273. private ISubtitleWriter TryGetWriter(string format)
  274. {
  275. if (string.IsNullOrEmpty(format))
  276. {
  277. throw new ArgumentNullException("format");
  278. }
  279. if (string.Equals(format, "json", StringComparison.OrdinalIgnoreCase))
  280. {
  281. return new JsonWriter(_json);
  282. }
  283. if (string.Equals(format, SubtitleFormat.SRT, StringComparison.OrdinalIgnoreCase))
  284. {
  285. return new SrtWriter();
  286. }
  287. if (string.Equals(format, SubtitleFormat.VTT, StringComparison.OrdinalIgnoreCase))
  288. {
  289. return new VttWriter();
  290. }
  291. if (string.Equals(format, SubtitleFormat.TTML, StringComparison.OrdinalIgnoreCase))
  292. {
  293. return new TtmlWriter();
  294. }
  295. return null;
  296. }
  297. private ISubtitleWriter GetWriter(string format)
  298. {
  299. var writer = TryGetWriter(format);
  300. if (writer != null)
  301. {
  302. return writer;
  303. }
  304. throw new ArgumentException("Unsupported format: " + format);
  305. }
  306. /// <summary>
  307. /// The _semaphoreLocks
  308. /// </summary>
  309. private readonly ConcurrentDictionary<string, SemaphoreSlim> _semaphoreLocks =
  310. new ConcurrentDictionary<string, SemaphoreSlim>();
  311. /// <summary>
  312. /// Gets the lock.
  313. /// </summary>
  314. /// <param name="filename">The filename.</param>
  315. /// <returns>System.Object.</returns>
  316. private SemaphoreSlim GetLock(string filename)
  317. {
  318. return _semaphoreLocks.GetOrAdd(filename, key => new SemaphoreSlim(1, 1));
  319. }
  320. /// <summary>
  321. /// Converts the text subtitle to SRT.
  322. /// </summary>
  323. /// <param name="inputPath">The input path.</param>
  324. /// <param name="inputProtocol">The input protocol.</param>
  325. /// <param name="outputPath">The output path.</param>
  326. /// <param name="cancellationToken">The cancellation token.</param>
  327. /// <returns>Task.</returns>
  328. private async Task ConvertTextSubtitleToSrt(string inputPath, string language, MediaProtocol inputProtocol, string outputPath, CancellationToken cancellationToken)
  329. {
  330. var semaphore = GetLock(outputPath);
  331. await semaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
  332. try
  333. {
  334. if (!_fileSystem.FileExists(outputPath))
  335. {
  336. await ConvertTextSubtitleToSrtInternal(inputPath, language, inputProtocol, outputPath, cancellationToken).ConfigureAwait(false);
  337. }
  338. }
  339. finally
  340. {
  341. semaphore.Release();
  342. }
  343. }
  344. /// <summary>
  345. /// Converts the text subtitle to SRT internal.
  346. /// </summary>
  347. /// <param name="inputPath">The input path.</param>
  348. /// <param name="inputProtocol">The input protocol.</param>
  349. /// <param name="outputPath">The output path.</param>
  350. /// <param name="cancellationToken">The cancellation token.</param>
  351. /// <returns>Task.</returns>
  352. /// <exception cref="System.ArgumentNullException">
  353. /// inputPath
  354. /// or
  355. /// outputPath
  356. /// </exception>
  357. /// <exception cref="System.ApplicationException"></exception>
  358. private async Task ConvertTextSubtitleToSrtInternal(string inputPath, string language, MediaProtocol inputProtocol, string outputPath, CancellationToken cancellationToken)
  359. {
  360. if (string.IsNullOrEmpty(inputPath))
  361. {
  362. throw new ArgumentNullException("inputPath");
  363. }
  364. if (string.IsNullOrEmpty(outputPath))
  365. {
  366. throw new ArgumentNullException("outputPath");
  367. }
  368. _fileSystem.CreateDirectory(Path.GetDirectoryName(outputPath));
  369. var encodingParam = await GetSubtitleFileCharacterSet(inputPath, language, inputProtocol, cancellationToken).ConfigureAwait(false);
  370. if (!string.IsNullOrEmpty(encodingParam))
  371. {
  372. encodingParam = " -sub_charenc " + encodingParam;
  373. }
  374. var process = new Process
  375. {
  376. StartInfo = new ProcessStartInfo
  377. {
  378. RedirectStandardOutput = false,
  379. RedirectStandardError = true,
  380. RedirectStandardInput = true,
  381. CreateNoWindow = true,
  382. UseShellExecute = false,
  383. FileName = _mediaEncoder.EncoderPath,
  384. Arguments = string.Format("{0} -i \"{1}\" -c:s srt \"{2}\"", encodingParam, inputPath, outputPath),
  385. WindowStyle = ProcessWindowStyle.Hidden,
  386. ErrorDialog = false
  387. }
  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, FileMode.Create, FileAccess.Write, FileShare.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 ApplicationException(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 = new Process
  499. {
  500. StartInfo = new ProcessStartInfo
  501. {
  502. CreateNoWindow = true,
  503. UseShellExecute = false,
  504. RedirectStandardOutput = false,
  505. RedirectStandardError = true,
  506. RedirectStandardInput = true,
  507. FileName = _mediaEncoder.EncoderPath,
  508. Arguments = processArgs,
  509. WindowStyle = ProcessWindowStyle.Hidden,
  510. ErrorDialog = false
  511. }
  512. };
  513. _logger.Info("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments);
  514. var logFilePath = Path.Combine(_appPaths.LogDirectoryPath, "ffmpeg-sub-extract-" + Guid.NewGuid() + ".txt");
  515. _fileSystem.CreateDirectory(Path.GetDirectoryName(logFilePath));
  516. var logFileStream = _fileSystem.GetFileStream(logFilePath, FileMode.Create, FileAccess.Write, FileShare.Read,
  517. true);
  518. try
  519. {
  520. process.Start();
  521. }
  522. catch (Exception ex)
  523. {
  524. logFileStream.Dispose();
  525. _logger.ErrorException("Error starting ffmpeg", ex);
  526. throw;
  527. }
  528. // Important - don't await the log task or we won't be able to kill ffmpeg when the user stops playback
  529. Task.Run(() => StartStreamingLog(process.StandardError.BaseStream, logFileStream));
  530. var ranToCompletion = process.WaitForExit(300000);
  531. if (!ranToCompletion)
  532. {
  533. try
  534. {
  535. _logger.Info("Killing ffmpeg subtitle extraction process");
  536. process.StandardInput.WriteLine("q");
  537. process.WaitForExit(1000);
  538. }
  539. catch (Exception ex)
  540. {
  541. _logger.ErrorException("Error killing subtitle extraction process", ex);
  542. }
  543. finally
  544. {
  545. logFileStream.Dispose();
  546. }
  547. }
  548. var exitCode = ranToCompletion ? process.ExitCode : -1;
  549. process.Dispose();
  550. var failed = false;
  551. if (exitCode == -1)
  552. {
  553. failed = true;
  554. try
  555. {
  556. _logger.Info("Deleting extracted subtitle due to failure: {0}", outputPath);
  557. _fileSystem.DeleteFile(outputPath);
  558. }
  559. catch (FileNotFoundException)
  560. {
  561. }
  562. catch (DirectoryNotFoundException)
  563. {
  564. }
  565. catch (IOException ex)
  566. {
  567. _logger.ErrorException("Error deleting extracted subtitle {0}", ex, outputPath);
  568. }
  569. }
  570. else if (!_fileSystem.FileExists(outputPath))
  571. {
  572. failed = true;
  573. }
  574. if (failed)
  575. {
  576. var msg = string.Format("ffmpeg subtitle extraction failed for {0} to {1}", inputPath, outputPath);
  577. _logger.Error(msg);
  578. throw new ApplicationException(msg);
  579. }
  580. else
  581. {
  582. var msg = string.Format("ffmpeg subtitle extraction completed for {0} to {1}", inputPath, outputPath);
  583. _logger.Info(msg);
  584. }
  585. if (string.Equals(outputCodec, "ass", StringComparison.OrdinalIgnoreCase))
  586. {
  587. await SetAssFont(outputPath).ConfigureAwait(false);
  588. }
  589. }
  590. private async Task StartStreamingLog(Stream source, Stream target)
  591. {
  592. try
  593. {
  594. using (var reader = new StreamReader(source))
  595. {
  596. while (!reader.EndOfStream)
  597. {
  598. var line = await reader.ReadLineAsync().ConfigureAwait(false);
  599. var bytes = Encoding.UTF8.GetBytes(Environment.NewLine + line);
  600. await target.WriteAsync(bytes, 0, bytes.Length).ConfigureAwait(false);
  601. await target.FlushAsync().ConfigureAwait(false);
  602. }
  603. }
  604. }
  605. catch (ObjectDisposedException)
  606. {
  607. // Don't spam the log. This doesn't seem to throw in windows, but sometimes under linux
  608. }
  609. catch (Exception ex)
  610. {
  611. _logger.ErrorException("Error reading ffmpeg log", ex);
  612. }
  613. }
  614. /// <summary>
  615. /// Sets the ass font.
  616. /// </summary>
  617. /// <param name="file">The file.</param>
  618. /// <returns>Task.</returns>
  619. private async Task SetAssFont(string file)
  620. {
  621. _logger.Info("Setting ass font within {0}", file);
  622. string text;
  623. Encoding encoding;
  624. using (var reader = new StreamReader(file, true))
  625. {
  626. encoding = reader.CurrentEncoding;
  627. text = await reader.ReadToEndAsync().ConfigureAwait(false);
  628. }
  629. var newText = text.Replace(",Arial,", ",Arial Unicode MS,");
  630. if (!string.Equals(text, newText))
  631. {
  632. using (var writer = new StreamWriter(file, false, encoding))
  633. {
  634. writer.Write(newText);
  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. if (GetFileEncoding(path).Equals(Encoding.UTF8))
  660. {
  661. return string.Empty;
  662. }
  663. }
  664. var charset = await DetectCharset(path, language, protocol, cancellationToken).ConfigureAwait(false);
  665. if (!string.IsNullOrWhiteSpace(charset))
  666. {
  667. if (string.Equals(charset, "utf-8", StringComparison.OrdinalIgnoreCase))
  668. {
  669. return null;
  670. }
  671. return charset;
  672. }
  673. if (!string.IsNullOrWhiteSpace(language))
  674. {
  675. return GetSubtitleFileCharacterSetFromLanguage(language);
  676. }
  677. return null;
  678. }
  679. public string GetSubtitleFileCharacterSetFromLanguage(string language)
  680. {
  681. // https://developer.xamarin.com/api/type/System.Text.Encoding/
  682. switch (language.ToLower())
  683. {
  684. case "hun":
  685. return "windows-1252";
  686. case "pol":
  687. case "cze":
  688. case "ces":
  689. case "slo":
  690. case "slk":
  691. case "slv":
  692. case "srp":
  693. case "hrv":
  694. case "rum":
  695. case "ron":
  696. case "rup":
  697. case "alb":
  698. case "sqi":
  699. return "windows-1250";
  700. case "ara":
  701. return "windows-1256";
  702. case "heb":
  703. return "windows-1255";
  704. case "grc":
  705. case "gre":
  706. return "windows-1253";
  707. case "crh":
  708. case "ota":
  709. case "tur":
  710. return "windows-1254";
  711. case "rus":
  712. return "windows-1251";
  713. case "vie":
  714. return "windows-1258";
  715. case "kor":
  716. return "cp949";
  717. default:
  718. return "windows-1252";
  719. }
  720. }
  721. private async Task<string> DetectCharset(string path, string language, MediaProtocol protocol, CancellationToken cancellationToken)
  722. {
  723. try
  724. {
  725. using (var file = await GetStream(path, protocol, cancellationToken).ConfigureAwait(false))
  726. {
  727. var detector = new CharsetDetector();
  728. detector.Feed(file);
  729. detector.DataEnd();
  730. var charset = detector.Charset;
  731. if (!string.IsNullOrWhiteSpace(charset))
  732. {
  733. _logger.Info("UniversalDetector detected charset {0} for {1}", charset, path);
  734. }
  735. // This is often incorrectly indetected. If this happens, try to use other techniques instead
  736. if (string.Equals("x-mac-cyrillic", charset, StringComparison.OrdinalIgnoreCase))
  737. {
  738. if (!string.IsNullOrWhiteSpace(language))
  739. {
  740. return null;
  741. }
  742. }
  743. return charset;
  744. }
  745. }
  746. catch (IOException ex)
  747. {
  748. _logger.ErrorException("Error attempting to determine subtitle charset from {0}", ex, path);
  749. }
  750. return null;
  751. }
  752. private Encoding GetFileEncoding(string srcFile)
  753. {
  754. // *** Detect byte order mark if any - otherwise assume default
  755. var buffer = new byte[5];
  756. using (var file = _fileSystem.GetFileStream(srcFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
  757. {
  758. file.Read(buffer, 0, 5);
  759. }
  760. if (buffer[0] == 0xef && buffer[1] == 0xbb && buffer[2] == 0xbf)
  761. return Encoding.UTF8;
  762. if (buffer[0] == 0xfe && buffer[1] == 0xff)
  763. return Encoding.Unicode;
  764. if (buffer[0] == 0 && buffer[1] == 0 && buffer[2] == 0xfe && buffer[3] == 0xff)
  765. return Encoding.UTF32;
  766. if (buffer[0] == 0x2b && buffer[1] == 0x2f && buffer[2] == 0x76)
  767. return Encoding.UTF7;
  768. // It's ok - anything aside from utf is ok since that's what we're looking for
  769. return Encoding.Default;
  770. }
  771. private async Task<Stream> GetStream(string path, MediaProtocol protocol, CancellationToken cancellationToken)
  772. {
  773. if (protocol == MediaProtocol.Http)
  774. {
  775. return await _httpClient.Get(path, cancellationToken).ConfigureAwait(false);
  776. }
  777. if (protocol == MediaProtocol.File)
  778. {
  779. return _fileSystem.GetFileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
  780. }
  781. throw new ArgumentOutOfRangeException("protocol");
  782. }
  783. }
  784. }