2
0

MediaEncoder.cs 38 KB

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