MediaEncoder.cs 32 KB

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