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