MediaEncoder.cs 42 KB

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