MediaEncoder.cs 39 KB

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