MediaEncoder.cs 41 KB

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