2
0

MediaEncoder.cs 37 KB

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