MediaEncoder.cs 39 KB

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