MediaEncoder.cs 38 KB

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