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