MediaEncoder.cs 40 KB

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