FFMpegManager.cs 36 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010
  1. using MediaBrowser.Common.Extensions;
  2. using MediaBrowser.Common.IO;
  3. using MediaBrowser.Common.Kernel;
  4. using MediaBrowser.Common.Serialization;
  5. using MediaBrowser.Controller.Entities;
  6. using MediaBrowser.Controller.Entities.Audio;
  7. using MediaBrowser.Model.Entities;
  8. using MediaBrowser.Model.IO;
  9. using MediaBrowser.Model.Logging;
  10. using System;
  11. using System.Collections.Generic;
  12. using System.ComponentModel;
  13. using System.Diagnostics;
  14. using System.IO;
  15. using System.Linq;
  16. using System.Reflection;
  17. using System.Runtime.InteropServices;
  18. using System.Threading;
  19. using System.Threading.Tasks;
  20. namespace MediaBrowser.Controller.MediaInfo
  21. {
  22. /// <summary>
  23. /// Class FFMpegManager
  24. /// </summary>
  25. public class FFMpegManager : BaseManager<Kernel>
  26. {
  27. /// <summary>
  28. /// Gets or sets the video image cache.
  29. /// </summary>
  30. /// <value>The video image cache.</value>
  31. internal FileSystemRepository VideoImageCache { get; set; }
  32. /// <summary>
  33. /// Gets or sets the image cache.
  34. /// </summary>
  35. /// <value>The image cache.</value>
  36. internal FileSystemRepository AudioImageCache { get; set; }
  37. /// <summary>
  38. /// Gets or sets the subtitle cache.
  39. /// </summary>
  40. /// <value>The subtitle cache.</value>
  41. internal FileSystemRepository SubtitleCache { get; set; }
  42. /// <summary>
  43. /// Gets or sets the zip client.
  44. /// </summary>
  45. /// <value>The zip client.</value>
  46. private IZipClient ZipClient { get; set; }
  47. /// <summary>
  48. /// The _logger
  49. /// </summary>
  50. private readonly ILogger _logger;
  51. /// <summary>
  52. /// Initializes a new instance of the <see cref="FFMpegManager" /> class.
  53. /// </summary>
  54. /// <param name="kernel">The kernel.</param>
  55. /// <param name="zipClient">The zip client.</param>
  56. /// <param name="logger">The logger.</param>
  57. /// <exception cref="System.ArgumentNullException">zipClient</exception>
  58. public FFMpegManager(Kernel kernel, IZipClient zipClient, ILogger logger)
  59. : base(kernel)
  60. {
  61. if (zipClient == null)
  62. {
  63. throw new ArgumentNullException("zipClient");
  64. }
  65. _logger = logger;
  66. ZipClient = zipClient;
  67. // Not crazy about this but it's the only way to suppress ffmpeg crash dialog boxes
  68. SetErrorMode(ErrorModes.SEM_FAILCRITICALERRORS | ErrorModes.SEM_NOALIGNMENTFAULTEXCEPT | ErrorModes.SEM_NOGPFAULTERRORBOX | ErrorModes.SEM_NOOPENFILEERRORBOX);
  69. VideoImageCache = new FileSystemRepository(VideoImagesDataPath);
  70. AudioImageCache = new FileSystemRepository(AudioImagesDataPath);
  71. SubtitleCache = new FileSystemRepository(SubtitleCachePath);
  72. Task.Run(() => VersionedDirectoryPath = GetVersionedDirectoryPath());
  73. }
  74. /// <summary>
  75. /// Releases unmanaged and - optionally - managed resources.
  76. /// </summary>
  77. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  78. protected override void Dispose(bool dispose)
  79. {
  80. if (dispose)
  81. {
  82. SetErrorMode(ErrorModes.SYSTEM_DEFAULT);
  83. AudioImageCache.Dispose();
  84. VideoImageCache.Dispose();
  85. }
  86. base.Dispose(dispose);
  87. }
  88. /// <summary>
  89. /// The FF probe resource pool count
  90. /// </summary>
  91. private const int FFProbeResourcePoolCount = 4;
  92. /// <summary>
  93. /// The audio image resource pool count
  94. /// </summary>
  95. private const int AudioImageResourcePoolCount = 4;
  96. /// <summary>
  97. /// The video image resource pool count
  98. /// </summary>
  99. private const int VideoImageResourcePoolCount = 2;
  100. /// <summary>
  101. /// The FF probe resource pool
  102. /// </summary>
  103. private readonly SemaphoreSlim FFProbeResourcePool = new SemaphoreSlim(FFProbeResourcePoolCount, FFProbeResourcePoolCount);
  104. /// <summary>
  105. /// The audio image resource pool
  106. /// </summary>
  107. private readonly SemaphoreSlim AudioImageResourcePool = new SemaphoreSlim(AudioImageResourcePoolCount, AudioImageResourcePoolCount);
  108. /// <summary>
  109. /// The video image resource pool
  110. /// </summary>
  111. private readonly SemaphoreSlim VideoImageResourcePool = new SemaphoreSlim(VideoImageResourcePoolCount, VideoImageResourcePoolCount);
  112. /// <summary>
  113. /// Gets or sets the versioned directory path.
  114. /// </summary>
  115. /// <value>The versioned directory path.</value>
  116. private string VersionedDirectoryPath { get; set; }
  117. /// <summary>
  118. /// Gets the FFMPEG version.
  119. /// </summary>
  120. /// <value>The FFMPEG version.</value>
  121. public string FFMpegVersion
  122. {
  123. get { return Path.GetFileNameWithoutExtension(VersionedDirectoryPath); }
  124. }
  125. /// <summary>
  126. /// The _ FF MPEG path
  127. /// </summary>
  128. private string _FFMpegPath;
  129. /// <summary>
  130. /// Gets the path to ffmpeg.exe
  131. /// </summary>
  132. /// <value>The FF MPEG path.</value>
  133. public string FFMpegPath
  134. {
  135. get
  136. {
  137. return _FFMpegPath ?? (_FFMpegPath = Path.Combine(VersionedDirectoryPath, "ffmpeg.exe"));
  138. }
  139. }
  140. /// <summary>
  141. /// The _ FF probe path
  142. /// </summary>
  143. private string _FFProbePath;
  144. /// <summary>
  145. /// Gets the path to ffprobe.exe
  146. /// </summary>
  147. /// <value>The FF probe path.</value>
  148. public string FFProbePath
  149. {
  150. get
  151. {
  152. return _FFProbePath ?? (_FFProbePath = Path.Combine(VersionedDirectoryPath, "ffprobe.exe"));
  153. }
  154. }
  155. /// <summary>
  156. /// The _video images data path
  157. /// </summary>
  158. private string _videoImagesDataPath;
  159. /// <summary>
  160. /// Gets the video images data path.
  161. /// </summary>
  162. /// <value>The video images data path.</value>
  163. public string VideoImagesDataPath
  164. {
  165. get
  166. {
  167. if (_videoImagesDataPath == null)
  168. {
  169. _videoImagesDataPath = Path.Combine(Kernel.ApplicationPaths.DataPath, "ffmpeg-video-images");
  170. if (!Directory.Exists(_videoImagesDataPath))
  171. {
  172. Directory.CreateDirectory(_videoImagesDataPath);
  173. }
  174. }
  175. return _videoImagesDataPath;
  176. }
  177. }
  178. /// <summary>
  179. /// The _audio images data path
  180. /// </summary>
  181. private string _audioImagesDataPath;
  182. /// <summary>
  183. /// Gets the audio images data path.
  184. /// </summary>
  185. /// <value>The audio images data path.</value>
  186. public string AudioImagesDataPath
  187. {
  188. get
  189. {
  190. if (_audioImagesDataPath == null)
  191. {
  192. _audioImagesDataPath = Path.Combine(Kernel.ApplicationPaths.DataPath, "ffmpeg-audio-images");
  193. if (!Directory.Exists(_audioImagesDataPath))
  194. {
  195. Directory.CreateDirectory(_audioImagesDataPath);
  196. }
  197. }
  198. return _audioImagesDataPath;
  199. }
  200. }
  201. /// <summary>
  202. /// The _subtitle cache path
  203. /// </summary>
  204. private string _subtitleCachePath;
  205. /// <summary>
  206. /// Gets the subtitle cache path.
  207. /// </summary>
  208. /// <value>The subtitle cache path.</value>
  209. public string SubtitleCachePath
  210. {
  211. get
  212. {
  213. if (_subtitleCachePath == null)
  214. {
  215. _subtitleCachePath = Path.Combine(Kernel.ApplicationPaths.CachePath, "ffmpeg-subtitles");
  216. if (!Directory.Exists(_subtitleCachePath))
  217. {
  218. Directory.CreateDirectory(_subtitleCachePath);
  219. }
  220. }
  221. return _subtitleCachePath;
  222. }
  223. }
  224. /// <summary>
  225. /// Gets the versioned directory path.
  226. /// </summary>
  227. /// <returns>System.String.</returns>
  228. private string GetVersionedDirectoryPath()
  229. {
  230. var assembly = GetType().Assembly;
  231. const string prefix = "MediaBrowser.Controller.MediaInfo.";
  232. const string srch = prefix + "ffmpeg";
  233. var resource = assembly.GetManifestResourceNames().First(r => r.StartsWith(srch));
  234. var filename = resource.Substring(resource.IndexOf(prefix, StringComparison.OrdinalIgnoreCase) + prefix.Length);
  235. var versionedDirectoryPath = Path.Combine(Kernel.ApplicationPaths.MediaToolsPath, Path.GetFileNameWithoutExtension(filename));
  236. if (!Directory.Exists(versionedDirectoryPath))
  237. {
  238. Directory.CreateDirectory(versionedDirectoryPath);
  239. }
  240. ExtractTools(assembly, resource, versionedDirectoryPath);
  241. return versionedDirectoryPath;
  242. }
  243. /// <summary>
  244. /// Extracts the tools.
  245. /// </summary>
  246. /// <param name="assembly">The assembly.</param>
  247. /// <param name="zipFileResourcePath">The zip file resource path.</param>
  248. /// <param name="targetPath">The target path.</param>
  249. private void ExtractTools(Assembly assembly, string zipFileResourcePath, string targetPath)
  250. {
  251. using (var resourceStream = assembly.GetManifestResourceStream(zipFileResourcePath))
  252. {
  253. ZipClient.ExtractAll(resourceStream, targetPath, false);
  254. }
  255. }
  256. /// <summary>
  257. /// Gets the probe size argument.
  258. /// </summary>
  259. /// <param name="item">The item.</param>
  260. /// <returns>System.String.</returns>
  261. public string GetProbeSizeArgument(BaseItem item)
  262. {
  263. var video = item as Video;
  264. return video != null ? GetProbeSizeArgument(video.VideoType, video.IsoType) : string.Empty;
  265. }
  266. /// <summary>
  267. /// Gets the probe size argument.
  268. /// </summary>
  269. /// <param name="videoType">Type of the video.</param>
  270. /// <param name="isoType">Type of the iso.</param>
  271. /// <returns>System.String.</returns>
  272. public string GetProbeSizeArgument(VideoType videoType, IsoType? isoType)
  273. {
  274. if (videoType == VideoType.Dvd || (isoType.HasValue && isoType.Value == IsoType.Dvd))
  275. {
  276. return "-probesize 1G -analyzeduration 200M";
  277. }
  278. return string.Empty;
  279. }
  280. /// <summary>
  281. /// Runs FFProbe against a BaseItem
  282. /// </summary>
  283. /// <param name="item">The item.</param>
  284. /// <param name="inputPath">The input path.</param>
  285. /// <param name="lastDateModified">The last date modified.</param>
  286. /// <param name="cache">The cache.</param>
  287. /// <param name="cancellationToken">The cancellation token.</param>
  288. /// <returns>Task{FFProbeResult}.</returns>
  289. /// <exception cref="System.ArgumentNullException">item</exception>
  290. public Task<FFProbeResult> RunFFProbe(BaseItem item, string inputPath, DateTime lastDateModified, FileSystemRepository cache, CancellationToken cancellationToken)
  291. {
  292. if (string.IsNullOrEmpty(inputPath))
  293. {
  294. throw new ArgumentNullException("inputPath");
  295. }
  296. if (cache == null)
  297. {
  298. throw new ArgumentNullException("cache");
  299. }
  300. // Put the ffmpeg version into the cache name so that it's unique per-version
  301. // We don't want to try and deserialize data based on an old version, which could potentially fail
  302. var resourceName = item.Id + "_" + lastDateModified.Ticks + "_" + FFMpegVersion;
  303. // Forumulate the cache file path
  304. var cacheFilePath = cache.GetResourcePath(resourceName, ".pb");
  305. cancellationToken.ThrowIfCancellationRequested();
  306. // Avoid File.Exists by just trying to deserialize
  307. try
  308. {
  309. return Task.FromResult(Kernel.ProtobufSerializer.DeserializeFromFile<FFProbeResult>(cacheFilePath));
  310. }
  311. catch (FileNotFoundException)
  312. {
  313. var extractChapters = false;
  314. var video = item as Video;
  315. var probeSizeArgument = string.Empty;
  316. if (video != null)
  317. {
  318. extractChapters = true;
  319. probeSizeArgument = GetProbeSizeArgument(video.VideoType, video.IsoType);
  320. }
  321. return RunFFProbeInternal(inputPath, extractChapters, cacheFilePath, probeSizeArgument, cancellationToken);
  322. }
  323. }
  324. /// <summary>
  325. /// Runs FFProbe against a BaseItem
  326. /// </summary>
  327. /// <param name="inputPath">The input path.</param>
  328. /// <param name="extractChapters">if set to <c>true</c> [extract chapters].</param>
  329. /// <param name="cacheFile">The cache file.</param>
  330. /// <param name="probeSizeArgument">The probe size argument.</param>
  331. /// <param name="cancellationToken">The cancellation token.</param>
  332. /// <returns>Task{FFProbeResult}.</returns>
  333. /// <exception cref="System.ApplicationException"></exception>
  334. private async Task<FFProbeResult> RunFFProbeInternal(string inputPath, bool extractChapters, string cacheFile, string probeSizeArgument, CancellationToken cancellationToken)
  335. {
  336. var process = new Process
  337. {
  338. StartInfo = new ProcessStartInfo
  339. {
  340. CreateNoWindow = true,
  341. UseShellExecute = false,
  342. // Must consume both or ffmpeg may hang due to deadlocks. See comments below.
  343. RedirectStandardOutput = true,
  344. RedirectStandardError = true,
  345. FileName = FFProbePath,
  346. Arguments = string.Format("{0} -i {1} -threads 0 -v info -print_format json -show_streams -show_format", probeSizeArgument, inputPath).Trim(),
  347. WindowStyle = ProcessWindowStyle.Hidden,
  348. ErrorDialog = false
  349. },
  350. EnableRaisingEvents = true
  351. };
  352. _logger.Debug("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments);
  353. process.Exited += ProcessExited;
  354. await FFProbeResourcePool.WaitAsync(cancellationToken).ConfigureAwait(false);
  355. FFProbeResult result;
  356. string standardError = null;
  357. try
  358. {
  359. process.Start();
  360. Task<string> standardErrorReadTask = null;
  361. // MUST read both stdout and stderr asynchronously or a deadlock may occurr
  362. if (extractChapters)
  363. {
  364. standardErrorReadTask = process.StandardError.ReadToEndAsync();
  365. }
  366. else
  367. {
  368. process.BeginErrorReadLine();
  369. }
  370. result = JsonSerializer.DeserializeFromStream<FFProbeResult>(process.StandardOutput.BaseStream);
  371. if (extractChapters)
  372. {
  373. standardError = await standardErrorReadTask.ConfigureAwait(false);
  374. }
  375. }
  376. catch
  377. {
  378. // Hate having to do this
  379. try
  380. {
  381. process.Kill();
  382. }
  383. catch (InvalidOperationException ex1)
  384. {
  385. _logger.ErrorException("Error killing ffprobe", ex1);
  386. }
  387. catch (Win32Exception ex1)
  388. {
  389. _logger.ErrorException("Error killing ffprobe", ex1);
  390. }
  391. throw;
  392. }
  393. finally
  394. {
  395. FFProbeResourcePool.Release();
  396. }
  397. if (result == null)
  398. {
  399. throw new ApplicationException(string.Format("FFProbe failed for {0}", inputPath));
  400. }
  401. cancellationToken.ThrowIfCancellationRequested();
  402. if (extractChapters && !string.IsNullOrEmpty(standardError))
  403. {
  404. AddChapters(result, standardError);
  405. }
  406. Kernel.ProtobufSerializer.SerializeToFile(result, cacheFile);
  407. return result;
  408. }
  409. /// <summary>
  410. /// Adds the chapters.
  411. /// </summary>
  412. /// <param name="result">The result.</param>
  413. /// <param name="standardError">The standard error.</param>
  414. private void AddChapters(FFProbeResult result, string standardError)
  415. {
  416. var lines = standardError.Split('\n').Select(l => l.TrimStart());
  417. var chapters = new List<ChapterInfo> { };
  418. ChapterInfo lastChapter = null;
  419. foreach (var line in lines)
  420. {
  421. if (line.StartsWith("Chapter", StringComparison.OrdinalIgnoreCase))
  422. {
  423. // Example:
  424. // Chapter #0.2: start 400.534, end 4565.435
  425. const string srch = "start ";
  426. var start = line.IndexOf(srch, StringComparison.OrdinalIgnoreCase);
  427. if (start == -1)
  428. {
  429. continue;
  430. }
  431. var subString = line.Substring(start + srch.Length);
  432. subString = subString.Substring(0, subString.IndexOf(','));
  433. double seconds;
  434. if (double.TryParse(subString, out seconds))
  435. {
  436. lastChapter = new ChapterInfo
  437. {
  438. StartPositionTicks = TimeSpan.FromSeconds(seconds).Ticks
  439. };
  440. chapters.Add(lastChapter);
  441. }
  442. }
  443. else if (line.StartsWith("title", StringComparison.OrdinalIgnoreCase))
  444. {
  445. if (lastChapter != null && string.IsNullOrEmpty(lastChapter.Name))
  446. {
  447. var index = line.IndexOf(':');
  448. if (index != -1)
  449. {
  450. lastChapter.Name = line.Substring(index + 1).Trim().TrimEnd('\r');
  451. }
  452. }
  453. }
  454. }
  455. result.Chapters = chapters;
  456. }
  457. /// <summary>
  458. /// The first chapter ticks
  459. /// </summary>
  460. private static long FirstChapterTicks = TimeSpan.FromSeconds(15).Ticks;
  461. /// <summary>
  462. /// Extracts the chapter images.
  463. /// </summary>
  464. /// <param name="video">The video.</param>
  465. /// <param name="cancellationToken">The cancellation token.</param>
  466. /// <param name="extractImages">if set to <c>true</c> [extract images].</param>
  467. /// <param name="saveItem">if set to <c>true</c> [save item].</param>
  468. /// <returns>Task.</returns>
  469. /// <exception cref="System.ArgumentNullException"></exception>
  470. public async Task PopulateChapterImages(Video video, CancellationToken cancellationToken, bool extractImages, bool saveItem)
  471. {
  472. if (video.Chapters == null)
  473. {
  474. throw new ArgumentNullException();
  475. }
  476. var changesMade = false;
  477. foreach (var chapter in video.Chapters)
  478. {
  479. var filename = video.Id + "_" + video.DateModified.Ticks + "_" + chapter.StartPositionTicks;
  480. var path = VideoImageCache.GetResourcePath(filename, ".jpg");
  481. if (!VideoImageCache.ContainsFilePath(path))
  482. {
  483. if (extractImages)
  484. {
  485. // Disable for now on folder rips
  486. if (video.VideoType != VideoType.VideoFile)
  487. {
  488. continue;
  489. }
  490. // Add some time for the first chapter to make sure we don't end up with a black image
  491. var time = chapter.StartPositionTicks == 0 ? TimeSpan.FromTicks(Math.Min(FirstChapterTicks, video.RunTimeTicks ?? 0)) : TimeSpan.FromTicks(chapter.StartPositionTicks);
  492. var success = await ExtractImage(GetInputArgument(video), time, path, cancellationToken).ConfigureAwait(false);
  493. if (success)
  494. {
  495. chapter.ImagePath = path;
  496. changesMade = true;
  497. }
  498. }
  499. }
  500. else if (!string.Equals(path, chapter.ImagePath, StringComparison.OrdinalIgnoreCase))
  501. {
  502. chapter.ImagePath = path;
  503. changesMade = true;
  504. }
  505. }
  506. if (saveItem && changesMade)
  507. {
  508. await Kernel.ItemRepository.SaveItem(video, CancellationToken.None).ConfigureAwait(false);
  509. }
  510. }
  511. /// <summary>
  512. /// Extracts an image from an Audio file and returns a Task whose result indicates whether it was successful or not
  513. /// </summary>
  514. /// <param name="input">The input.</param>
  515. /// <param name="outputPath">The output path.</param>
  516. /// <param name="cancellationToken">The cancellation token.</param>
  517. /// <returns>Task{System.Boolean}.</returns>
  518. /// <exception cref="System.ArgumentNullException">input</exception>
  519. public async Task<bool> ExtractImage(Audio input, string outputPath, CancellationToken cancellationToken)
  520. {
  521. if (input == null)
  522. {
  523. throw new ArgumentNullException("input");
  524. }
  525. if (string.IsNullOrEmpty(outputPath))
  526. {
  527. throw new ArgumentNullException("outputPath");
  528. }
  529. var process = new Process
  530. {
  531. StartInfo = new ProcessStartInfo
  532. {
  533. CreateNoWindow = true,
  534. UseShellExecute = false,
  535. FileName = FFMpegPath,
  536. Arguments = string.Format("-i {0} -threads 0 -v quiet -f image2 \"{1}\"", GetInputArgument(input), outputPath),
  537. WindowStyle = ProcessWindowStyle.Hidden,
  538. ErrorDialog = false
  539. }
  540. };
  541. await AudioImageResourcePool.WaitAsync(cancellationToken).ConfigureAwait(false);
  542. await process.RunAsync().ConfigureAwait(false);
  543. AudioImageResourcePool.Release();
  544. var exitCode = process.ExitCode;
  545. process.Dispose();
  546. if (exitCode != -1 && File.Exists(outputPath))
  547. {
  548. return true;
  549. }
  550. _logger.Error("ffmpeg audio image extraction failed for {0}", input.Path);
  551. return false;
  552. }
  553. /// <summary>
  554. /// Determines whether [is subtitle cached] [the specified input].
  555. /// </summary>
  556. /// <param name="input">The input.</param>
  557. /// <param name="subtitleStreamIndex">Index of the subtitle stream.</param>
  558. /// <param name="outputExtension">The output extension.</param>
  559. /// <returns><c>true</c> if [is subtitle cached] [the specified input]; otherwise, <c>false</c>.</returns>
  560. public bool IsSubtitleCached(Video input, int subtitleStreamIndex, string outputExtension)
  561. {
  562. return SubtitleCache.ContainsFilePath(GetSubtitleCachePath(input, subtitleStreamIndex, outputExtension));
  563. }
  564. /// <summary>
  565. /// Gets the subtitle cache path.
  566. /// </summary>
  567. /// <param name="input">The input.</param>
  568. /// <param name="subtitleStreamIndex">Index of the subtitle stream.</param>
  569. /// <param name="outputExtension">The output extension.</param>
  570. /// <returns>System.String.</returns>
  571. public string GetSubtitleCachePath(Video input, int subtitleStreamIndex, string outputExtension)
  572. {
  573. return SubtitleCache.GetResourcePath(input.Id + "_" + subtitleStreamIndex + "_" + input.DateModified.Ticks, outputExtension);
  574. }
  575. /// <summary>
  576. /// Extracts the text subtitle.
  577. /// </summary>
  578. /// <param name="input">The input.</param>
  579. /// <param name="subtitleStreamIndex">Index of the subtitle stream.</param>
  580. /// <param name="outputPath">The output path.</param>
  581. /// <param name="cancellationToken">The cancellation token.</param>
  582. /// <returns>Task{System.Boolean}.</returns>
  583. /// <exception cref="System.ArgumentNullException">input</exception>
  584. public async Task<bool> ExtractTextSubtitle(Video input, int subtitleStreamIndex, string outputPath, CancellationToken cancellationToken)
  585. {
  586. if (input == null)
  587. {
  588. throw new ArgumentNullException("input");
  589. }
  590. if (cancellationToken == null)
  591. {
  592. throw new ArgumentNullException("cancellationToken");
  593. }
  594. var process = new Process
  595. {
  596. StartInfo = new ProcessStartInfo
  597. {
  598. CreateNoWindow = true,
  599. UseShellExecute = false,
  600. FileName = FFMpegPath,
  601. Arguments = string.Format("-i {0} -map 0:{1} -an -vn -c:s ass \"{2}\"", GetInputArgument(input), subtitleStreamIndex, outputPath),
  602. WindowStyle = ProcessWindowStyle.Hidden,
  603. ErrorDialog = false
  604. }
  605. };
  606. _logger.Debug("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments);
  607. await AudioImageResourcePool.WaitAsync(cancellationToken).ConfigureAwait(false);
  608. await process.RunAsync().ConfigureAwait(false);
  609. AudioImageResourcePool.Release();
  610. var exitCode = process.ExitCode;
  611. process.Dispose();
  612. if (exitCode != -1 && File.Exists(outputPath))
  613. {
  614. return true;
  615. }
  616. _logger.Error("ffmpeg subtitle extraction failed for {0}", input.Path);
  617. return false;
  618. }
  619. /// <summary>
  620. /// Converts the text subtitle.
  621. /// </summary>
  622. /// <param name="mediaStream">The media stream.</param>
  623. /// <param name="outputPath">The output path.</param>
  624. /// <param name="cancellationToken">The cancellation token.</param>
  625. /// <returns>Task{System.Boolean}.</returns>
  626. /// <exception cref="System.ArgumentNullException">mediaStream</exception>
  627. /// <exception cref="System.ArgumentException">The given MediaStream is not an external subtitle stream</exception>
  628. public async Task<bool> ConvertTextSubtitle(MediaStream mediaStream, string outputPath, CancellationToken cancellationToken)
  629. {
  630. if (mediaStream == null)
  631. {
  632. throw new ArgumentNullException("mediaStream");
  633. }
  634. if (!mediaStream.IsExternal || string.IsNullOrEmpty(mediaStream.Path))
  635. {
  636. throw new ArgumentException("The given MediaStream is not an external subtitle stream");
  637. }
  638. var process = new Process
  639. {
  640. StartInfo = new ProcessStartInfo
  641. {
  642. CreateNoWindow = true,
  643. UseShellExecute = false,
  644. FileName = FFMpegPath,
  645. Arguments = string.Format("-i \"{0}\" \"{1}\"", mediaStream.Path, outputPath),
  646. WindowStyle = ProcessWindowStyle.Hidden,
  647. ErrorDialog = false
  648. }
  649. };
  650. _logger.Debug("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments);
  651. await AudioImageResourcePool.WaitAsync(cancellationToken).ConfigureAwait(false);
  652. await process.RunAsync().ConfigureAwait(false);
  653. AudioImageResourcePool.Release();
  654. var exitCode = process.ExitCode;
  655. process.Dispose();
  656. if (exitCode != -1 && File.Exists(outputPath))
  657. {
  658. return true;
  659. }
  660. _logger.Error("ffmpeg subtitle conversion failed for {0}", mediaStream.Path);
  661. return false;
  662. }
  663. /// <summary>
  664. /// Extracts an image from a Video and returns a Task whose result indicates whether it was successful or not
  665. /// </summary>
  666. /// <param name="inputPath">The input path.</param>
  667. /// <param name="offset">The offset.</param>
  668. /// <param name="outputPath">The output path.</param>
  669. /// <param name="cancellationToken">The cancellation token.</param>
  670. /// <returns>Task{System.Boolean}.</returns>
  671. /// <exception cref="System.ArgumentNullException">video</exception>
  672. public async Task<bool> ExtractImage(string inputPath, TimeSpan offset, string outputPath, CancellationToken cancellationToken)
  673. {
  674. if (string.IsNullOrEmpty(inputPath))
  675. {
  676. throw new ArgumentNullException("inputPath");
  677. }
  678. if (string.IsNullOrEmpty(outputPath))
  679. {
  680. throw new ArgumentNullException("outputPath");
  681. }
  682. var process = new Process
  683. {
  684. StartInfo = new ProcessStartInfo
  685. {
  686. CreateNoWindow = true,
  687. UseShellExecute = false,
  688. FileName = FFMpegPath,
  689. Arguments = string.Format("-ss {0} -i {1} -threads 0 -v quiet -t 1 -f image2 \"{2}\"", Convert.ToInt32(offset.TotalSeconds), inputPath, outputPath),
  690. WindowStyle = ProcessWindowStyle.Hidden,
  691. ErrorDialog = false
  692. }
  693. };
  694. await VideoImageResourcePool.WaitAsync(cancellationToken).ConfigureAwait(false);
  695. process.Start();
  696. var ranToCompletion = process.WaitForExit(10000);
  697. if (!ranToCompletion)
  698. {
  699. try
  700. {
  701. _logger.Info("Killing ffmpeg process");
  702. process.Kill();
  703. process.WaitForExit(1000);
  704. }
  705. catch (Win32Exception ex)
  706. {
  707. _logger.ErrorException("Error killing process", ex);
  708. }
  709. catch (InvalidOperationException ex)
  710. {
  711. _logger.ErrorException("Error killing process", ex);
  712. }
  713. catch (NotSupportedException ex)
  714. {
  715. _logger.ErrorException("Error killing process", ex);
  716. }
  717. }
  718. VideoImageResourcePool.Release();
  719. var exitCode = ranToCompletion ? process.ExitCode : -1;
  720. process.Dispose();
  721. if (exitCode == -1)
  722. {
  723. if (File.Exists(outputPath))
  724. {
  725. try
  726. {
  727. _logger.Info("Deleting extracted image due to failure: ", outputPath);
  728. File.Delete(outputPath);
  729. }
  730. catch (IOException ex)
  731. {
  732. _logger.ErrorException("Error deleting extracted image {0}", ex, outputPath);
  733. }
  734. }
  735. }
  736. else
  737. {
  738. if (File.Exists(outputPath))
  739. {
  740. return true;
  741. }
  742. }
  743. _logger.Error("ffmpeg video image extraction failed for {0}", inputPath);
  744. return false;
  745. }
  746. /// <summary>
  747. /// Gets the input argument.
  748. /// </summary>
  749. /// <param name="item">The item.</param>
  750. /// <returns>System.String.</returns>
  751. public string GetInputArgument(BaseItem item)
  752. {
  753. var video = item as Video;
  754. if (video != null)
  755. {
  756. if (video.VideoType == VideoType.BluRay)
  757. {
  758. return GetBlurayInputArgument(video.Path);
  759. }
  760. if (video.VideoType == VideoType.Dvd)
  761. {
  762. return GetDvdInputArgument(video.GetPlayableStreamFiles());
  763. }
  764. }
  765. return string.Format("file:\"{0}\"", item.Path);
  766. }
  767. /// <summary>
  768. /// Gets the input argument.
  769. /// </summary>
  770. /// <param name="item">The item.</param>
  771. /// <param name="mount">The mount.</param>
  772. /// <returns>System.String.</returns>
  773. public string GetInputArgument(Video item, IIsoMount mount)
  774. {
  775. if (item.VideoType == VideoType.Iso && item.IsoType.HasValue)
  776. {
  777. if (item.IsoType.Value == IsoType.BluRay)
  778. {
  779. return GetBlurayInputArgument(mount.MountedPath);
  780. }
  781. if (item.IsoType.Value == IsoType.Dvd)
  782. {
  783. return GetDvdInputArgument(item.GetPlayableStreamFiles(mount.MountedPath));
  784. }
  785. }
  786. return GetInputArgument(item);
  787. }
  788. /// <summary>
  789. /// Gets the bluray input argument.
  790. /// </summary>
  791. /// <param name="blurayRoot">The bluray root.</param>
  792. /// <returns>System.String.</returns>
  793. public string GetBlurayInputArgument(string blurayRoot)
  794. {
  795. return string.Format("bluray:\"{0}\"", blurayRoot);
  796. }
  797. /// <summary>
  798. /// Gets the DVD input argument.
  799. /// </summary>
  800. /// <param name="playableStreamFiles">The playable stream files.</param>
  801. /// <returns>System.String.</returns>
  802. public string GetDvdInputArgument(IEnumerable<string> playableStreamFiles)
  803. {
  804. // Get all streams
  805. var streamFilePaths = (playableStreamFiles ?? new string[] { }).ToArray();
  806. // If there's more than one we'll need to use the concat command
  807. if (streamFilePaths.Length > 1)
  808. {
  809. var files = string.Join("|", streamFilePaths);
  810. return string.Format("concat:\"{0}\"", files);
  811. }
  812. // Determine the input path for video files
  813. return string.Format("file:\"{0}\"", streamFilePaths[0]);
  814. }
  815. /// <summary>
  816. /// Processes the exited.
  817. /// </summary>
  818. /// <param name="sender">The sender.</param>
  819. /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
  820. void ProcessExited(object sender, EventArgs e)
  821. {
  822. ((Process)sender).Dispose();
  823. }
  824. /// <summary>
  825. /// Sets the error mode.
  826. /// </summary>
  827. /// <param name="uMode">The u mode.</param>
  828. /// <returns>ErrorModes.</returns>
  829. [DllImport("kernel32.dll")]
  830. static extern ErrorModes SetErrorMode(ErrorModes uMode);
  831. /// <summary>
  832. /// Enum ErrorModes
  833. /// </summary>
  834. [Flags]
  835. public enum ErrorModes : uint
  836. {
  837. /// <summary>
  838. /// The SYSTE m_ DEFAULT
  839. /// </summary>
  840. SYSTEM_DEFAULT = 0x0,
  841. /// <summary>
  842. /// The SE m_ FAILCRITICALERRORS
  843. /// </summary>
  844. SEM_FAILCRITICALERRORS = 0x0001,
  845. /// <summary>
  846. /// The SE m_ NOALIGNMENTFAULTEXCEPT
  847. /// </summary>
  848. SEM_NOALIGNMENTFAULTEXCEPT = 0x0004,
  849. /// <summary>
  850. /// The SE m_ NOGPFAULTERRORBOX
  851. /// </summary>
  852. SEM_NOGPFAULTERRORBOX = 0x0002,
  853. /// <summary>
  854. /// The SE m_ NOOPENFILEERRORBOX
  855. /// </summary>
  856. SEM_NOOPENFILEERRORBOX = 0x8000
  857. }
  858. }
  859. }