FFMpegManager.cs 42 KB

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