MediaEncoder.cs 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992
  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. CreateNoWindow = true,
  478. UseShellExecute = false,
  479. FileName = FFMpegPath,
  480. Arguments = string.Format("-i \"{0}\" \"{1}\"", inputPath, outputPath),
  481. WindowStyle = ProcessWindowStyle.Hidden,
  482. ErrorDialog = false
  483. }
  484. };
  485. _logger.Debug("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments);
  486. await _subtitleExtractionResourcePool.WaitAsync(cancellationToken).ConfigureAwait(false);
  487. var ranToCompletion = StartAndWaitForProcess(process);
  488. _subtitleExtractionResourcePool.Release();
  489. var exitCode = ranToCompletion ? process.ExitCode : -1;
  490. process.Dispose();
  491. var failed = false;
  492. if (exitCode == -1)
  493. {
  494. failed = true;
  495. if (File.Exists(outputPath))
  496. {
  497. try
  498. {
  499. _logger.Info("Deleting converted subtitle due to failure: ", outputPath);
  500. File.Delete(outputPath);
  501. }
  502. catch (IOException ex)
  503. {
  504. _logger.ErrorException("Error deleting converted subtitle {0}", ex, outputPath);
  505. }
  506. }
  507. }
  508. else if (!File.Exists(outputPath))
  509. {
  510. failed = true;
  511. }
  512. if (failed)
  513. {
  514. var msg = string.Format("ffmpeg subtitle conversion failed for {0}", inputPath);
  515. _logger.Error(msg);
  516. throw new ApplicationException(msg);
  517. }
  518. }
  519. /// <summary>
  520. /// Extracts the text subtitle.
  521. /// </summary>
  522. /// <param name="inputFiles">The input files.</param>
  523. /// <param name="type">The type.</param>
  524. /// <param name="subtitleStreamIndex">Index of the subtitle stream.</param>
  525. /// <param name="offset">The offset.</param>
  526. /// <param name="outputPath">The output path.</param>
  527. /// <param name="cancellationToken">The cancellation token.</param>
  528. /// <returns>Task.</returns>
  529. /// <exception cref="System.ArgumentException">Must use inputPath list overload</exception>
  530. public Task ExtractTextSubtitle(string[] inputFiles, InputType type, int subtitleStreamIndex, TimeSpan offset, string outputPath, CancellationToken cancellationToken)
  531. {
  532. return ExtractTextSubtitleInternal(GetInputArgument(inputFiles, type), subtitleStreamIndex, offset, outputPath, cancellationToken);
  533. }
  534. /// <summary>
  535. /// Extracts the text subtitle.
  536. /// </summary>
  537. /// <param name="inputPath">The input path.</param>
  538. /// <param name="subtitleStreamIndex">Index of the subtitle stream.</param>
  539. /// <param name="offset">The offset.</param>
  540. /// <param name="outputPath">The output path.</param>
  541. /// <param name="cancellationToken">The cancellation token.</param>
  542. /// <returns>Task.</returns>
  543. /// <exception cref="System.ArgumentNullException">inputPath
  544. /// or
  545. /// outputPath
  546. /// or
  547. /// cancellationToken</exception>
  548. /// <exception cref="System.ApplicationException"></exception>
  549. private async Task ExtractTextSubtitleInternal(string inputPath, int subtitleStreamIndex, TimeSpan offset, string outputPath, CancellationToken cancellationToken)
  550. {
  551. if (string.IsNullOrEmpty(inputPath))
  552. {
  553. throw new ArgumentNullException("inputPath");
  554. }
  555. if (string.IsNullOrEmpty(outputPath))
  556. {
  557. throw new ArgumentNullException("outputPath");
  558. }
  559. if (cancellationToken == null)
  560. {
  561. throw new ArgumentNullException("cancellationToken");
  562. }
  563. var offsetParam = offset.Ticks > 0 ? "-ss " + offset.TotalSeconds + " " : string.Empty;
  564. var process = new Process
  565. {
  566. StartInfo = new ProcessStartInfo
  567. {
  568. CreateNoWindow = true,
  569. UseShellExecute = false,
  570. FileName = FFMpegPath,
  571. Arguments = string.Format("{0}-i {1} -map 0:{2} -an -vn -c:s ass \"{3}\"", offsetParam, inputPath, subtitleStreamIndex, outputPath),
  572. WindowStyle = ProcessWindowStyle.Hidden,
  573. ErrorDialog = false
  574. }
  575. };
  576. _logger.Debug("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments);
  577. await _subtitleExtractionResourcePool.WaitAsync(cancellationToken).ConfigureAwait(false);
  578. var ranToCompletion = StartAndWaitForProcess(process);
  579. _subtitleExtractionResourcePool.Release();
  580. var exitCode = ranToCompletion ? process.ExitCode : -1;
  581. process.Dispose();
  582. var failed = false;
  583. if (exitCode == -1)
  584. {
  585. failed = true;
  586. if (File.Exists(outputPath))
  587. {
  588. try
  589. {
  590. _logger.Info("Deleting extracted subtitle due to failure: ", outputPath);
  591. File.Delete(outputPath);
  592. }
  593. catch (IOException ex)
  594. {
  595. _logger.ErrorException("Error deleting extracted subtitle {0}", ex, outputPath);
  596. }
  597. }
  598. }
  599. else if (!File.Exists(outputPath))
  600. {
  601. failed = true;
  602. }
  603. if (failed)
  604. {
  605. var msg = string.Format("ffmpeg subtitle extraction failed for {0}", inputPath);
  606. _logger.Error(msg);
  607. throw new ApplicationException(msg);
  608. }
  609. }
  610. /// <summary>
  611. /// Extracts the image.
  612. /// </summary>
  613. /// <param name="inputFiles">The input files.</param>
  614. /// <param name="type">The type.</param>
  615. /// <param name="offset">The offset.</param>
  616. /// <param name="outputPath">The output path.</param>
  617. /// <param name="cancellationToken">The cancellation token.</param>
  618. /// <returns>Task.</returns>
  619. /// <exception cref="System.ArgumentException">Must use inputPath list overload</exception>
  620. public async Task ExtractImage(string[] inputFiles, InputType type, TimeSpan? offset, string outputPath, CancellationToken cancellationToken)
  621. {
  622. var resourcePool = type == InputType.AudioFile ? _audioImageResourcePool : _videoImageResourcePool;
  623. var inputArgument = GetInputArgument(inputFiles, type);
  624. if (type != InputType.AudioFile)
  625. {
  626. try
  627. {
  628. await ExtractImageInternal(inputArgument, type, offset, outputPath, true, resourcePool, cancellationToken).ConfigureAwait(false);
  629. return;
  630. }
  631. catch
  632. {
  633. _logger.Error("I-frame image extraction failed, will attempt standard way. Input: {0}", inputArgument);
  634. }
  635. }
  636. await ExtractImageInternal(inputArgument, type, offset, outputPath, false, resourcePool, cancellationToken).ConfigureAwait(false);
  637. }
  638. /// <summary>
  639. /// Extracts the image.
  640. /// </summary>
  641. /// <param name="inputPath">The input path.</param>
  642. /// <param name="type">The type.</param>
  643. /// <param name="offset">The offset.</param>
  644. /// <param name="outputPath">The output path.</param>
  645. /// <param name="useIFrame">if set to <c>true</c> [use I frame].</param>
  646. /// <param name="resourcePool">The resource pool.</param>
  647. /// <param name="cancellationToken">The cancellation token.</param>
  648. /// <returns>Task.</returns>
  649. /// <exception cref="System.ArgumentNullException">inputPath
  650. /// or
  651. /// outputPath</exception>
  652. /// <exception cref="System.ApplicationException"></exception>
  653. private async Task ExtractImageInternal(string inputPath, InputType type, TimeSpan? offset, string outputPath, bool useIFrame, SemaphoreSlim resourcePool, CancellationToken cancellationToken)
  654. {
  655. if (string.IsNullOrEmpty(inputPath))
  656. {
  657. throw new ArgumentNullException("inputPath");
  658. }
  659. if (string.IsNullOrEmpty(outputPath))
  660. {
  661. throw new ArgumentNullException("outputPath");
  662. }
  663. 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) :
  664. string.Format("-i {0} -threads 0 -v quiet -vframes 1 -vf \"scale=iw*sar:ih, scale=600:-1\" -f image2 \"{1}\"", inputPath, outputPath);
  665. var probeSize = GetProbeSizeArgument(type);
  666. if (!string.IsNullOrEmpty(probeSize))
  667. {
  668. args = probeSize + " " + args;
  669. }
  670. if (offset.HasValue)
  671. {
  672. args = string.Format("-ss {0} ", Convert.ToInt32(offset.Value.TotalSeconds)) + args;
  673. }
  674. var process = new Process
  675. {
  676. StartInfo = new ProcessStartInfo
  677. {
  678. CreateNoWindow = true,
  679. UseShellExecute = false,
  680. FileName = FFMpegPath,
  681. Arguments = args,
  682. WindowStyle = ProcessWindowStyle.Hidden,
  683. ErrorDialog = false
  684. }
  685. };
  686. await resourcePool.WaitAsync(cancellationToken).ConfigureAwait(false);
  687. var ranToCompletion = StartAndWaitForProcess(process);
  688. resourcePool.Release();
  689. var exitCode = ranToCompletion ? process.ExitCode : -1;
  690. process.Dispose();
  691. var failed = false;
  692. if (exitCode == -1)
  693. {
  694. failed = true;
  695. if (File.Exists(outputPath))
  696. {
  697. try
  698. {
  699. _logger.Info("Deleting extracted image due to failure: ", outputPath);
  700. File.Delete(outputPath);
  701. }
  702. catch (IOException ex)
  703. {
  704. _logger.ErrorException("Error deleting extracted image {0}", ex, outputPath);
  705. }
  706. }
  707. }
  708. else if (!File.Exists(outputPath))
  709. {
  710. failed = true;
  711. }
  712. if (failed)
  713. {
  714. var msg = string.Format("ffmpeg image extraction failed for {0}", inputPath);
  715. _logger.Error(msg);
  716. throw new ApplicationException(msg);
  717. }
  718. }
  719. /// <summary>
  720. /// Starts the and wait for process.
  721. /// </summary>
  722. /// <param name="process">The process.</param>
  723. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  724. private bool StartAndWaitForProcess(Process process)
  725. {
  726. process.Start();
  727. var ranToCompletion = process.WaitForExit(10000);
  728. if (!ranToCompletion)
  729. {
  730. try
  731. {
  732. _logger.Info("Killing ffmpeg process");
  733. process.Kill();
  734. process.WaitForExit(1000);
  735. }
  736. catch (Win32Exception ex)
  737. {
  738. _logger.ErrorException("Error killing process", ex);
  739. }
  740. catch (InvalidOperationException ex)
  741. {
  742. _logger.ErrorException("Error killing process", ex);
  743. }
  744. catch (NotSupportedException ex)
  745. {
  746. _logger.ErrorException("Error killing process", ex);
  747. }
  748. }
  749. return ranToCompletion;
  750. }
  751. /// <summary>
  752. /// Gets the file input argument.
  753. /// </summary>
  754. /// <param name="path">The path.</param>
  755. /// <returns>System.String.</returns>
  756. public string GetFileInputArgument(string path)
  757. {
  758. return string.Format("file:\"{0}\"", path);
  759. }
  760. /// <summary>
  761. /// Gets the concat input argument.
  762. /// </summary>
  763. /// <param name="playableStreamFiles">The playable stream files.</param>
  764. /// <returns>System.String.</returns>
  765. public string GetConcatInputArgument(string[] playableStreamFiles)
  766. {
  767. // Get all streams
  768. // If there's more than one we'll need to use the concat command
  769. if (playableStreamFiles.Length > 1)
  770. {
  771. var files = string.Join("|", playableStreamFiles);
  772. return string.Format("concat:\"{0}\"", files);
  773. }
  774. // Determine the input path for video files
  775. return string.Format("file:\"{0}\"", playableStreamFiles[0]);
  776. }
  777. /// <summary>
  778. /// Gets the bluray input argument.
  779. /// </summary>
  780. /// <param name="blurayRoot">The bluray root.</param>
  781. /// <returns>System.String.</returns>
  782. public string GetBlurayInputArgument(string blurayRoot)
  783. {
  784. return string.Format("bluray:\"{0}\"", blurayRoot);
  785. }
  786. /// <summary>
  787. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  788. /// </summary>
  789. public void Dispose()
  790. {
  791. Dispose(true);
  792. }
  793. /// <summary>
  794. /// Releases unmanaged and - optionally - managed resources.
  795. /// </summary>
  796. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  797. protected virtual void Dispose(bool dispose)
  798. {
  799. if (dispose)
  800. {
  801. _videoImageResourcePool.Dispose();
  802. }
  803. SetErrorMode(ErrorModes.SYSTEM_DEFAULT);
  804. }
  805. /// <summary>
  806. /// Sets the error mode.
  807. /// </summary>
  808. /// <param name="uMode">The u mode.</param>
  809. /// <returns>ErrorModes.</returns>
  810. [DllImport("kernel32.dll")]
  811. static extern ErrorModes SetErrorMode(ErrorModes uMode);
  812. /// <summary>
  813. /// Enum ErrorModes
  814. /// </summary>
  815. [Flags]
  816. public enum ErrorModes : uint
  817. {
  818. /// <summary>
  819. /// The SYSTE m_ DEFAULT
  820. /// </summary>
  821. SYSTEM_DEFAULT = 0x0,
  822. /// <summary>
  823. /// The SE m_ FAILCRITICALERRORS
  824. /// </summary>
  825. SEM_FAILCRITICALERRORS = 0x0001,
  826. /// <summary>
  827. /// The SE m_ NOALIGNMENTFAULTEXCEPT
  828. /// </summary>
  829. SEM_NOALIGNMENTFAULTEXCEPT = 0x0004,
  830. /// <summary>
  831. /// The SE m_ NOGPFAULTERRORBOX
  832. /// </summary>
  833. SEM_NOGPFAULTERRORBOX = 0x0002,
  834. /// <summary>
  835. /// The SE m_ NOOPENFILEERRORBOX
  836. /// </summary>
  837. SEM_NOOPENFILEERRORBOX = 0x8000
  838. }
  839. }
  840. }