FFMpegManager.cs 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170
  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="inputPath">The input path.</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> ExtractAudioImage(string inputPath, string outputPath, CancellationToken cancellationToken)
  634. {
  635. if (string.IsNullOrEmpty(inputPath))
  636. {
  637. throw new ArgumentNullException("inputPath");
  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}\"", GetFileInputArgument(inputPath), 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}", inputPath);
  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 file input argument.
  883. /// </summary>
  884. /// <param name="path">The path.</param>
  885. /// <returns>System.String.</returns>
  886. private string GetFileInputArgument(string path)
  887. {
  888. return string.Format("file:\"{0}\"", path);
  889. }
  890. /// <summary>
  891. /// Gets the input argument.
  892. /// </summary>
  893. /// <param name="item">The item.</param>
  894. /// <param name="mount">The mount.</param>
  895. /// <returns>System.String.</returns>
  896. public string GetInputArgument(Video item, IIsoMount mount)
  897. {
  898. if (item.VideoType == VideoType.Iso && item.IsoType.HasValue)
  899. {
  900. if (item.IsoType.Value == IsoType.BluRay)
  901. {
  902. return GetBlurayInputArgument(mount.MountedPath);
  903. }
  904. if (item.IsoType.Value == IsoType.Dvd)
  905. {
  906. return GetDvdInputArgument(item.GetPlayableStreamFiles(mount.MountedPath));
  907. }
  908. }
  909. return GetInputArgument(item);
  910. }
  911. /// <summary>
  912. /// Gets the bluray input argument.
  913. /// </summary>
  914. /// <param name="blurayRoot">The bluray root.</param>
  915. /// <returns>System.String.</returns>
  916. public string GetBlurayInputArgument(string blurayRoot)
  917. {
  918. return string.Format("bluray:\"{0}\"", blurayRoot);
  919. }
  920. /// <summary>
  921. /// Gets the DVD input argument.
  922. /// </summary>
  923. /// <param name="playableStreamFiles">The playable stream files.</param>
  924. /// <returns>System.String.</returns>
  925. public string GetDvdInputArgument(IEnumerable<string> playableStreamFiles)
  926. {
  927. // Get all streams
  928. var streamFilePaths = (playableStreamFiles ?? new string[] { }).ToArray();
  929. // If there's more than one we'll need to use the concat command
  930. if (streamFilePaths.Length > 1)
  931. {
  932. var files = string.Join("|", streamFilePaths);
  933. return string.Format("concat:\"{0}\"", files);
  934. }
  935. // Determine the input path for video files
  936. return string.Format("file:\"{0}\"", streamFilePaths[0]);
  937. }
  938. /// <summary>
  939. /// Processes the exited.
  940. /// </summary>
  941. /// <param name="sender">The sender.</param>
  942. /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
  943. void ProcessExited(object sender, EventArgs e)
  944. {
  945. ((Process)sender).Dispose();
  946. }
  947. /// <summary>
  948. /// Provides a non-blocking method to start a process and wait asynchronously for it to exit
  949. /// </summary>
  950. /// <param name="process">The process.</param>
  951. /// <returns>Task{System.Boolean}.</returns>
  952. private static Task<bool> RunAsync(Process process)
  953. {
  954. var tcs = new TaskCompletionSource<bool>();
  955. process.EnableRaisingEvents = true;
  956. process.Exited += (sender, args) => tcs.SetResult(true);
  957. process.Start();
  958. return tcs.Task;
  959. }
  960. /// <summary>
  961. /// Sets the error mode.
  962. /// </summary>
  963. /// <param name="uMode">The u mode.</param>
  964. /// <returns>ErrorModes.</returns>
  965. [DllImport("kernel32.dll")]
  966. static extern ErrorModes SetErrorMode(ErrorModes uMode);
  967. /// <summary>
  968. /// Enum ErrorModes
  969. /// </summary>
  970. [Flags]
  971. public enum ErrorModes : uint
  972. {
  973. /// <summary>
  974. /// The SYSTE m_ DEFAULT
  975. /// </summary>
  976. SYSTEM_DEFAULT = 0x0,
  977. /// <summary>
  978. /// The SE m_ FAILCRITICALERRORS
  979. /// </summary>
  980. SEM_FAILCRITICALERRORS = 0x0001,
  981. /// <summary>
  982. /// The SE m_ NOALIGNMENTFAULTEXCEPT
  983. /// </summary>
  984. SEM_NOALIGNMENTFAULTEXCEPT = 0x0004,
  985. /// <summary>
  986. /// The SE m_ NOGPFAULTERRORBOX
  987. /// </summary>
  988. SEM_NOGPFAULTERRORBOX = 0x0002,
  989. /// <summary>
  990. /// The SE m_ NOOPENFILEERRORBOX
  991. /// </summary>
  992. SEM_NOOPENFILEERRORBOX = 0x8000
  993. }
  994. }
  995. }