FFMpegManager.cs 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160
  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. }
  613. }
  614. else if (!string.Equals(path, chapter.ImagePath, StringComparison.OrdinalIgnoreCase))
  615. {
  616. chapter.ImagePath = path;
  617. changesMade = true;
  618. }
  619. }
  620. if (saveItem && changesMade)
  621. {
  622. await _kernel.ItemRepository.SaveItem(video, CancellationToken.None).ConfigureAwait(false);
  623. }
  624. }
  625. /// <summary>
  626. /// Extracts an image from an Audio file and returns a Task whose result indicates whether it was successful or not
  627. /// </summary>
  628. /// <param name="input">The input.</param>
  629. /// <param name="outputPath">The output path.</param>
  630. /// <param name="cancellationToken">The cancellation token.</param>
  631. /// <returns>Task{System.Boolean}.</returns>
  632. /// <exception cref="System.ArgumentNullException">input</exception>
  633. public async Task<bool> ExtractImage(Audio input, string outputPath, CancellationToken cancellationToken)
  634. {
  635. if (input == null)
  636. {
  637. throw new ArgumentNullException("input");
  638. }
  639. if (string.IsNullOrEmpty(outputPath))
  640. {
  641. throw new ArgumentNullException("outputPath");
  642. }
  643. var process = new Process
  644. {
  645. StartInfo = new ProcessStartInfo
  646. {
  647. CreateNoWindow = true,
  648. UseShellExecute = false,
  649. FileName = FFMpegPath,
  650. Arguments = string.Format("-i {0} -threads 0 -v quiet -f image2 \"{1}\"", GetInputArgument(input), outputPath),
  651. WindowStyle = ProcessWindowStyle.Hidden,
  652. ErrorDialog = false
  653. }
  654. };
  655. await AudioImageResourcePool.WaitAsync(cancellationToken).ConfigureAwait(false);
  656. await RunAsync(process).ConfigureAwait(false);
  657. AudioImageResourcePool.Release();
  658. var exitCode = process.ExitCode;
  659. process.Dispose();
  660. if (exitCode != -1 && File.Exists(outputPath))
  661. {
  662. return true;
  663. }
  664. _logger.Error("ffmpeg audio image extraction failed for {0}", input.Path);
  665. return false;
  666. }
  667. /// <summary>
  668. /// Determines whether [is subtitle cached] [the specified input].
  669. /// </summary>
  670. /// <param name="input">The input.</param>
  671. /// <param name="subtitleStreamIndex">Index of the subtitle stream.</param>
  672. /// <param name="outputExtension">The output extension.</param>
  673. /// <returns><c>true</c> if [is subtitle cached] [the specified input]; otherwise, <c>false</c>.</returns>
  674. public bool IsSubtitleCached(Video input, int subtitleStreamIndex, string outputExtension)
  675. {
  676. return SubtitleCache.ContainsFilePath(GetSubtitleCachePath(input, subtitleStreamIndex, outputExtension));
  677. }
  678. /// <summary>
  679. /// Gets the subtitle cache path.
  680. /// </summary>
  681. /// <param name="input">The input.</param>
  682. /// <param name="subtitleStreamIndex">Index of the subtitle stream.</param>
  683. /// <param name="outputExtension">The output extension.</param>
  684. /// <returns>System.String.</returns>
  685. public string GetSubtitleCachePath(Video input, int subtitleStreamIndex, string outputExtension)
  686. {
  687. return SubtitleCache.GetResourcePath(input.Id + "_" + subtitleStreamIndex + "_" + input.DateModified.Ticks, outputExtension);
  688. }
  689. /// <summary>
  690. /// Extracts the text subtitle.
  691. /// </summary>
  692. /// <param name="input">The input.</param>
  693. /// <param name="subtitleStreamIndex">Index of the subtitle stream.</param>
  694. /// <param name="outputPath">The output path.</param>
  695. /// <param name="cancellationToken">The cancellation token.</param>
  696. /// <returns>Task{System.Boolean}.</returns>
  697. /// <exception cref="System.ArgumentNullException">input</exception>
  698. public async Task<bool> ExtractTextSubtitle(Video input, int subtitleStreamIndex, string outputPath, CancellationToken cancellationToken)
  699. {
  700. if (input == null)
  701. {
  702. throw new ArgumentNullException("input");
  703. }
  704. if (cancellationToken == null)
  705. {
  706. throw new ArgumentNullException("cancellationToken");
  707. }
  708. var process = new Process
  709. {
  710. StartInfo = new ProcessStartInfo
  711. {
  712. CreateNoWindow = true,
  713. UseShellExecute = false,
  714. FileName = FFMpegPath,
  715. Arguments = string.Format("-i {0} -map 0:{1} -an -vn -c:s ass \"{2}\"", GetInputArgument(input), subtitleStreamIndex, outputPath),
  716. WindowStyle = ProcessWindowStyle.Hidden,
  717. ErrorDialog = false
  718. }
  719. };
  720. _logger.Debug("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments);
  721. await AudioImageResourcePool.WaitAsync(cancellationToken).ConfigureAwait(false);
  722. await RunAsync(process).ConfigureAwait(false);
  723. AudioImageResourcePool.Release();
  724. var exitCode = process.ExitCode;
  725. process.Dispose();
  726. if (exitCode != -1 && File.Exists(outputPath))
  727. {
  728. return true;
  729. }
  730. _logger.Error("ffmpeg subtitle extraction failed for {0}", input.Path);
  731. return false;
  732. }
  733. /// <summary>
  734. /// Converts the text subtitle.
  735. /// </summary>
  736. /// <param name="mediaStream">The media stream.</param>
  737. /// <param name="outputPath">The output path.</param>
  738. /// <param name="cancellationToken">The cancellation token.</param>
  739. /// <returns>Task{System.Boolean}.</returns>
  740. /// <exception cref="System.ArgumentNullException">mediaStream</exception>
  741. /// <exception cref="System.ArgumentException">The given MediaStream is not an external subtitle stream</exception>
  742. public async Task<bool> ConvertTextSubtitle(MediaStream mediaStream, string outputPath, CancellationToken cancellationToken)
  743. {
  744. if (mediaStream == null)
  745. {
  746. throw new ArgumentNullException("mediaStream");
  747. }
  748. if (!mediaStream.IsExternal || string.IsNullOrEmpty(mediaStream.Path))
  749. {
  750. throw new ArgumentException("The given MediaStream is not an external subtitle stream");
  751. }
  752. var process = new Process
  753. {
  754. StartInfo = new ProcessStartInfo
  755. {
  756. CreateNoWindow = true,
  757. UseShellExecute = false,
  758. FileName = FFMpegPath,
  759. Arguments = string.Format("-i \"{0}\" \"{1}\"", mediaStream.Path, outputPath),
  760. WindowStyle = ProcessWindowStyle.Hidden,
  761. ErrorDialog = false
  762. }
  763. };
  764. _logger.Debug("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments);
  765. await AudioImageResourcePool.WaitAsync(cancellationToken).ConfigureAwait(false);
  766. await RunAsync(process).ConfigureAwait(false);
  767. AudioImageResourcePool.Release();
  768. var exitCode = process.ExitCode;
  769. process.Dispose();
  770. if (exitCode != -1 && File.Exists(outputPath))
  771. {
  772. return true;
  773. }
  774. _logger.Error("ffmpeg subtitle conversion failed for {0}", mediaStream.Path);
  775. return false;
  776. }
  777. /// <summary>
  778. /// Extracts an image from a Video and returns a Task whose result indicates whether it was successful or not
  779. /// </summary>
  780. /// <param name="inputPath">The input path.</param>
  781. /// <param name="offset">The offset.</param>
  782. /// <param name="outputPath">The output path.</param>
  783. /// <param name="cancellationToken">The cancellation token.</param>
  784. /// <returns>Task{System.Boolean}.</returns>
  785. /// <exception cref="System.ArgumentNullException">video</exception>
  786. public async Task<bool> ExtractImage(string inputPath, TimeSpan offset, string outputPath, CancellationToken cancellationToken)
  787. {
  788. if (string.IsNullOrEmpty(inputPath))
  789. {
  790. throw new ArgumentNullException("inputPath");
  791. }
  792. if (string.IsNullOrEmpty(outputPath))
  793. {
  794. throw new ArgumentNullException("outputPath");
  795. }
  796. var process = new Process
  797. {
  798. StartInfo = new ProcessStartInfo
  799. {
  800. CreateNoWindow = true,
  801. UseShellExecute = false,
  802. FileName = FFMpegPath,
  803. 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),
  804. WindowStyle = ProcessWindowStyle.Hidden,
  805. ErrorDialog = false
  806. }
  807. };
  808. await VideoImageResourcePool.WaitAsync(cancellationToken).ConfigureAwait(false);
  809. process.Start();
  810. var ranToCompletion = process.WaitForExit(10000);
  811. if (!ranToCompletion)
  812. {
  813. try
  814. {
  815. _logger.Info("Killing ffmpeg process");
  816. process.Kill();
  817. process.WaitForExit(1000);
  818. }
  819. catch (Win32Exception ex)
  820. {
  821. _logger.ErrorException("Error killing process", ex);
  822. }
  823. catch (InvalidOperationException ex)
  824. {
  825. _logger.ErrorException("Error killing process", ex);
  826. }
  827. catch (NotSupportedException ex)
  828. {
  829. _logger.ErrorException("Error killing process", ex);
  830. }
  831. }
  832. VideoImageResourcePool.Release();
  833. var exitCode = ranToCompletion ? process.ExitCode : -1;
  834. process.Dispose();
  835. if (exitCode == -1)
  836. {
  837. if (File.Exists(outputPath))
  838. {
  839. try
  840. {
  841. _logger.Info("Deleting extracted image due to failure: ", outputPath);
  842. File.Delete(outputPath);
  843. }
  844. catch (IOException ex)
  845. {
  846. _logger.ErrorException("Error deleting extracted image {0}", ex, outputPath);
  847. }
  848. }
  849. }
  850. else
  851. {
  852. if (File.Exists(outputPath))
  853. {
  854. return true;
  855. }
  856. }
  857. _logger.Error("ffmpeg video image extraction failed for {0}", inputPath);
  858. return false;
  859. }
  860. /// <summary>
  861. /// Gets the input argument.
  862. /// </summary>
  863. /// <param name="item">The item.</param>
  864. /// <returns>System.String.</returns>
  865. public string GetInputArgument(BaseItem item)
  866. {
  867. var video = item as Video;
  868. if (video != null)
  869. {
  870. if (video.VideoType == VideoType.BluRay)
  871. {
  872. return GetBlurayInputArgument(video.Path);
  873. }
  874. if (video.VideoType == VideoType.Dvd)
  875. {
  876. return GetDvdInputArgument(video.GetPlayableStreamFiles());
  877. }
  878. }
  879. return string.Format("file:\"{0}\"", item.Path);
  880. }
  881. /// <summary>
  882. /// Gets the input argument.
  883. /// </summary>
  884. /// <param name="item">The item.</param>
  885. /// <param name="mount">The mount.</param>
  886. /// <returns>System.String.</returns>
  887. public string GetInputArgument(Video item, IIsoMount mount)
  888. {
  889. if (item.VideoType == VideoType.Iso && item.IsoType.HasValue)
  890. {
  891. if (item.IsoType.Value == IsoType.BluRay)
  892. {
  893. return GetBlurayInputArgument(mount.MountedPath);
  894. }
  895. if (item.IsoType.Value == IsoType.Dvd)
  896. {
  897. return GetDvdInputArgument(item.GetPlayableStreamFiles(mount.MountedPath));
  898. }
  899. }
  900. return GetInputArgument(item);
  901. }
  902. /// <summary>
  903. /// Gets the bluray input argument.
  904. /// </summary>
  905. /// <param name="blurayRoot">The bluray root.</param>
  906. /// <returns>System.String.</returns>
  907. public string GetBlurayInputArgument(string blurayRoot)
  908. {
  909. return string.Format("bluray:\"{0}\"", blurayRoot);
  910. }
  911. /// <summary>
  912. /// Gets the DVD input argument.
  913. /// </summary>
  914. /// <param name="playableStreamFiles">The playable stream files.</param>
  915. /// <returns>System.String.</returns>
  916. public string GetDvdInputArgument(IEnumerable<string> playableStreamFiles)
  917. {
  918. // Get all streams
  919. var streamFilePaths = (playableStreamFiles ?? new string[] { }).ToArray();
  920. // If there's more than one we'll need to use the concat command
  921. if (streamFilePaths.Length > 1)
  922. {
  923. var files = string.Join("|", streamFilePaths);
  924. return string.Format("concat:\"{0}\"", files);
  925. }
  926. // Determine the input path for video files
  927. return string.Format("file:\"{0}\"", streamFilePaths[0]);
  928. }
  929. /// <summary>
  930. /// Processes the exited.
  931. /// </summary>
  932. /// <param name="sender">The sender.</param>
  933. /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
  934. void ProcessExited(object sender, EventArgs e)
  935. {
  936. ((Process)sender).Dispose();
  937. }
  938. /// <summary>
  939. /// Provides a non-blocking method to start a process and wait asynchronously for it to exit
  940. /// </summary>
  941. /// <param name="process">The process.</param>
  942. /// <returns>Task{System.Boolean}.</returns>
  943. private static Task<bool> RunAsync(Process process)
  944. {
  945. var tcs = new TaskCompletionSource<bool>();
  946. process.EnableRaisingEvents = true;
  947. process.Exited += (sender, args) => tcs.SetResult(true);
  948. process.Start();
  949. return tcs.Task;
  950. }
  951. /// <summary>
  952. /// Sets the error mode.
  953. /// </summary>
  954. /// <param name="uMode">The u mode.</param>
  955. /// <returns>ErrorModes.</returns>
  956. [DllImport("kernel32.dll")]
  957. static extern ErrorModes SetErrorMode(ErrorModes uMode);
  958. /// <summary>
  959. /// Enum ErrorModes
  960. /// </summary>
  961. [Flags]
  962. public enum ErrorModes : uint
  963. {
  964. /// <summary>
  965. /// The SYSTE m_ DEFAULT
  966. /// </summary>
  967. SYSTEM_DEFAULT = 0x0,
  968. /// <summary>
  969. /// The SE m_ FAILCRITICALERRORS
  970. /// </summary>
  971. SEM_FAILCRITICALERRORS = 0x0001,
  972. /// <summary>
  973. /// The SE m_ NOALIGNMENTFAULTEXCEPT
  974. /// </summary>
  975. SEM_NOALIGNMENTFAULTEXCEPT = 0x0004,
  976. /// <summary>
  977. /// The SE m_ NOGPFAULTERRORBOX
  978. /// </summary>
  979. SEM_NOGPFAULTERRORBOX = 0x0002,
  980. /// <summary>
  981. /// The SE m_ NOOPENFILEERRORBOX
  982. /// </summary>
  983. SEM_NOOPENFILEERRORBOX = 0x8000
  984. }
  985. }
  986. }