MediaEncoder.cs 41 KB

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