MediaEncoder.cs 36 KB

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