MediaEncoder.cs 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Globalization;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Threading;
  7. using System.Threading.Tasks;
  8. using MediaBrowser.Common.Configuration;
  9. using MediaBrowser.Common.Extensions;
  10. using MediaBrowser.Controller.Configuration;
  11. using MediaBrowser.Controller.Library;
  12. using MediaBrowser.Controller.MediaEncoding;
  13. using MediaBrowser.MediaEncoding.Probing;
  14. using MediaBrowser.Model.Configuration;
  15. using MediaBrowser.Model.Diagnostics;
  16. using MediaBrowser.Model.Dlna;
  17. using MediaBrowser.Model.Entities;
  18. using MediaBrowser.Model.IO;
  19. using MediaBrowser.Model.MediaInfo;
  20. using MediaBrowser.Model.Serialization;
  21. using Microsoft.Extensions.Logging;
  22. namespace MediaBrowser.MediaEncoding.Encoder
  23. {
  24. /// <summary>
  25. /// Class MediaEncoder
  26. /// </summary>
  27. public class MediaEncoder : IMediaEncoder, IDisposable
  28. {
  29. /// <summary>
  30. /// Gets the encoder path.
  31. /// </summary>
  32. /// <value>The encoder path.</value>
  33. public string EncoderPath => FFmpegPath;
  34. /// <summary>
  35. /// External: path supplied via command line
  36. /// Custom: coming from UI or config/encoding.xml file
  37. /// System: FFmpeg found in system $PATH
  38. /// null: No FFmpeg found
  39. /// </summary>
  40. public string EncoderLocationType { get; private set; }
  41. private readonly ILogger _logger;
  42. private readonly IJsonSerializer _jsonSerializer;
  43. private string FFmpegPath { get; set; }
  44. private string FFprobePath { get; set; }
  45. protected readonly IServerConfigurationManager ConfigurationManager;
  46. protected readonly IFileSystem FileSystem;
  47. protected readonly Func<ISubtitleEncoder> SubtitleEncoder;
  48. protected readonly Func<IMediaSourceManager> MediaSourceManager;
  49. private readonly IProcessFactory _processFactory;
  50. private readonly int DefaultImageExtractionTimeoutMs;
  51. private readonly string StartupOptionFFmpegPath;
  52. private readonly string StartupOptionFFprobePath;
  53. private readonly SemaphoreSlim _thumbnailResourcePool = new SemaphoreSlim(1, 1);
  54. private readonly List<ProcessWrapper> _runningProcesses = new List<ProcessWrapper>();
  55. public MediaEncoder(
  56. ILoggerFactory loggerFactory,
  57. IJsonSerializer jsonSerializer,
  58. string startupOptionsFFmpegPath,
  59. string startupOptionsFFprobePath,
  60. IServerConfigurationManager configurationManager,
  61. IFileSystem fileSystem,
  62. Func<ISubtitleEncoder> subtitleEncoder,
  63. Func<IMediaSourceManager> mediaSourceManager,
  64. IProcessFactory processFactory,
  65. int defaultImageExtractionTimeoutMs)
  66. {
  67. _logger = loggerFactory.CreateLogger(nameof(MediaEncoder));
  68. _jsonSerializer = jsonSerializer;
  69. StartupOptionFFmpegPath = startupOptionsFFmpegPath;
  70. StartupOptionFFprobePath = startupOptionsFFprobePath;
  71. ConfigurationManager = configurationManager;
  72. FileSystem = fileSystem;
  73. SubtitleEncoder = subtitleEncoder;
  74. _processFactory = processFactory;
  75. DefaultImageExtractionTimeoutMs = defaultImageExtractionTimeoutMs;
  76. }
  77. /// <summary>
  78. /// Run at startup or if the user removes a Custom path from transcode page.
  79. /// Sets global variables FFmpegPath and EncoderLocationType.
  80. /// If startup options --ffprobe is given then FFprobePath is set too.
  81. /// </summary>
  82. public void Init()
  83. {
  84. // 1) If given, use the --ffmpeg CLI switch
  85. if (ValidatePathFFmpeg("From CLI Switch", StartupOptionFFmpegPath))
  86. {
  87. _logger.LogInformation("FFmpeg: Using path from command line switch --ffmpeg");
  88. EncoderLocationType = "External";
  89. }
  90. // 2) Try Custom path stroed in config/encoding xml file under tag <EncoderAppPathCustom>
  91. else if (ValidatePathFFmpeg("From Config File", ConfigurationManager.GetConfiguration<EncodingOptions>("encoding").EncoderAppPathCustom))
  92. {
  93. _logger.LogInformation("FFmpeg: Using path from config/encoding.xml file");
  94. EncoderLocationType = "Custom";
  95. }
  96. // 3) Search system $PATH environment variable for valid FFmpeg
  97. else if (ValidatePathFFmpeg("From $PATH", ExistsOnSystemPath("ffmpeg")))
  98. {
  99. _logger.LogInformation("FFmpeg: Using system $PATH for FFmpeg");
  100. EncoderLocationType = "System";
  101. }
  102. else
  103. {
  104. _logger.LogError("FFmpeg: No suitable executable found");
  105. FFmpegPath = null;
  106. EncoderLocationType = null;
  107. }
  108. // If given, use the --ffprobe CLI switch
  109. if (ValidatePathFFprobe("CLI Switch", StartupOptionFFprobePath))
  110. {
  111. _logger.LogInformation("FFprobe: Using path from command line switch --ffprobe");
  112. }
  113. else
  114. {
  115. // FFprobe path from command line is no good, so set to null and let ReInit() try
  116. // and set using the FFmpeg path.
  117. FFprobePath = null;
  118. }
  119. ReInit();
  120. }
  121. /// <summary>
  122. /// Writes the currently used FFmpeg to config/encoding.xml file.
  123. /// Sets the FFprobe path if not currently set.
  124. /// Interrogates the FFmpeg tool to identify what encoders/decodres are available.
  125. /// </summary>
  126. private void ReInit()
  127. {
  128. // Write the FFmpeg path to the config/encoding.xml file so it appears in UI
  129. var config = ConfigurationManager.GetConfiguration<EncodingOptions>("encoding");
  130. config.EncoderAppPath = FFmpegPath ?? string.Empty;
  131. ConfigurationManager.SaveConfiguration("encoding", config);
  132. // Only if mpeg path is set, try and set path to probe
  133. if (FFmpegPath != null)
  134. {
  135. // Probe would be null here if no valid --ffprobe path was given
  136. // at startup, or we're performing ReInit following mpeg path update from UI
  137. if (FFprobePath == null)
  138. {
  139. // Use the mpeg path to create a probe path
  140. if (ValidatePathFFprobe("Copied from FFmpeg:", GetProbePathFromEncoderPath(FFmpegPath)))
  141. {
  142. _logger.LogInformation("FFprobe: Using FFprobe in same folders as FFmpeg");
  143. }
  144. else
  145. {
  146. _logger.LogError("FFprobe: No suitable executable found");
  147. }
  148. }
  149. // Interrogate to understand what coders it supports
  150. var result = new EncoderValidator(_logger, _processFactory).GetAvailableCoders(FFmpegPath);
  151. SetAvailableDecoders(result.decoders);
  152. SetAvailableEncoders(result.encoders);
  153. }
  154. // Stamp FFmpeg paths to the log file
  155. LogPaths();
  156. }
  157. /// <summary>
  158. /// Triggered from the Settings > Trascoding UI page when users sumits Custom FFmpeg path to use.
  159. /// </summary>
  160. /// <param name="path"></param>
  161. /// <param name="pathType"></param>
  162. public void UpdateEncoderPath(string path, string pathType)
  163. {
  164. _logger.LogInformation("Attempting to update encoder path to {0}. pathType: {1}", path ?? string.Empty, pathType ?? string.Empty);
  165. if (!string.Equals(pathType, "custom", StringComparison.OrdinalIgnoreCase))
  166. {
  167. throw new ArgumentException("Unexpected pathType value");
  168. }
  169. else
  170. {
  171. if (string.IsNullOrWhiteSpace(path))
  172. {
  173. // User had cleared the cutom path in UI. Clear the Custom config
  174. // setting and peform full Init to relook any CLI switches and system $PATH
  175. var config = ConfigurationManager.GetConfiguration<EncodingOptions>("encoding");
  176. config.EncoderAppPathCustom = string.Empty;
  177. ConfigurationManager.SaveConfiguration("encoding", config);
  178. Init();
  179. }
  180. else if (!File.Exists(path) && !Directory.Exists(path))
  181. {
  182. // Given path is neither file or folder
  183. throw new ResourceNotFoundException();
  184. }
  185. else
  186. {
  187. // Supplied path could be either file path or folder path.
  188. // Resolve down to file path and validate
  189. path = GetEncoderPath(path);
  190. if (path == null)
  191. {
  192. throw new ResourceNotFoundException("FFmpeg not found");
  193. }
  194. else if (!ValidatePathFFmpeg("New From UI", path))
  195. {
  196. throw new ResourceNotFoundException("Failed validation checks. Version 4.0 or greater is required");
  197. }
  198. else
  199. {
  200. EncoderLocationType = "Custom";
  201. // Write the validated mpeg path to the xml as <EncoderAppPathCustom>
  202. // This ensures its not lost on new startup
  203. var config = ConfigurationManager.GetConfiguration<EncodingOptions>("encoding");
  204. config.EncoderAppPathCustom = FFmpegPath;
  205. ConfigurationManager.SaveConfiguration("encoding", config);
  206. FFprobePath = null; // Clear probe path so it gets relooked in ReInit()
  207. ReInit();
  208. }
  209. }
  210. }
  211. }
  212. private bool ValidatePath(string type, string path)
  213. {
  214. if (!string.IsNullOrEmpty(path))
  215. {
  216. if (File.Exists(path))
  217. {
  218. var valid = new EncoderValidator(_logger, _processFactory).ValidateVersion(path, true);
  219. if (valid == true)
  220. {
  221. return true;
  222. }
  223. else
  224. {
  225. _logger.LogError("{0}: Failed validation checks. Version 4.0 or greater is required: {1}", type, path);
  226. }
  227. }
  228. else
  229. {
  230. _logger.LogError("{0}: File not found: {1}", type, path);
  231. }
  232. }
  233. return false;
  234. }
  235. private bool ValidatePathFFmpeg(string comment, string path)
  236. {
  237. if (ValidatePath("FFmpeg: " + comment, path) == true)
  238. {
  239. FFmpegPath = path;
  240. return true;
  241. }
  242. return false;
  243. }
  244. private bool ValidatePathFFprobe(string comment, string path)
  245. {
  246. if (ValidatePath("FFprobe: " + comment, path) == true)
  247. {
  248. FFprobePath = path;
  249. return true;
  250. }
  251. return false;
  252. }
  253. private string GetEncoderPath(string path)
  254. {
  255. if (Directory.Exists(path))
  256. {
  257. return GetEncoderPathFromDirectory(path);
  258. }
  259. if (File.Exists(path))
  260. {
  261. return path;
  262. }
  263. return null;
  264. }
  265. private string GetEncoderPathFromDirectory(string path)
  266. {
  267. try
  268. {
  269. var files = FileSystem.GetFilePaths(path);
  270. var excludeExtensions = new[] { ".c" };
  271. return files.FirstOrDefault(i => string.Equals(Path.GetFileNameWithoutExtension(i), "ffmpeg", StringComparison.OrdinalIgnoreCase) && !excludeExtensions.Contains(Path.GetExtension(i) ?? string.Empty));
  272. }
  273. catch (Exception)
  274. {
  275. // Trap all exceptions, like DirNotExists, and return null
  276. return null;
  277. }
  278. }
  279. private string GetProbePathFromEncoderPath(string appPath)
  280. {
  281. return FileSystem.GetFilePaths(Path.GetDirectoryName(appPath))
  282. .FirstOrDefault(i => string.Equals(Path.GetFileNameWithoutExtension(i), "ffprobe", StringComparison.OrdinalIgnoreCase));
  283. }
  284. /// <summary>
  285. /// Search the system $PATH environment variable looking for given filename.
  286. /// </summary>
  287. /// <param name="fileName"></param>
  288. /// <returns></returns>
  289. private string ExistsOnSystemPath(string fileName)
  290. {
  291. var values = Environment.GetEnvironmentVariable("PATH");
  292. foreach (var path in values.Split(Path.PathSeparator))
  293. {
  294. var candidatePath = GetEncoderPathFromDirectory(path);
  295. if (ValidatePath("Found on PATH", candidatePath))
  296. {
  297. return candidatePath;
  298. }
  299. }
  300. return null;
  301. }
  302. private void LogPaths()
  303. {
  304. _logger.LogInformation("FFMpeg: {0}", FFmpegPath ?? "not found");
  305. _logger.LogInformation("FFProbe: {0}", FFprobePath ?? "not found");
  306. }
  307. private List<string> _encoders = new List<string>();
  308. public void SetAvailableEncoders(IEnumerable<string> list)
  309. {
  310. _encoders = list.ToList();
  311. //_logger.Info("Supported encoders: {0}", string.Join(",", list.ToArray()));
  312. }
  313. private List<string> _decoders = new List<string>();
  314. public void SetAvailableDecoders(IEnumerable<string> list)
  315. {
  316. _decoders = list.ToList();
  317. //_logger.Info("Supported decoders: {0}", string.Join(",", list.ToArray()));
  318. }
  319. public bool SupportsEncoder(string encoder)
  320. {
  321. return _encoders.Contains(encoder, StringComparer.OrdinalIgnoreCase);
  322. }
  323. public bool SupportsDecoder(string decoder)
  324. {
  325. return _decoders.Contains(decoder, StringComparer.OrdinalIgnoreCase);
  326. }
  327. public bool CanEncodeToAudioCodec(string codec)
  328. {
  329. if (string.Equals(codec, "opus", StringComparison.OrdinalIgnoreCase))
  330. {
  331. codec = "libopus";
  332. }
  333. else if (string.Equals(codec, "mp3", StringComparison.OrdinalIgnoreCase))
  334. {
  335. codec = "libmp3lame";
  336. }
  337. return SupportsEncoder(codec);
  338. }
  339. public bool CanEncodeToSubtitleCodec(string codec)
  340. {
  341. // TODO
  342. return true;
  343. }
  344. /// <summary>
  345. /// Gets the media info.
  346. /// </summary>
  347. /// <param name="request">The request.</param>
  348. /// <param name="cancellationToken">The cancellation token.</param>
  349. /// <returns>Task.</returns>
  350. public Task<MediaInfo> GetMediaInfo(MediaInfoRequest request, CancellationToken cancellationToken)
  351. {
  352. var extractChapters = request.MediaType == DlnaProfileType.Video && request.ExtractChapters;
  353. var inputFiles = MediaEncoderHelpers.GetInputArgument(FileSystem, request.MediaSource.Path, request.MediaSource.Protocol, request.MountedIso, request.PlayableStreamFileNames);
  354. var probeSize = EncodingHelper.GetProbeSizeArgument(inputFiles.Length);
  355. string analyzeDuration;
  356. if (request.MediaSource.AnalyzeDurationMs > 0)
  357. {
  358. analyzeDuration = "-analyzeduration " +
  359. (request.MediaSource.AnalyzeDurationMs * 1000).ToString();
  360. }
  361. else
  362. {
  363. analyzeDuration = EncodingHelper.GetAnalyzeDurationArgument(inputFiles.Length);
  364. }
  365. probeSize = probeSize + " " + analyzeDuration;
  366. probeSize = probeSize.Trim();
  367. var forceEnableLogging = request.MediaSource.Protocol != MediaProtocol.File;
  368. return GetMediaInfoInternal(GetInputArgument(inputFiles, request.MediaSource.Protocol), request.MediaSource.Path, request.MediaSource.Protocol, extractChapters,
  369. probeSize, request.MediaType == DlnaProfileType.Audio, request.MediaSource.VideoType, forceEnableLogging, cancellationToken);
  370. }
  371. /// <summary>
  372. /// Gets the input argument.
  373. /// </summary>
  374. /// <param name="inputFiles">The input files.</param>
  375. /// <param name="protocol">The protocol.</param>
  376. /// <returns>System.String.</returns>
  377. /// <exception cref="ArgumentException">Unrecognized InputType</exception>
  378. public string GetInputArgument(string[] inputFiles, MediaProtocol protocol)
  379. {
  380. return EncodingUtils.GetInputArgument(inputFiles.ToList(), protocol);
  381. }
  382. /// <summary>
  383. /// Gets the media info internal.
  384. /// </summary>
  385. /// <returns>Task{MediaInfoResult}.</returns>
  386. private async Task<MediaInfo> GetMediaInfoInternal(string inputPath,
  387. string primaryPath,
  388. MediaProtocol protocol,
  389. bool extractChapters,
  390. string probeSizeArgument,
  391. bool isAudio,
  392. VideoType? videoType,
  393. bool forceEnableLogging,
  394. CancellationToken cancellationToken)
  395. {
  396. var args = extractChapters
  397. ? "{0} -i {1} -threads 0 -v info -print_format json -show_streams -show_chapters -show_format"
  398. : "{0} -i {1} -threads 0 -v info -print_format json -show_streams -show_format";
  399. var process = _processFactory.Create(new ProcessOptions
  400. {
  401. CreateNoWindow = true,
  402. UseShellExecute = false,
  403. // Must consume both or ffmpeg may hang due to deadlocks. See comments below.
  404. RedirectStandardOutput = true,
  405. FileName = FFprobePath,
  406. Arguments = string.Format(args, probeSizeArgument, inputPath).Trim(),
  407. IsHidden = true,
  408. ErrorDialog = false,
  409. EnableRaisingEvents = true
  410. });
  411. if (forceEnableLogging)
  412. {
  413. _logger.LogInformation("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments);
  414. }
  415. else
  416. {
  417. _logger.LogDebug("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments);
  418. }
  419. using (var processWrapper = new ProcessWrapper(process, this, _logger))
  420. {
  421. StartProcess(processWrapper);
  422. try
  423. {
  424. //process.BeginErrorReadLine();
  425. var result = await _jsonSerializer.DeserializeFromStreamAsync<InternalMediaInfoResult>(process.StandardOutput.BaseStream).ConfigureAwait(false);
  426. if (result == null || (result.streams == null && result.format == null))
  427. {
  428. throw new Exception("ffprobe failed - streams and format are both null.");
  429. }
  430. if (result.streams != null)
  431. {
  432. // Normalize aspect ratio if invalid
  433. foreach (var stream in result.streams)
  434. {
  435. if (string.Equals(stream.display_aspect_ratio, "0:1", StringComparison.OrdinalIgnoreCase))
  436. {
  437. stream.display_aspect_ratio = string.Empty;
  438. }
  439. if (string.Equals(stream.sample_aspect_ratio, "0:1", StringComparison.OrdinalIgnoreCase))
  440. {
  441. stream.sample_aspect_ratio = string.Empty;
  442. }
  443. }
  444. }
  445. return new ProbeResultNormalizer(_logger, FileSystem).GetMediaInfo(result, videoType, isAudio, primaryPath, protocol);
  446. }
  447. catch
  448. {
  449. StopProcess(processWrapper, 100);
  450. throw;
  451. }
  452. }
  453. }
  454. /// <summary>
  455. /// The us culture
  456. /// </summary>
  457. protected readonly CultureInfo UsCulture = new CultureInfo("en-US");
  458. public Task<string> ExtractAudioImage(string path, int? imageStreamIndex, CancellationToken cancellationToken)
  459. {
  460. return ExtractImage(new[] { path }, null, null, imageStreamIndex, MediaProtocol.File, true, null, null, cancellationToken);
  461. }
  462. public Task<string> ExtractVideoImage(string[] inputFiles, string container, MediaProtocol protocol, MediaStream videoStream, Video3DFormat? threedFormat, TimeSpan? offset, CancellationToken cancellationToken)
  463. {
  464. return ExtractImage(inputFiles, container, videoStream, null, protocol, false, threedFormat, offset, cancellationToken);
  465. }
  466. public Task<string> ExtractVideoImage(string[] inputFiles, string container, MediaProtocol protocol, MediaStream imageStream, int? imageStreamIndex, CancellationToken cancellationToken)
  467. {
  468. return ExtractImage(inputFiles, container, imageStream, imageStreamIndex, protocol, false, null, null, cancellationToken);
  469. }
  470. private async Task<string> ExtractImage(string[] inputFiles, string container, MediaStream videoStream, int? imageStreamIndex, MediaProtocol protocol, bool isAudio,
  471. Video3DFormat? threedFormat, TimeSpan? offset, CancellationToken cancellationToken)
  472. {
  473. var inputArgument = GetInputArgument(inputFiles, protocol);
  474. if (isAudio)
  475. {
  476. if (imageStreamIndex.HasValue && imageStreamIndex.Value > 0)
  477. {
  478. // It seems for audio files we need to subtract 1 (for the audio stream??)
  479. imageStreamIndex = imageStreamIndex.Value - 1;
  480. }
  481. }
  482. else
  483. {
  484. try
  485. {
  486. return await ExtractImageInternal(inputArgument, container, videoStream, imageStreamIndex, threedFormat, offset, true, cancellationToken).ConfigureAwait(false);
  487. }
  488. catch (ArgumentException)
  489. {
  490. throw;
  491. }
  492. catch (Exception ex)
  493. {
  494. _logger.LogError(ex, "I-frame image extraction failed, will attempt standard way. Input: {arguments}", inputArgument);
  495. }
  496. }
  497. return await ExtractImageInternal(inputArgument, container, videoStream, imageStreamIndex, threedFormat, offset, false, cancellationToken).ConfigureAwait(false);
  498. }
  499. private async Task<string> ExtractImageInternal(string inputPath, string container, MediaStream videoStream, int? imageStreamIndex, Video3DFormat? threedFormat, TimeSpan? offset, bool useIFrame, CancellationToken cancellationToken)
  500. {
  501. if (string.IsNullOrEmpty(inputPath))
  502. {
  503. throw new ArgumentNullException(nameof(inputPath));
  504. }
  505. var tempExtractPath = Path.Combine(ConfigurationManager.ApplicationPaths.TempDirectory, Guid.NewGuid() + ".jpg");
  506. Directory.CreateDirectory(Path.GetDirectoryName(tempExtractPath));
  507. // apply some filters to thumbnail extracted below (below) crop any black lines that we made and get the correct ar then scale to width 600.
  508. // This filter chain may have adverse effects on recorded tv thumbnails if ar changes during presentation ex. commercials @ diff ar
  509. var vf = "scale=600:trunc(600/dar/2)*2";
  510. if (threedFormat.HasValue)
  511. {
  512. switch (threedFormat.Value)
  513. {
  514. case Video3DFormat.HalfSideBySide:
  515. vf = "crop=iw/2:ih:0:0,scale=(iw*2):ih,setdar=dar=a,crop=min(iw\\,ih*dar):min(ih\\,iw/dar):(iw-min(iw\\,iw*sar))/2:(ih - min (ih\\,ih/sar))/2,setsar=sar=1,scale=600:trunc(600/dar/2)*2";
  516. // hsbs crop width in half,scale to correct size, set the display aspect,crop out any black bars we may have made the scale width to 600. Work out the correct height based on the display aspect it will maintain the aspect where -1 in this case (3d) may not.
  517. break;
  518. case Video3DFormat.FullSideBySide:
  519. vf = "crop=iw/2:ih:0:0,setdar=dar=a,crop=min(iw\\,ih*dar):min(ih\\,iw/dar):(iw-min(iw\\,iw*sar))/2:(ih - min (ih\\,ih/sar))/2,setsar=sar=1,scale=600:trunc(600/dar/2)*2";
  520. //fsbs crop width in half,set the display aspect,crop out any black bars we may have made the scale width to 600.
  521. break;
  522. case Video3DFormat.HalfTopAndBottom:
  523. vf = "crop=iw:ih/2:0:0,scale=(iw*2):ih),setdar=dar=a,crop=min(iw\\,ih*dar):min(ih\\,iw/dar):(iw-min(iw\\,iw*sar))/2:(ih - min (ih\\,ih/sar))/2,setsar=sar=1,scale=600:trunc(600/dar/2)*2";
  524. //htab crop heigh in half,scale to correct size, set the display aspect,crop out any black bars we may have made the scale width to 600
  525. break;
  526. case Video3DFormat.FullTopAndBottom:
  527. vf = "crop=iw:ih/2:0:0,setdar=dar=a,crop=min(iw\\,ih*dar):min(ih\\,iw/dar):(iw-min(iw\\,iw*sar))/2:(ih - min (ih\\,ih/sar))/2,setsar=sar=1,scale=600:trunc(600/dar/2)*2";
  528. // ftab crop heigt in half, set the display aspect,crop out any black bars we may have made the scale width to 600
  529. break;
  530. default:
  531. break;
  532. }
  533. }
  534. var mapArg = imageStreamIndex.HasValue ? (" -map 0:v:" + imageStreamIndex.Value.ToString(CultureInfo.InvariantCulture)) : string.Empty;
  535. var enableThumbnail = !new List<string> { "wtv" }.Contains(container ?? string.Empty, StringComparer.OrdinalIgnoreCase);
  536. // Use ffmpeg to sample 100 (we can drop this if required using thumbnail=50 for 50 frames) frames and pick the best thumbnail. Have a fall back just in case.
  537. var thumbnail = enableThumbnail ? ",thumbnail=24" : string.Empty;
  538. var args = useIFrame ? string.Format("-i {0}{3} -threads 0 -v quiet -vframes 1 -vf \"{2}{4}\" -f image2 \"{1}\"", inputPath, tempExtractPath, vf, mapArg, thumbnail) :
  539. string.Format("-i {0}{3} -threads 0 -v quiet -vframes 1 -vf \"{2}\" -f image2 \"{1}\"", inputPath, tempExtractPath, vf, mapArg);
  540. var probeSizeArgument = EncodingHelper.GetProbeSizeArgument(1);
  541. var analyzeDurationArgument = EncodingHelper.GetAnalyzeDurationArgument(1);
  542. if (!string.IsNullOrWhiteSpace(probeSizeArgument))
  543. {
  544. args = probeSizeArgument + " " + args;
  545. }
  546. if (!string.IsNullOrWhiteSpace(analyzeDurationArgument))
  547. {
  548. args = analyzeDurationArgument + " " + args;
  549. }
  550. if (offset.HasValue)
  551. {
  552. args = string.Format("-ss {0} ", GetTimeParameter(offset.Value)) + args;
  553. }
  554. var encodinghelper = new EncodingHelper(this, FileSystem, SubtitleEncoder());
  555. if (videoStream != null)
  556. {
  557. /* fix
  558. var decoder = encodinghelper.GetHardwareAcceleratedVideoDecoder(VideoType.VideoFile, videoStream, GetEncodingOptions());
  559. if (!string.IsNullOrWhiteSpace(decoder))
  560. {
  561. args = decoder + " " + args;
  562. }
  563. */
  564. }
  565. if (!string.IsNullOrWhiteSpace(container))
  566. {
  567. var inputFormat = encodinghelper.GetInputFormat(container);
  568. if (!string.IsNullOrWhiteSpace(inputFormat))
  569. {
  570. args = "-f " + inputFormat + " " + args;
  571. }
  572. }
  573. var process = _processFactory.Create(new ProcessOptions
  574. {
  575. CreateNoWindow = true,
  576. UseShellExecute = false,
  577. FileName = FFmpegPath,
  578. Arguments = args,
  579. IsHidden = true,
  580. ErrorDialog = false,
  581. EnableRaisingEvents = true
  582. });
  583. _logger.LogDebug("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments);
  584. using (var processWrapper = new ProcessWrapper(process, this, _logger))
  585. {
  586. bool ranToCompletion;
  587. StartProcess(processWrapper);
  588. var timeoutMs = ConfigurationManager.Configuration.ImageExtractionTimeoutMs;
  589. if (timeoutMs <= 0)
  590. {
  591. timeoutMs = DefaultImageExtractionTimeoutMs;
  592. }
  593. ranToCompletion = await process.WaitForExitAsync(timeoutMs).ConfigureAwait(false);
  594. if (!ranToCompletion)
  595. {
  596. StopProcess(processWrapper, 1000);
  597. }
  598. var exitCode = ranToCompletion ? processWrapper.ExitCode ?? 0 : -1;
  599. var file = FileSystem.GetFileInfo(tempExtractPath);
  600. if (exitCode == -1 || !file.Exists || file.Length == 0)
  601. {
  602. var msg = string.Format("ffmpeg image extraction failed for {0}", inputPath);
  603. _logger.LogError(msg);
  604. throw new Exception(msg);
  605. }
  606. return tempExtractPath;
  607. }
  608. }
  609. public string GetTimeParameter(long ticks)
  610. {
  611. var time = TimeSpan.FromTicks(ticks);
  612. return GetTimeParameter(time);
  613. }
  614. public string GetTimeParameter(TimeSpan time)
  615. {
  616. return time.ToString(@"hh\:mm\:ss\.fff", UsCulture);
  617. }
  618. public async Task ExtractVideoImagesOnInterval(string[] inputFiles,
  619. string container,
  620. MediaStream videoStream,
  621. MediaProtocol protocol,
  622. Video3DFormat? threedFormat,
  623. TimeSpan interval,
  624. string targetDirectory,
  625. string filenamePrefix,
  626. int? maxWidth,
  627. CancellationToken cancellationToken)
  628. {
  629. var resourcePool = _thumbnailResourcePool;
  630. var inputArgument = GetInputArgument(inputFiles, protocol);
  631. var vf = "fps=fps=1/" + interval.TotalSeconds.ToString(UsCulture);
  632. if (maxWidth.HasValue)
  633. {
  634. var maxWidthParam = maxWidth.Value.ToString(UsCulture);
  635. vf += string.Format(",scale=min(iw\\,{0}):trunc(ow/dar/2)*2", maxWidthParam);
  636. }
  637. Directory.CreateDirectory(targetDirectory);
  638. var outputPath = Path.Combine(targetDirectory, filenamePrefix + "%05d.jpg");
  639. var args = string.Format("-i {0} -threads 0 -v quiet -vf \"{2}\" -f image2 \"{1}\"", inputArgument, outputPath, vf);
  640. var probeSizeArgument = EncodingHelper.GetProbeSizeArgument(1);
  641. var analyzeDurationArgument = EncodingHelper.GetAnalyzeDurationArgument(1);
  642. if (!string.IsNullOrWhiteSpace(probeSizeArgument))
  643. {
  644. args = probeSizeArgument + " " + args;
  645. }
  646. if (!string.IsNullOrWhiteSpace(analyzeDurationArgument))
  647. {
  648. args = analyzeDurationArgument + " " + args;
  649. }
  650. var encodinghelper = new EncodingHelper(this, FileSystem, SubtitleEncoder());
  651. if (videoStream != null)
  652. {
  653. /* fix
  654. var decoder = encodinghelper.GetHardwareAcceleratedVideoDecoder(VideoType.VideoFile, videoStream, GetEncodingOptions());
  655. if (!string.IsNullOrWhiteSpace(decoder))
  656. {
  657. args = decoder + " " + args;
  658. }
  659. */
  660. }
  661. if (!string.IsNullOrWhiteSpace(container))
  662. {
  663. var inputFormat = encodinghelper.GetInputFormat(container);
  664. if (!string.IsNullOrWhiteSpace(inputFormat))
  665. {
  666. args = "-f " + inputFormat + " " + args;
  667. }
  668. }
  669. var process = _processFactory.Create(new ProcessOptions
  670. {
  671. CreateNoWindow = true,
  672. UseShellExecute = false,
  673. FileName = FFmpegPath,
  674. Arguments = args,
  675. IsHidden = true,
  676. ErrorDialog = false,
  677. EnableRaisingEvents = true
  678. });
  679. _logger.LogInformation(process.StartInfo.FileName + " " + process.StartInfo.Arguments);
  680. await resourcePool.WaitAsync(cancellationToken).ConfigureAwait(false);
  681. bool ranToCompletion = false;
  682. using (var processWrapper = new ProcessWrapper(process, this, _logger))
  683. {
  684. try
  685. {
  686. StartProcess(processWrapper);
  687. // Need to give ffmpeg enough time to make all the thumbnails, which could be a while,
  688. // but we still need to detect if the process hangs.
  689. // Making the assumption that as long as new jpegs are showing up, everything is good.
  690. bool isResponsive = true;
  691. int lastCount = 0;
  692. while (isResponsive)
  693. {
  694. if (await process.WaitForExitAsync(30000).ConfigureAwait(false))
  695. {
  696. ranToCompletion = true;
  697. break;
  698. }
  699. cancellationToken.ThrowIfCancellationRequested();
  700. var jpegCount = FileSystem.GetFilePaths(targetDirectory)
  701. .Count(i => string.Equals(Path.GetExtension(i), ".jpg", StringComparison.OrdinalIgnoreCase));
  702. isResponsive = (jpegCount > lastCount);
  703. lastCount = jpegCount;
  704. }
  705. if (!ranToCompletion)
  706. {
  707. StopProcess(processWrapper, 1000);
  708. }
  709. }
  710. finally
  711. {
  712. resourcePool.Release();
  713. }
  714. var exitCode = ranToCompletion ? processWrapper.ExitCode ?? 0 : -1;
  715. if (exitCode == -1)
  716. {
  717. var msg = string.Format("ffmpeg image extraction failed for {0}", inputArgument);
  718. _logger.LogError(msg);
  719. throw new Exception(msg);
  720. }
  721. }
  722. }
  723. private void StartProcess(ProcessWrapper process)
  724. {
  725. process.Process.Start();
  726. lock (_runningProcesses)
  727. {
  728. _runningProcesses.Add(process);
  729. }
  730. }
  731. private void StopProcess(ProcessWrapper process, int waitTimeMs)
  732. {
  733. try
  734. {
  735. if (process.Process.WaitForExit(waitTimeMs))
  736. {
  737. return;
  738. }
  739. }
  740. catch (Exception ex)
  741. {
  742. _logger.LogError(ex, "Error in WaitForExit");
  743. }
  744. try
  745. {
  746. _logger.LogInformation("Killing ffmpeg process");
  747. process.Process.Kill();
  748. }
  749. catch (Exception ex)
  750. {
  751. _logger.LogError(ex, "Error killing process");
  752. }
  753. }
  754. private void StopProcesses()
  755. {
  756. List<ProcessWrapper> proceses;
  757. lock (_runningProcesses)
  758. {
  759. proceses = _runningProcesses.ToList();
  760. _runningProcesses.Clear();
  761. }
  762. foreach (var process in proceses)
  763. {
  764. if (!process.HasExited)
  765. {
  766. StopProcess(process, 500);
  767. }
  768. }
  769. }
  770. public string EscapeSubtitleFilterPath(string path)
  771. {
  772. // https://ffmpeg.org/ffmpeg-filters.html#Notes-on-filtergraph-escaping
  773. // We need to double escape
  774. return path.Replace('\\', '/').Replace(":", "\\:").Replace("'", "'\\\\\\''");
  775. }
  776. /// <summary>
  777. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  778. /// </summary>
  779. public void Dispose()
  780. {
  781. Dispose(true);
  782. }
  783. /// <summary>
  784. /// Releases unmanaged and - optionally - managed resources.
  785. /// </summary>
  786. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  787. protected virtual void Dispose(bool dispose)
  788. {
  789. if (dispose)
  790. {
  791. StopProcesses();
  792. }
  793. }
  794. public Task ConvertImage(string inputPath, string outputPath)
  795. {
  796. throw new NotImplementedException();
  797. }
  798. public string[] GetPlayableStreamFileNames(string path, VideoType videoType)
  799. {
  800. throw new NotImplementedException();
  801. }
  802. public IEnumerable<string> GetPrimaryPlaylistVobFiles(string path, IIsoMount isoMount, uint? titleNumber)
  803. {
  804. throw new NotImplementedException();
  805. }
  806. public bool CanExtractSubtitles(string codec)
  807. {
  808. // TODO is there ever a case when a subtitle can't be extracted??
  809. return true;
  810. }
  811. private class ProcessWrapper : IDisposable
  812. {
  813. public readonly IProcess Process;
  814. public bool HasExited;
  815. public int? ExitCode;
  816. private readonly MediaEncoder _mediaEncoder;
  817. private readonly ILogger _logger;
  818. public ProcessWrapper(IProcess process, MediaEncoder mediaEncoder, ILogger logger)
  819. {
  820. Process = process;
  821. _mediaEncoder = mediaEncoder;
  822. _logger = logger;
  823. Process.Exited += Process_Exited;
  824. }
  825. void Process_Exited(object sender, EventArgs e)
  826. {
  827. var process = (IProcess)sender;
  828. HasExited = true;
  829. try
  830. {
  831. ExitCode = process.ExitCode;
  832. }
  833. catch
  834. {
  835. }
  836. DisposeProcess(process);
  837. }
  838. private void DisposeProcess(IProcess process)
  839. {
  840. lock (_mediaEncoder._runningProcesses)
  841. {
  842. _mediaEncoder._runningProcesses.Remove(this);
  843. }
  844. try
  845. {
  846. process.Dispose();
  847. }
  848. catch
  849. {
  850. }
  851. }
  852. private bool _disposed;
  853. private readonly object _syncLock = new object();
  854. public void Dispose()
  855. {
  856. lock (_syncLock)
  857. {
  858. if (!_disposed)
  859. {
  860. if (Process != null)
  861. {
  862. Process.Exited -= Process_Exited;
  863. DisposeProcess(Process);
  864. }
  865. }
  866. _disposed = true;
  867. }
  868. }
  869. }
  870. }
  871. }