MediaEncoder.cs 39 KB

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