MediaEncoder.cs 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054
  1. using MediaBrowser.Common.Configuration;
  2. using MediaBrowser.Common.IO;
  3. using MediaBrowser.Common.MediaInfo;
  4. using MediaBrowser.Controller.IO;
  5. using MediaBrowser.Model.Entities;
  6. using MediaBrowser.Model.Logging;
  7. using MediaBrowser.Model.Serialization;
  8. using System;
  9. using System.Collections.Concurrent;
  10. using System.Collections.Generic;
  11. using System.ComponentModel;
  12. using System.Diagnostics;
  13. using System.Globalization;
  14. using System.IO;
  15. using System.Linq;
  16. using System.Text;
  17. using System.Threading;
  18. using System.Threading.Tasks;
  19. namespace MediaBrowser.Server.Implementations.MediaEncoder
  20. {
  21. /// <summary>
  22. /// Class MediaEncoder
  23. /// </summary>
  24. public class MediaEncoder : IMediaEncoder, IDisposable
  25. {
  26. /// <summary>
  27. /// The _logger
  28. /// </summary>
  29. private readonly ILogger _logger;
  30. /// <summary>
  31. /// The _app paths
  32. /// </summary>
  33. private readonly IApplicationPaths _appPaths;
  34. /// <summary>
  35. /// Gets the json serializer.
  36. /// </summary>
  37. /// <value>The json serializer.</value>
  38. private readonly IJsonSerializer _jsonSerializer;
  39. /// <summary>
  40. /// The video image resource pool
  41. /// </summary>
  42. private readonly SemaphoreSlim _videoImageResourcePool = new SemaphoreSlim(1, 1);
  43. /// <summary>
  44. /// The audio image resource pool
  45. /// </summary>
  46. private readonly SemaphoreSlim _audioImageResourcePool = new SemaphoreSlim(1, 1);
  47. /// <summary>
  48. /// The FF probe resource pool
  49. /// </summary>
  50. private readonly SemaphoreSlim _ffProbeResourcePool = new SemaphoreSlim(1, 1);
  51. private readonly IFileSystem _fileSystem;
  52. public string FFMpegPath { get; private set; }
  53. public string FFProbePath { get; private set; }
  54. public string Version { get; private set; }
  55. public MediaEncoder(ILogger logger, IApplicationPaths appPaths,
  56. IJsonSerializer jsonSerializer, string ffMpegPath, string ffProbePath, string version, IFileSystem fileSystem)
  57. {
  58. _logger = logger;
  59. _appPaths = appPaths;
  60. _jsonSerializer = jsonSerializer;
  61. Version = version;
  62. _fileSystem = fileSystem;
  63. FFProbePath = ffProbePath;
  64. FFMpegPath = ffMpegPath;
  65. }
  66. /// <summary>
  67. /// Gets the encoder path.
  68. /// </summary>
  69. /// <value>The encoder path.</value>
  70. public string EncoderPath
  71. {
  72. get { return FFMpegPath; }
  73. }
  74. /// <summary>
  75. /// The _semaphoreLocks
  76. /// </summary>
  77. private readonly ConcurrentDictionary<string, SemaphoreSlim> _semaphoreLocks = new ConcurrentDictionary<string, SemaphoreSlim>();
  78. /// <summary>
  79. /// Gets the lock.
  80. /// </summary>
  81. /// <param name="filename">The filename.</param>
  82. /// <returns>System.Object.</returns>
  83. private SemaphoreSlim GetLock(string filename)
  84. {
  85. return _semaphoreLocks.GetOrAdd(filename, key => new SemaphoreSlim(1, 1));
  86. }
  87. /// <summary>
  88. /// Gets the media info.
  89. /// </summary>
  90. /// <param name="inputFiles">The input files.</param>
  91. /// <param name="type">The type.</param>
  92. /// <param name="cancellationToken">The cancellation token.</param>
  93. /// <returns>Task.</returns>
  94. public Task<MediaInfoResult> GetMediaInfo(string[] inputFiles, InputType type,
  95. CancellationToken cancellationToken)
  96. {
  97. return GetMediaInfoInternal(GetInputArgument(inputFiles, type), type != InputType.AudioFile,
  98. GetProbeSizeArgument(type), cancellationToken);
  99. }
  100. /// <summary>
  101. /// Gets the input argument.
  102. /// </summary>
  103. /// <param name="inputFiles">The input files.</param>
  104. /// <param name="type">The type.</param>
  105. /// <returns>System.String.</returns>
  106. /// <exception cref="System.ArgumentException">Unrecognized InputType</exception>
  107. public string GetInputArgument(string[] inputFiles, InputType type)
  108. {
  109. string inputPath;
  110. switch (type)
  111. {
  112. case InputType.Dvd:
  113. case InputType.VideoFile:
  114. case InputType.AudioFile:
  115. inputPath = GetConcatInputArgument(inputFiles);
  116. break;
  117. case InputType.Bluray:
  118. inputPath = GetBlurayInputArgument(inputFiles[0]);
  119. break;
  120. case InputType.Url:
  121. inputPath = GetHttpInputArgument(inputFiles);
  122. break;
  123. default:
  124. throw new ArgumentException("Unrecognized InputType");
  125. }
  126. return inputPath;
  127. }
  128. /// <summary>
  129. /// Gets the HTTP input argument.
  130. /// </summary>
  131. /// <param name="inputFiles">The input files.</param>
  132. /// <returns>System.String.</returns>
  133. private string GetHttpInputArgument(string[] inputFiles)
  134. {
  135. var url = inputFiles[0];
  136. return string.Format("\"{0}\"", url);
  137. }
  138. /// <summary>
  139. /// Gets the probe size argument.
  140. /// </summary>
  141. /// <param name="type">The type.</param>
  142. /// <returns>System.String.</returns>
  143. public string GetProbeSizeArgument(InputType type)
  144. {
  145. return type == InputType.Dvd ? "-probesize 1G -analyzeduration 200M" : string.Empty;
  146. }
  147. /// <summary>
  148. /// Gets the media info internal.
  149. /// </summary>
  150. /// <param name="inputPath">The input path.</param>
  151. /// <param name="extractChapters">if set to <c>true</c> [extract chapters].</param>
  152. /// <param name="probeSizeArgument">The probe size argument.</param>
  153. /// <param name="cancellationToken">The cancellation token.</param>
  154. /// <returns>Task{MediaInfoResult}.</returns>
  155. /// <exception cref="System.ApplicationException"></exception>
  156. private async Task<MediaInfoResult> GetMediaInfoInternal(string inputPath, bool extractChapters,
  157. string probeSizeArgument,
  158. CancellationToken cancellationToken)
  159. {
  160. var process = new Process
  161. {
  162. StartInfo = new ProcessStartInfo
  163. {
  164. CreateNoWindow = true,
  165. UseShellExecute = false,
  166. // Must consume both or ffmpeg may hang due to deadlocks. See comments below.
  167. RedirectStandardOutput = true,
  168. RedirectStandardError = true,
  169. FileName = FFProbePath,
  170. Arguments =
  171. string.Format(
  172. "{0} -i {1} -threads 0 -v info -print_format json -show_streams -show_format",
  173. probeSizeArgument, inputPath).Trim(),
  174. WindowStyle = ProcessWindowStyle.Hidden,
  175. ErrorDialog = false
  176. },
  177. EnableRaisingEvents = true
  178. };
  179. _logger.Debug("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments);
  180. process.Exited += ProcessExited;
  181. await _ffProbeResourcePool.WaitAsync(cancellationToken).ConfigureAwait(false);
  182. MediaInfoResult result;
  183. string standardError = null;
  184. try
  185. {
  186. process.Start();
  187. }
  188. catch (Exception ex)
  189. {
  190. _ffProbeResourcePool.Release();
  191. _logger.ErrorException("Error starting ffprobe", ex);
  192. throw;
  193. }
  194. try
  195. {
  196. Task<string> standardErrorReadTask = null;
  197. // MUST read both stdout and stderr asynchronously or a deadlock may occurr
  198. if (extractChapters)
  199. {
  200. standardErrorReadTask = process.StandardError.ReadToEndAsync();
  201. }
  202. else
  203. {
  204. process.BeginErrorReadLine();
  205. }
  206. result = _jsonSerializer.DeserializeFromStream<MediaInfoResult>(process.StandardOutput.BaseStream);
  207. if (extractChapters)
  208. {
  209. standardError = await standardErrorReadTask.ConfigureAwait(false);
  210. }
  211. }
  212. catch
  213. {
  214. // Hate having to do this
  215. try
  216. {
  217. process.Kill();
  218. }
  219. catch (InvalidOperationException ex1)
  220. {
  221. _logger.ErrorException("Error killing ffprobe", ex1);
  222. }
  223. catch (Win32Exception ex1)
  224. {
  225. _logger.ErrorException("Error killing ffprobe", ex1);
  226. }
  227. throw;
  228. }
  229. finally
  230. {
  231. _ffProbeResourcePool.Release();
  232. }
  233. if (result == null)
  234. {
  235. throw new ApplicationException(string.Format("FFProbe failed for {0}", inputPath));
  236. }
  237. cancellationToken.ThrowIfCancellationRequested();
  238. if (result.streams != null)
  239. {
  240. // Normalize aspect ratio if invalid
  241. foreach (var stream in result.streams)
  242. {
  243. if (string.Equals(stream.display_aspect_ratio, "0:1", StringComparison.OrdinalIgnoreCase))
  244. {
  245. stream.display_aspect_ratio = string.Empty;
  246. }
  247. if (string.Equals(stream.sample_aspect_ratio, "0:1", StringComparison.OrdinalIgnoreCase))
  248. {
  249. stream.sample_aspect_ratio = string.Empty;
  250. }
  251. }
  252. }
  253. if (extractChapters && !string.IsNullOrEmpty(standardError))
  254. {
  255. AddChapters(result, standardError);
  256. }
  257. return result;
  258. }
  259. /// <summary>
  260. /// The us culture
  261. /// </summary>
  262. protected readonly CultureInfo UsCulture = new CultureInfo("en-US");
  263. /// <summary>
  264. /// Adds the chapters.
  265. /// </summary>
  266. /// <param name="result">The result.</param>
  267. /// <param name="standardError">The standard error.</param>
  268. private void AddChapters(MediaInfoResult result, string standardError)
  269. {
  270. var lines = standardError.Split('\n').Select(l => l.TrimStart());
  271. var chapters = new List<ChapterInfo>();
  272. ChapterInfo lastChapter = null;
  273. foreach (var line in lines)
  274. {
  275. if (line.StartsWith("Chapter", StringComparison.OrdinalIgnoreCase))
  276. {
  277. // Example:
  278. // Chapter #0.2: start 400.534, end 4565.435
  279. const string srch = "start ";
  280. var start = line.IndexOf(srch, StringComparison.OrdinalIgnoreCase);
  281. if (start == -1)
  282. {
  283. continue;
  284. }
  285. var subString = line.Substring(start + srch.Length);
  286. subString = subString.Substring(0, subString.IndexOf(','));
  287. double seconds;
  288. if (double.TryParse(subString, NumberStyles.Any, UsCulture, out seconds))
  289. {
  290. lastChapter = new ChapterInfo
  291. {
  292. StartPositionTicks = TimeSpan.FromSeconds(seconds).Ticks
  293. };
  294. chapters.Add(lastChapter);
  295. }
  296. }
  297. else if (line.StartsWith("title", StringComparison.OrdinalIgnoreCase))
  298. {
  299. if (lastChapter != null && string.IsNullOrEmpty(lastChapter.Name))
  300. {
  301. var index = line.IndexOf(':');
  302. if (index != -1)
  303. {
  304. lastChapter.Name = line.Substring(index + 1).Trim().TrimEnd('\r');
  305. }
  306. }
  307. }
  308. }
  309. result.Chapters = chapters;
  310. }
  311. /// <summary>
  312. /// Processes the exited.
  313. /// </summary>
  314. /// <param name="sender">The sender.</param>
  315. /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
  316. private void ProcessExited(object sender, EventArgs e)
  317. {
  318. ((Process)sender).Dispose();
  319. }
  320. /// <summary>
  321. /// Converts the text subtitle to ass.
  322. /// </summary>
  323. /// <param name="inputPath">The input path.</param>
  324. /// <param name="outputPath">The output path.</param>
  325. /// <param name="language">The language.</param>
  326. /// <param name="offset">The offset.</param>
  327. /// <param name="cancellationToken">The cancellation token.</param>
  328. /// <returns>Task.</returns>
  329. public async Task ConvertTextSubtitleToAss(string inputPath, string outputPath, string language, TimeSpan offset,
  330. CancellationToken cancellationToken)
  331. {
  332. var semaphore = GetLock(outputPath);
  333. await semaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
  334. try
  335. {
  336. if (!File.Exists(outputPath))
  337. {
  338. await ConvertTextSubtitleToAssInternal(inputPath, outputPath, language, offset).ConfigureAwait(false);
  339. }
  340. }
  341. finally
  342. {
  343. semaphore.Release();
  344. }
  345. }
  346. private const int FastSeekOffsetSeconds = 1;
  347. /// <summary>
  348. /// Converts the text subtitle to ass.
  349. /// </summary>
  350. /// <param name="inputPath">The input path.</param>
  351. /// <param name="outputPath">The output path.</param>
  352. /// <param name="language">The language.</param>
  353. /// <param name="offset">The offset.</param>
  354. /// <returns>Task.</returns>
  355. /// <exception cref="System.ArgumentNullException">inputPath
  356. /// or
  357. /// outputPath</exception>
  358. /// <exception cref="System.ApplicationException"></exception>
  359. private async Task ConvertTextSubtitleToAssInternal(string inputPath, string outputPath, string language, TimeSpan offset)
  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. var slowSeekParam = GetSlowSeekCommandLineParameter(offset);
  370. var fastSeekParam = GetFastSeekCommandLineParameter(offset);
  371. var encodingParam = string.IsNullOrEmpty(language) ? string.Empty :
  372. GetSubtitleLanguageEncodingParam(language) + " ";
  373. var process = new Process
  374. {
  375. StartInfo = new ProcessStartInfo
  376. {
  377. RedirectStandardOutput = false,
  378. RedirectStandardError = true,
  379. CreateNoWindow = true,
  380. UseShellExecute = false,
  381. FileName = FFMpegPath,
  382. Arguments =
  383. string.Format("{0}{1}-i \"{2}\"{3} \"{4}\"",
  384. fastSeekParam,
  385. encodingParam,
  386. inputPath,
  387. slowSeekParam,
  388. outputPath),
  389. WindowStyle = ProcessWindowStyle.Hidden,
  390. ErrorDialog = false
  391. }
  392. };
  393. _logger.Debug("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments);
  394. var logFilePath = Path.Combine(_appPaths.LogDirectoryPath, "ffmpeg-sub-convert-" + Guid.NewGuid() + ".txt");
  395. var logFileStream = _fileSystem.GetFileStream(logFilePath, FileMode.Create, FileAccess.Write, FileShare.Read, true);
  396. try
  397. {
  398. process.Start();
  399. }
  400. catch (Exception ex)
  401. {
  402. logFileStream.Dispose();
  403. _logger.ErrorException("Error starting ffmpeg", ex);
  404. throw;
  405. }
  406. var logTask = process.StandardError.BaseStream.CopyToAsync(logFileStream);
  407. var ranToCompletion = process.WaitForExit(60000);
  408. if (!ranToCompletion)
  409. {
  410. try
  411. {
  412. _logger.Info("Killing ffmpeg subtitle conversion process");
  413. process.Kill();
  414. process.WaitForExit(1000);
  415. await logTask.ConfigureAwait(false);
  416. }
  417. catch (Exception ex)
  418. {
  419. _logger.ErrorException("Error killing subtitle conversion process", ex);
  420. }
  421. finally
  422. {
  423. logFileStream.Dispose();
  424. }
  425. }
  426. var exitCode = ranToCompletion ? process.ExitCode : -1;
  427. process.Dispose();
  428. var failed = false;
  429. if (exitCode == -1)
  430. {
  431. failed = true;
  432. if (File.Exists(outputPath))
  433. {
  434. try
  435. {
  436. _logger.Info("Deleting converted subtitle due to failure: ", outputPath);
  437. File.Delete(outputPath);
  438. }
  439. catch (IOException ex)
  440. {
  441. _logger.ErrorException("Error deleting converted subtitle {0}", ex, outputPath);
  442. }
  443. }
  444. }
  445. else if (!File.Exists(outputPath))
  446. {
  447. failed = true;
  448. }
  449. if (failed)
  450. {
  451. var msg = string.Format("ffmpeg subtitle converted failed for {0}", inputPath);
  452. _logger.Error(msg);
  453. throw new ApplicationException(msg);
  454. }
  455. await SetAssFont(outputPath).ConfigureAwait(false);
  456. }
  457. protected string GetFastSeekCommandLineParameter(TimeSpan offset)
  458. {
  459. var seconds = offset.TotalSeconds - FastSeekOffsetSeconds;
  460. if (seconds > 0)
  461. {
  462. return string.Format("-ss {0} ", seconds.ToString(UsCulture));
  463. }
  464. return string.Empty;
  465. }
  466. protected string GetSlowSeekCommandLineParameter(TimeSpan offset)
  467. {
  468. if (offset.TotalSeconds - FastSeekOffsetSeconds > 0)
  469. {
  470. return string.Format(" -ss {0}", FastSeekOffsetSeconds.ToString(UsCulture));
  471. }
  472. return string.Empty;
  473. }
  474. /// <summary>
  475. /// Gets the subtitle language encoding param.
  476. /// </summary>
  477. /// <param name="language">The language.</param>
  478. /// <returns>System.String.</returns>
  479. private string GetSubtitleLanguageEncodingParam(string language)
  480. {
  481. switch (language.ToLower())
  482. {
  483. case "pol":
  484. case "cze":
  485. case "ces":
  486. case "slo":
  487. case "slk":
  488. case "hun":
  489. case "slv":
  490. case "srp":
  491. case "hrv":
  492. case "rum":
  493. case "ron":
  494. case "rup":
  495. case "alb":
  496. case "sqi":
  497. return "-sub_charenc windows-1250";
  498. case "ara":
  499. return "-sub_charenc windows-1256";
  500. case "heb":
  501. return "-sub_charenc windows-1255";
  502. case "grc":
  503. case "gre":
  504. return "-sub_charenc windows-1253";
  505. case "crh":
  506. case "ota":
  507. case "tur":
  508. return "-sub_charenc windows-1254";
  509. case "rus":
  510. return "-sub_charenc windows-1251";
  511. case "vie":
  512. return "-sub_charenc windows-1258";
  513. default:
  514. return "-sub_charenc windows-1252";
  515. }
  516. }
  517. /// <summary>
  518. /// Extracts the text subtitle.
  519. /// </summary>
  520. /// <param name="inputFiles">The input files.</param>
  521. /// <param name="type">The type.</param>
  522. /// <param name="subtitleStreamIndex">Index of the subtitle stream.</param>
  523. /// <param name="offset">The offset.</param>
  524. /// <param name="outputPath">The output path.</param>
  525. /// <param name="cancellationToken">The cancellation token.</param>
  526. /// <returns>Task.</returns>
  527. /// <exception cref="System.ArgumentException">Must use inputPath list overload</exception>
  528. public async Task ExtractTextSubtitle(string[] inputFiles, InputType type, int subtitleStreamIndex, TimeSpan offset, string outputPath, CancellationToken cancellationToken)
  529. {
  530. var semaphore = GetLock(outputPath);
  531. await semaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
  532. try
  533. {
  534. if (!File.Exists(outputPath))
  535. {
  536. await ExtractTextSubtitleInternal(GetInputArgument(inputFiles, type), subtitleStreamIndex, offset, outputPath, cancellationToken).ConfigureAwait(false);
  537. }
  538. }
  539. finally
  540. {
  541. semaphore.Release();
  542. }
  543. }
  544. /// <summary>
  545. /// Extracts the text subtitle.
  546. /// </summary>
  547. /// <param name="inputPath">The input path.</param>
  548. /// <param name="subtitleStreamIndex">Index of the subtitle stream.</param>
  549. /// <param name="offset">The offset.</param>
  550. /// <param name="outputPath">The output path.</param>
  551. /// <param name="cancellationToken">The cancellation token.</param>
  552. /// <returns>Task.</returns>
  553. /// <exception cref="System.ArgumentNullException">inputPath
  554. /// or
  555. /// outputPath
  556. /// or
  557. /// cancellationToken</exception>
  558. /// <exception cref="System.ApplicationException"></exception>
  559. private async Task ExtractTextSubtitleInternal(string inputPath, int subtitleStreamIndex, TimeSpan offset, string outputPath, CancellationToken cancellationToken)
  560. {
  561. if (string.IsNullOrEmpty(inputPath))
  562. {
  563. throw new ArgumentNullException("inputPath");
  564. }
  565. if (string.IsNullOrEmpty(outputPath))
  566. {
  567. throw new ArgumentNullException("outputPath");
  568. }
  569. var slowSeekParam = offset.TotalSeconds > 0 ? " -ss " + offset.TotalSeconds.ToString(UsCulture) : string.Empty;
  570. var process = new Process
  571. {
  572. StartInfo = new ProcessStartInfo
  573. {
  574. CreateNoWindow = true,
  575. UseShellExecute = false,
  576. RedirectStandardOutput = false,
  577. RedirectStandardError = true,
  578. FileName = FFMpegPath,
  579. Arguments = string.Format("-i {0}{1} -map 0:{2} -an -vn -c:s ass \"{3}\"", inputPath, slowSeekParam, subtitleStreamIndex, outputPath),
  580. WindowStyle = ProcessWindowStyle.Hidden,
  581. ErrorDialog = false
  582. }
  583. };
  584. _logger.Debug("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments);
  585. var logFilePath = Path.Combine(_appPaths.LogDirectoryPath, "ffmpeg-sub-extract-" + Guid.NewGuid() + ".txt");
  586. var logFileStream = _fileSystem.GetFileStream(logFilePath, FileMode.Create, FileAccess.Write, FileShare.Read, true);
  587. try
  588. {
  589. process.Start();
  590. }
  591. catch (Exception ex)
  592. {
  593. logFileStream.Dispose();
  594. _logger.ErrorException("Error starting ffmpeg", ex);
  595. throw;
  596. }
  597. process.StandardError.BaseStream.CopyToAsync(logFileStream);
  598. var ranToCompletion = process.WaitForExit(60000);
  599. if (!ranToCompletion)
  600. {
  601. try
  602. {
  603. _logger.Info("Killing ffmpeg subtitle extraction process");
  604. process.Kill();
  605. process.WaitForExit(1000);
  606. }
  607. catch (Exception ex)
  608. {
  609. _logger.ErrorException("Error killing subtitle extraction process", ex);
  610. }
  611. finally
  612. {
  613. logFileStream.Dispose();
  614. }
  615. }
  616. var exitCode = ranToCompletion ? process.ExitCode : -1;
  617. process.Dispose();
  618. var failed = false;
  619. if (exitCode == -1)
  620. {
  621. failed = true;
  622. if (File.Exists(outputPath))
  623. {
  624. try
  625. {
  626. _logger.Info("Deleting extracted subtitle due to failure: ", outputPath);
  627. File.Delete(outputPath);
  628. }
  629. catch (IOException ex)
  630. {
  631. _logger.ErrorException("Error deleting extracted subtitle {0}", ex, outputPath);
  632. }
  633. }
  634. }
  635. else if (!File.Exists(outputPath))
  636. {
  637. failed = true;
  638. }
  639. if (failed)
  640. {
  641. var msg = string.Format("ffmpeg subtitle extraction failed for {0} to {1}", inputPath, outputPath);
  642. _logger.Error(msg);
  643. throw new ApplicationException(msg);
  644. }
  645. else
  646. {
  647. var msg = string.Format("ffmpeg subtitle extraction completed for {0} to {1}", inputPath, outputPath);
  648. _logger.Info(msg);
  649. }
  650. await SetAssFont(outputPath).ConfigureAwait(false);
  651. }
  652. /// <summary>
  653. /// Sets the ass font.
  654. /// </summary>
  655. /// <param name="file">The file.</param>
  656. /// <returns>Task.</returns>
  657. private async Task SetAssFont(string file)
  658. {
  659. _logger.Info("Setting ass font within {0}", file);
  660. string text;
  661. Encoding encoding;
  662. using (var reader = new StreamReader(file, detectEncodingFromByteOrderMarks: true))
  663. {
  664. encoding = reader.CurrentEncoding;
  665. text = await reader.ReadToEndAsync().ConfigureAwait(false);
  666. }
  667. var newText = text.Replace(",Arial,", ",Arial Unicode MS,");
  668. if (!string.Equals(text, newText))
  669. {
  670. using (var writer = new StreamWriter(file, false, encoding))
  671. {
  672. writer.Write(newText);
  673. }
  674. }
  675. }
  676. /// <summary>
  677. /// Extracts the image.
  678. /// </summary>
  679. /// <param name="inputFiles">The input files.</param>
  680. /// <param name="type">The type.</param>
  681. /// <param name="threedFormat">The threed format.</param>
  682. /// <param name="offset">The offset.</param>
  683. /// <param name="outputPath">The output path.</param>
  684. /// <param name="cancellationToken">The cancellation token.</param>
  685. /// <returns>Task.</returns>
  686. /// <exception cref="System.ArgumentException">Must use inputPath list overload</exception>
  687. public async Task ExtractImage(string[] inputFiles, InputType type, Video3DFormat? threedFormat, TimeSpan? offset, string outputPath, CancellationToken cancellationToken)
  688. {
  689. var resourcePool = type == InputType.AudioFile ? _audioImageResourcePool : _videoImageResourcePool;
  690. var inputArgument = GetInputArgument(inputFiles, type);
  691. if (type != InputType.AudioFile)
  692. {
  693. try
  694. {
  695. await ExtractImageInternal(inputArgument, type, threedFormat, offset, outputPath, true, resourcePool, cancellationToken).ConfigureAwait(false);
  696. return;
  697. }
  698. catch
  699. {
  700. _logger.Error("I-frame image extraction failed, will attempt standard way. Input: {0}", inputArgument);
  701. }
  702. }
  703. await ExtractImageInternal(inputArgument, type, threedFormat, offset, outputPath, false, resourcePool, cancellationToken).ConfigureAwait(false);
  704. }
  705. /// <summary>
  706. /// Extracts the image.
  707. /// </summary>
  708. /// <param name="inputPath">The input path.</param>
  709. /// <param name="type">The type.</param>
  710. /// <param name="threedFormat">The threed format.</param>
  711. /// <param name="offset">The offset.</param>
  712. /// <param name="outputPath">The output path.</param>
  713. /// <param name="useIFrame">if set to <c>true</c> [use I frame].</param>
  714. /// <param name="resourcePool">The resource pool.</param>
  715. /// <param name="cancellationToken">The cancellation token.</param>
  716. /// <returns>Task.</returns>
  717. /// <exception cref="System.ArgumentNullException">inputPath
  718. /// or
  719. /// outputPath</exception>
  720. /// <exception cref="System.ApplicationException"></exception>
  721. private async Task ExtractImageInternal(string inputPath, InputType type, Video3DFormat? threedFormat, TimeSpan? offset, string outputPath, bool useIFrame, SemaphoreSlim resourcePool, CancellationToken cancellationToken)
  722. {
  723. if (string.IsNullOrEmpty(inputPath))
  724. {
  725. throw new ArgumentNullException("inputPath");
  726. }
  727. if (string.IsNullOrEmpty(outputPath))
  728. {
  729. throw new ArgumentNullException("outputPath");
  730. }
  731. var vf = "scale=iw*sar:ih, scale=600:-1";
  732. if (threedFormat.HasValue)
  733. {
  734. switch (threedFormat.Value)
  735. {
  736. case Video3DFormat.HalfSideBySide:
  737. case Video3DFormat.FullSideBySide:
  738. vf = "crop=iw/2:ih:0:0,scale=(iw*2):ih,scale=600:-1";
  739. break;
  740. case Video3DFormat.HalfTopAndBottom:
  741. case Video3DFormat.FullTopAndBottom:
  742. vf = "crop=iw:ih/2:0:0,scale=iw:(ih*2),scale=600:-1";
  743. break;
  744. }
  745. }
  746. var args = useIFrame ? string.Format("-i {0} -threads 0 -v quiet -vframes 1 -filter:v select=\"eq(pict_type\\,I)\" -vf \"{2}\" -f image2 \"{1}\"", inputPath, outputPath, vf) :
  747. string.Format("-i {0} -threads 0 -v quiet -vframes 1 -vf \"{2}\" -f image2 \"{1}\"", inputPath, outputPath, vf);
  748. var probeSize = GetProbeSizeArgument(type);
  749. if (!string.IsNullOrEmpty(probeSize))
  750. {
  751. args = probeSize + " " + args;
  752. }
  753. if (offset.HasValue)
  754. {
  755. args = string.Format("-ss {0} ", Convert.ToInt32(offset.Value.TotalSeconds)).ToString(UsCulture) + args;
  756. }
  757. var process = new Process
  758. {
  759. StartInfo = new ProcessStartInfo
  760. {
  761. CreateNoWindow = true,
  762. UseShellExecute = false,
  763. FileName = FFMpegPath,
  764. Arguments = args,
  765. WindowStyle = ProcessWindowStyle.Hidden,
  766. ErrorDialog = false
  767. }
  768. };
  769. await resourcePool.WaitAsync(cancellationToken).ConfigureAwait(false);
  770. var ranToCompletion = StartAndWaitForProcess(process);
  771. resourcePool.Release();
  772. var exitCode = ranToCompletion ? process.ExitCode : -1;
  773. process.Dispose();
  774. var failed = false;
  775. if (exitCode == -1)
  776. {
  777. failed = true;
  778. if (File.Exists(outputPath))
  779. {
  780. try
  781. {
  782. _logger.Info("Deleting extracted image due to failure: ", outputPath);
  783. File.Delete(outputPath);
  784. }
  785. catch (IOException ex)
  786. {
  787. _logger.ErrorException("Error deleting extracted image {0}", ex, outputPath);
  788. }
  789. }
  790. }
  791. else if (!File.Exists(outputPath))
  792. {
  793. failed = true;
  794. }
  795. if (failed)
  796. {
  797. var msg = string.Format("ffmpeg image extraction failed for {0}", inputPath);
  798. _logger.Error(msg);
  799. throw new ApplicationException(msg);
  800. }
  801. }
  802. /// <summary>
  803. /// Starts the and wait for process.
  804. /// </summary>
  805. /// <param name="process">The process.</param>
  806. /// <param name="timeout">The timeout.</param>
  807. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  808. private bool StartAndWaitForProcess(Process process, int timeout = 10000)
  809. {
  810. process.Start();
  811. var ranToCompletion = process.WaitForExit(timeout);
  812. if (!ranToCompletion)
  813. {
  814. try
  815. {
  816. _logger.Info("Killing ffmpeg process");
  817. process.Kill();
  818. process.WaitForExit(1000);
  819. }
  820. catch (Win32Exception ex)
  821. {
  822. _logger.ErrorException("Error killing process", ex);
  823. }
  824. catch (InvalidOperationException ex)
  825. {
  826. _logger.ErrorException("Error killing process", ex);
  827. }
  828. catch (NotSupportedException ex)
  829. {
  830. _logger.ErrorException("Error killing process", ex);
  831. }
  832. }
  833. return ranToCompletion;
  834. }
  835. /// <summary>
  836. /// Gets the file input argument.
  837. /// </summary>
  838. /// <param name="path">The path.</param>
  839. /// <returns>System.String.</returns>
  840. private string GetFileInputArgument(string path)
  841. {
  842. return string.Format("file:\"{0}\"", path);
  843. }
  844. /// <summary>
  845. /// Gets the concat input argument.
  846. /// </summary>
  847. /// <param name="playableStreamFiles">The playable stream files.</param>
  848. /// <returns>System.String.</returns>
  849. private string GetConcatInputArgument(string[] playableStreamFiles)
  850. {
  851. // Get all streams
  852. // If there's more than one we'll need to use the concat command
  853. if (playableStreamFiles.Length > 1)
  854. {
  855. var files = string.Join("|", playableStreamFiles);
  856. return string.Format("concat:\"{0}\"", files);
  857. }
  858. // Determine the input path for video files
  859. return GetFileInputArgument(playableStreamFiles[0]);
  860. }
  861. /// <summary>
  862. /// Gets the bluray input argument.
  863. /// </summary>
  864. /// <param name="blurayRoot">The bluray root.</param>
  865. /// <returns>System.String.</returns>
  866. private string GetBlurayInputArgument(string blurayRoot)
  867. {
  868. return string.Format("bluray:\"{0}\"", blurayRoot);
  869. }
  870. /// <summary>
  871. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  872. /// </summary>
  873. public void Dispose()
  874. {
  875. Dispose(true);
  876. }
  877. /// <summary>
  878. /// Releases unmanaged and - optionally - managed resources.
  879. /// </summary>
  880. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  881. protected virtual void Dispose(bool dispose)
  882. {
  883. if (dispose)
  884. {
  885. _videoImageResourcePool.Dispose();
  886. }
  887. }
  888. }
  889. }