SubtitleEncoder.cs 33 KB

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