SubtitleEncoder.cs 33 KB

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