MediaEncoder.cs 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129
  1. using MediaBrowser.Controller.Channels;
  2. using MediaBrowser.Controller.Configuration;
  3. using MediaBrowser.Controller.Library;
  4. using MediaBrowser.Controller.LiveTv;
  5. using MediaBrowser.Controller.MediaEncoding;
  6. using MediaBrowser.Controller.Session;
  7. using MediaBrowser.MediaEncoding.Probing;
  8. using MediaBrowser.Model.Dlna;
  9. using MediaBrowser.Model.Entities;
  10. using MediaBrowser.Model.IO;
  11. using MediaBrowser.Model.MediaInfo;
  12. using MediaBrowser.Model.Serialization;
  13. using System;
  14. using System.Collections.Generic;
  15. using System.Globalization;
  16. using System.IO;
  17. using System.Linq;
  18. using System.Threading;
  19. using System.Threading.Tasks;
  20. using MediaBrowser.Model.Configuration;
  21. using MediaBrowser.Common.Configuration;
  22. using MediaBrowser.Common.Extensions;
  23. using MediaBrowser.Common.Net;
  24. using MediaBrowser.Model.Diagnostics;
  25. using MediaBrowser.Model.System;
  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 _logger
  36. /// </summary>
  37. private readonly ILogger _logger;
  38. /// <summary>
  39. /// Gets the json serializer.
  40. /// </summary>
  41. /// <value>The json serializer.</value>
  42. private readonly IJsonSerializer _jsonSerializer;
  43. /// <summary>
  44. /// The _thumbnail resource pool
  45. /// </summary>
  46. private readonly SemaphoreSlim _thumbnailResourcePool = new SemaphoreSlim(1, 1);
  47. public string FFMpegPath { get; private set; }
  48. public string FFProbePath { get; private set; }
  49. protected readonly IServerConfigurationManager ConfigurationManager;
  50. protected readonly IFileSystem FileSystem;
  51. protected readonly ILiveTvManager LiveTvManager;
  52. protected readonly IIsoManager IsoManager;
  53. protected readonly ILibraryManager LibraryManager;
  54. protected readonly IChannelManager ChannelManager;
  55. protected readonly ISessionManager SessionManager;
  56. protected readonly Func<ISubtitleEncoder> SubtitleEncoder;
  57. protected readonly Func<IMediaSourceManager> MediaSourceManager;
  58. private readonly IHttpClient _httpClient;
  59. private readonly IZipClient _zipClient;
  60. private readonly IProcessFactory _processFactory;
  61. private readonly List<ProcessWrapper> _runningProcesses = new List<ProcessWrapper>();
  62. private readonly bool _hasExternalEncoder;
  63. private readonly string _originalFFMpegPath;
  64. private readonly string _originalFFProbePath;
  65. private readonly int DefaultImageExtractionTimeoutMs;
  66. private readonly bool EnableEncoderFontFile;
  67. private readonly IEnvironmentInfo _environmentInfo;
  68. public MediaEncoder(ILogger logger, IJsonSerializer jsonSerializer, string ffMpegPath, string ffProbePath, bool hasExternalEncoder, IServerConfigurationManager configurationManager, IFileSystem fileSystem, ILiveTvManager liveTvManager, IIsoManager isoManager, ILibraryManager libraryManager, IChannelManager channelManager, ISessionManager sessionManager, Func<ISubtitleEncoder> subtitleEncoder, Func<IMediaSourceManager> mediaSourceManager, IHttpClient httpClient, IZipClient zipClient, IProcessFactory processFactory,
  69. int defaultImageExtractionTimeoutMs,
  70. bool enableEncoderFontFile, IEnvironmentInfo environmentInfo)
  71. {
  72. _logger = logger;
  73. _jsonSerializer = jsonSerializer;
  74. ConfigurationManager = configurationManager;
  75. FileSystem = fileSystem;
  76. LiveTvManager = liveTvManager;
  77. IsoManager = isoManager;
  78. LibraryManager = libraryManager;
  79. ChannelManager = channelManager;
  80. SessionManager = sessionManager;
  81. SubtitleEncoder = subtitleEncoder;
  82. MediaSourceManager = mediaSourceManager;
  83. _httpClient = httpClient;
  84. _zipClient = zipClient;
  85. _processFactory = processFactory;
  86. DefaultImageExtractionTimeoutMs = defaultImageExtractionTimeoutMs;
  87. EnableEncoderFontFile = enableEncoderFontFile;
  88. _environmentInfo = environmentInfo;
  89. FFProbePath = ffProbePath;
  90. FFMpegPath = ffMpegPath;
  91. _originalFFProbePath = ffProbePath;
  92. _originalFFMpegPath = ffMpegPath;
  93. _hasExternalEncoder = hasExternalEncoder;
  94. }
  95. private readonly object _logLock = new object();
  96. public void SetLogFilename(string name)
  97. {
  98. lock (_logLock)
  99. {
  100. try
  101. {
  102. _environmentInfo.SetProcessEnvironmentVariable("FFREPORT", "file=" + name + ":level=32");
  103. }
  104. catch (Exception ex)
  105. {
  106. _logger.LogError(ex, "Error setting FFREPORT environment variable");
  107. }
  108. }
  109. }
  110. public void ClearLogFilename()
  111. {
  112. lock (_logLock)
  113. {
  114. try
  115. {
  116. _environmentInfo.SetProcessEnvironmentVariable("FFREPORT", null);
  117. }
  118. catch (Exception ex)
  119. {
  120. _logger.LogError(ex, "Error setting FFREPORT environment variable");
  121. }
  122. }
  123. }
  124. public string EncoderLocationType
  125. {
  126. get
  127. {
  128. if (_hasExternalEncoder)
  129. {
  130. return "External";
  131. }
  132. if (string.IsNullOrWhiteSpace(FFMpegPath))
  133. {
  134. return null;
  135. }
  136. if (IsSystemInstalledPath(FFMpegPath))
  137. {
  138. return "System";
  139. }
  140. return "Custom";
  141. }
  142. }
  143. private bool IsSystemInstalledPath(string path)
  144. {
  145. if (path.IndexOf("/", StringComparison.Ordinal) == -1 && path.IndexOf("\\", StringComparison.Ordinal) == -1)
  146. {
  147. return true;
  148. }
  149. return false;
  150. }
  151. public void Init()
  152. {
  153. InitPaths();
  154. if (!string.IsNullOrWhiteSpace(FFMpegPath))
  155. {
  156. var result = new EncoderValidator(_logger, _processFactory).Validate(FFMpegPath);
  157. SetAvailableDecoders(result.decoders);
  158. SetAvailableEncoders(result.encoders);
  159. if (EnableEncoderFontFile)
  160. {
  161. var directory = FileSystem.GetDirectoryName(FFMpegPath);
  162. if (!string.IsNullOrWhiteSpace(directory) && FileSystem.ContainsSubPath(ConfigurationManager.ApplicationPaths.ProgramDataPath, directory))
  163. {
  164. new FontConfigLoader(_httpClient, ConfigurationManager.ApplicationPaths, _logger, _zipClient, FileSystem).DownloadFonts(directory).ConfigureAwait(false);
  165. }
  166. }
  167. }
  168. }
  169. private void InitPaths()
  170. {
  171. ConfigureEncoderPaths();
  172. if (_hasExternalEncoder)
  173. {
  174. LogPaths();
  175. return;
  176. }
  177. // If the path was passed in, save it into config now.
  178. var encodingOptions = GetEncodingOptions();
  179. var appPath = encodingOptions.EncoderAppPath;
  180. var valueToSave = FFMpegPath;
  181. if (!string.IsNullOrWhiteSpace(valueToSave))
  182. {
  183. // if using system variable, don't save this.
  184. if (IsSystemInstalledPath(valueToSave) || _hasExternalEncoder)
  185. {
  186. valueToSave = null;
  187. }
  188. }
  189. if (!string.Equals(valueToSave, appPath, StringComparison.Ordinal))
  190. {
  191. encodingOptions.EncoderAppPath = valueToSave;
  192. ConfigurationManager.SaveConfiguration("encoding", encodingOptions);
  193. }
  194. }
  195. public void UpdateEncoderPath(string path, string pathType)
  196. {
  197. if (_hasExternalEncoder)
  198. {
  199. return;
  200. }
  201. _logger.LogInformation("Attempting to update encoder path to {0}. pathType: {1}", path ?? string.Empty, pathType ?? string.Empty);
  202. Tuple<string, string> newPaths;
  203. if (string.Equals(pathType, "system", StringComparison.OrdinalIgnoreCase))
  204. {
  205. path = "ffmpeg";
  206. newPaths = TestForInstalledVersions();
  207. }
  208. else if (string.Equals(pathType, "custom", StringComparison.OrdinalIgnoreCase))
  209. {
  210. if (string.IsNullOrWhiteSpace(path))
  211. {
  212. throw new ArgumentNullException("path");
  213. }
  214. if (!FileSystem.FileExists(path) && !FileSystem.DirectoryExists(path))
  215. {
  216. throw new ResourceNotFoundException();
  217. }
  218. newPaths = GetEncoderPaths(path);
  219. }
  220. else
  221. {
  222. throw new ArgumentException("Unexpected pathType value");
  223. }
  224. if (string.IsNullOrWhiteSpace(newPaths.Item1))
  225. {
  226. throw new ResourceNotFoundException("ffmpeg not found");
  227. }
  228. if (string.IsNullOrWhiteSpace(newPaths.Item2))
  229. {
  230. throw new ResourceNotFoundException("ffprobe not found");
  231. }
  232. path = newPaths.Item1;
  233. if (!ValidateVersion(path, true))
  234. {
  235. throw new ResourceNotFoundException("ffmpeg version 3.0 or greater is required.");
  236. }
  237. var config = GetEncodingOptions();
  238. config.EncoderAppPath = path;
  239. ConfigurationManager.SaveConfiguration("encoding", config);
  240. Init();
  241. }
  242. private bool ValidateVersion(string path, bool logOutput)
  243. {
  244. return new EncoderValidator(_logger, _processFactory).ValidateVersion(path, logOutput);
  245. }
  246. private void ConfigureEncoderPaths()
  247. {
  248. if (_hasExternalEncoder)
  249. {
  250. return;
  251. }
  252. var appPath = GetEncodingOptions().EncoderAppPath;
  253. if (string.IsNullOrWhiteSpace(appPath))
  254. {
  255. appPath = Path.Combine(ConfigurationManager.ApplicationPaths.ProgramDataPath, "ffmpeg");
  256. }
  257. var newPaths = GetEncoderPaths(appPath);
  258. if (string.IsNullOrWhiteSpace(newPaths.Item1) || string.IsNullOrWhiteSpace(newPaths.Item2) || IsSystemInstalledPath(appPath))
  259. {
  260. newPaths = TestForInstalledVersions();
  261. }
  262. if (!string.IsNullOrWhiteSpace(newPaths.Item1) && !string.IsNullOrWhiteSpace(newPaths.Item2))
  263. {
  264. FFMpegPath = newPaths.Item1;
  265. FFProbePath = newPaths.Item2;
  266. }
  267. LogPaths();
  268. }
  269. private Tuple<string, string> GetEncoderPaths(string configuredPath)
  270. {
  271. var appPath = configuredPath;
  272. if (!string.IsNullOrWhiteSpace(appPath))
  273. {
  274. if (FileSystem.DirectoryExists(appPath))
  275. {
  276. return GetPathsFromDirectory(appPath);
  277. }
  278. if (FileSystem.FileExists(appPath))
  279. {
  280. return new Tuple<string, string>(appPath, GetProbePathFromEncoderPath(appPath));
  281. }
  282. }
  283. return new Tuple<string, string>(null, null);
  284. }
  285. private Tuple<string, string> TestForInstalledVersions()
  286. {
  287. string encoderPath = null;
  288. string probePath = null;
  289. if (_hasExternalEncoder && ValidateVersion(_originalFFMpegPath, true))
  290. {
  291. encoderPath = _originalFFMpegPath;
  292. probePath = _originalFFProbePath;
  293. }
  294. if (string.IsNullOrWhiteSpace(encoderPath))
  295. {
  296. if (ValidateVersion("ffmpeg", true) && ValidateVersion("ffprobe", false))
  297. {
  298. encoderPath = "ffmpeg";
  299. probePath = "ffprobe";
  300. }
  301. }
  302. return new Tuple<string, string>(encoderPath, probePath);
  303. }
  304. private Tuple<string, string> GetPathsFromDirectory(string path)
  305. {
  306. // Since we can't predict the file extension, first try directly within the folder
  307. // If that doesn't pan out, then do a recursive search
  308. var files = FileSystem.GetFilePaths(path);
  309. var excludeExtensions = new[] { ".c" };
  310. var ffmpegPath = files.FirstOrDefault(i => string.Equals(Path.GetFileNameWithoutExtension(i), "ffmpeg", StringComparison.OrdinalIgnoreCase) && !excludeExtensions.Contains(Path.GetExtension(i) ?? string.Empty));
  311. var ffprobePath = files.FirstOrDefault(i => string.Equals(Path.GetFileNameWithoutExtension(i), "ffprobe", StringComparison.OrdinalIgnoreCase) && !excludeExtensions.Contains(Path.GetExtension(i) ?? string.Empty));
  312. if (string.IsNullOrWhiteSpace(ffmpegPath) || !FileSystem.FileExists(ffmpegPath))
  313. {
  314. files = FileSystem.GetFilePaths(path, true);
  315. ffmpegPath = files.FirstOrDefault(i => string.Equals(Path.GetFileNameWithoutExtension(i), "ffmpeg", StringComparison.OrdinalIgnoreCase) && !excludeExtensions.Contains(Path.GetExtension(i) ?? string.Empty));
  316. if (!string.IsNullOrWhiteSpace(ffmpegPath))
  317. {
  318. ffprobePath = GetProbePathFromEncoderPath(ffmpegPath);
  319. }
  320. }
  321. return new Tuple<string, string>(ffmpegPath, ffprobePath);
  322. }
  323. private string GetProbePathFromEncoderPath(string appPath)
  324. {
  325. return FileSystem.GetFilePaths(FileSystem.GetDirectoryName(appPath))
  326. .FirstOrDefault(i => string.Equals(Path.GetFileNameWithoutExtension(i), "ffprobe", StringComparison.OrdinalIgnoreCase));
  327. }
  328. private void LogPaths()
  329. {
  330. _logger.LogInformation("FFMpeg: {0}", FFMpegPath ?? "not found");
  331. _logger.LogInformation("FFProbe: {0}", FFProbePath ?? "not found");
  332. }
  333. private EncodingOptions GetEncodingOptions()
  334. {
  335. return ConfigurationManager.GetConfiguration<EncodingOptions>("encoding");
  336. }
  337. private List<string> _encoders = new List<string>();
  338. public void SetAvailableEncoders(IEnumerable<string> list)
  339. {
  340. _encoders = list.ToList();
  341. //_logger.Info("Supported encoders: {0}", string.Join(",", list.ToArray()));
  342. }
  343. private List<string> _decoders = new List<string>();
  344. public void SetAvailableDecoders(IEnumerable<string> list)
  345. {
  346. _decoders = list.ToList();
  347. //_logger.Info("Supported decoders: {0}", string.Join(",", list.ToArray()));
  348. }
  349. public bool SupportsEncoder(string encoder)
  350. {
  351. return _encoders.Contains(encoder, StringComparer.OrdinalIgnoreCase);
  352. }
  353. public bool SupportsDecoder(string decoder)
  354. {
  355. return _decoders.Contains(decoder, StringComparer.OrdinalIgnoreCase);
  356. }
  357. public bool CanEncodeToAudioCodec(string codec)
  358. {
  359. if (string.Equals(codec, "opus", StringComparison.OrdinalIgnoreCase))
  360. {
  361. codec = "libopus";
  362. }
  363. else if (string.Equals(codec, "mp3", StringComparison.OrdinalIgnoreCase))
  364. {
  365. codec = "libmp3lame";
  366. }
  367. return SupportsEncoder(codec);
  368. }
  369. public bool CanEncodeToSubtitleCodec(string codec)
  370. {
  371. // TODO
  372. return true;
  373. }
  374. /// <summary>
  375. /// Gets the encoder path.
  376. /// </summary>
  377. /// <value>The encoder path.</value>
  378. public string EncoderPath
  379. {
  380. get { return FFMpegPath; }
  381. }
  382. /// <summary>
  383. /// Gets the media info.
  384. /// </summary>
  385. /// <param name="request">The request.</param>
  386. /// <param name="cancellationToken">The cancellation token.</param>
  387. /// <returns>Task.</returns>
  388. public Task<MediaInfo> GetMediaInfo(MediaInfoRequest request, CancellationToken cancellationToken)
  389. {
  390. var extractChapters = request.MediaType == DlnaProfileType.Video && request.ExtractChapters;
  391. var inputFiles = MediaEncoderHelpers.GetInputArgument(FileSystem, request.MediaSource.Path, request.MediaSource.Protocol, request.MountedIso, request.PlayableStreamFileNames);
  392. var probeSize = EncodingHelper.GetProbeSizeArgument(inputFiles.Length);
  393. string analyzeDuration;
  394. if (request.MediaSource.AnalyzeDurationMs > 0)
  395. {
  396. analyzeDuration = "-analyzeduration " +
  397. (request.MediaSource.AnalyzeDurationMs * 1000).ToString();
  398. }
  399. else
  400. {
  401. analyzeDuration = EncodingHelper.GetAnalyzeDurationArgument(inputFiles.Length);
  402. }
  403. probeSize = probeSize + " " + analyzeDuration;
  404. probeSize = probeSize.Trim();
  405. var forceEnableLogging = request.MediaSource.Protocol != MediaProtocol.File;
  406. return GetMediaInfoInternal(GetInputArgument(inputFiles, request.MediaSource.Protocol), request.MediaSource.Path, request.MediaSource.Protocol, extractChapters,
  407. probeSize, request.MediaType == DlnaProfileType.Audio, request.MediaSource.VideoType, forceEnableLogging, cancellationToken);
  408. }
  409. /// <summary>
  410. /// Gets the input argument.
  411. /// </summary>
  412. /// <param name="inputFiles">The input files.</param>
  413. /// <param name="protocol">The protocol.</param>
  414. /// <returns>System.String.</returns>
  415. /// <exception cref="System.ArgumentException">Unrecognized InputType</exception>
  416. public string GetInputArgument(string[] inputFiles, MediaProtocol protocol)
  417. {
  418. return EncodingUtils.GetInputArgument(inputFiles.ToList(), protocol);
  419. }
  420. /// <summary>
  421. /// Gets the media info internal.
  422. /// </summary>
  423. /// <returns>Task{MediaInfoResult}.</returns>
  424. private async Task<MediaInfo> GetMediaInfoInternal(string inputPath,
  425. string primaryPath,
  426. MediaProtocol protocol,
  427. bool extractChapters,
  428. string probeSizeArgument,
  429. bool isAudio,
  430. VideoType? videoType,
  431. bool forceEnableLogging,
  432. CancellationToken cancellationToken)
  433. {
  434. var args = extractChapters
  435. ? "{0} -i {1} -threads 0 -v info -print_format json -show_streams -show_chapters -show_format"
  436. : "{0} -i {1} -threads 0 -v info -print_format json -show_streams -show_format";
  437. var process = _processFactory.Create(new ProcessOptions
  438. {
  439. CreateNoWindow = true,
  440. UseShellExecute = false,
  441. // Must consume both or ffmpeg may hang due to deadlocks. See comments below.
  442. RedirectStandardOutput = true,
  443. FileName = FFProbePath,
  444. Arguments = string.Format(args, probeSizeArgument, inputPath).Trim(),
  445. IsHidden = true,
  446. ErrorDialog = false,
  447. EnableRaisingEvents = true
  448. });
  449. if (forceEnableLogging)
  450. {
  451. _logger.LogInformation("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments);
  452. }
  453. else
  454. {
  455. _logger.LogDebug("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments);
  456. }
  457. using (var processWrapper = new ProcessWrapper(process, this, _logger))
  458. {
  459. StartProcess(processWrapper);
  460. try
  461. {
  462. //process.BeginErrorReadLine();
  463. var result = await _jsonSerializer.DeserializeFromStreamAsync<InternalMediaInfoResult>(process.StandardOutput.BaseStream).ConfigureAwait(false);
  464. if (result == null || (result.streams == null && result.format == null))
  465. {
  466. throw new Exception("ffprobe failed - streams and format are both null.");
  467. }
  468. if (result.streams != null)
  469. {
  470. // Normalize aspect ratio if invalid
  471. foreach (var stream in result.streams)
  472. {
  473. if (string.Equals(stream.display_aspect_ratio, "0:1", StringComparison.OrdinalIgnoreCase))
  474. {
  475. stream.display_aspect_ratio = string.Empty;
  476. }
  477. if (string.Equals(stream.sample_aspect_ratio, "0:1", StringComparison.OrdinalIgnoreCase))
  478. {
  479. stream.sample_aspect_ratio = string.Empty;
  480. }
  481. }
  482. }
  483. return new ProbeResultNormalizer(_logger, FileSystem).GetMediaInfo(result, videoType, isAudio, primaryPath, protocol);
  484. }
  485. catch
  486. {
  487. StopProcess(processWrapper, 100);
  488. throw;
  489. }
  490. }
  491. }
  492. /// <summary>
  493. /// The us culture
  494. /// </summary>
  495. protected readonly CultureInfo UsCulture = new CultureInfo("en-US");
  496. public Task<string> ExtractAudioImage(string path, int? imageStreamIndex, CancellationToken cancellationToken)
  497. {
  498. return ExtractImage(new[] { path }, null, null, imageStreamIndex, MediaProtocol.File, true, null, null, cancellationToken);
  499. }
  500. public Task<string> ExtractVideoImage(string[] inputFiles, string container, MediaProtocol protocol, MediaStream videoStream, Video3DFormat? threedFormat, TimeSpan? offset, CancellationToken cancellationToken)
  501. {
  502. return ExtractImage(inputFiles, container, videoStream, null, protocol, false, threedFormat, offset, cancellationToken);
  503. }
  504. public Task<string> ExtractVideoImage(string[] inputFiles, string container, MediaProtocol protocol, MediaStream imageStream, int? imageStreamIndex, CancellationToken cancellationToken)
  505. {
  506. return ExtractImage(inputFiles, container, imageStream, imageStreamIndex, protocol, false, null, null, cancellationToken);
  507. }
  508. private async Task<string> ExtractImage(string[] inputFiles, string container, MediaStream videoStream, int? imageStreamIndex, MediaProtocol protocol, bool isAudio,
  509. Video3DFormat? threedFormat, TimeSpan? offset, CancellationToken cancellationToken)
  510. {
  511. var inputArgument = GetInputArgument(inputFiles, protocol);
  512. if (isAudio)
  513. {
  514. if (imageStreamIndex.HasValue && imageStreamIndex.Value > 0)
  515. {
  516. // It seems for audio files we need to subtract 1 (for the audio stream??)
  517. imageStreamIndex = imageStreamIndex.Value - 1;
  518. }
  519. }
  520. else
  521. {
  522. try
  523. {
  524. return await ExtractImageInternal(inputArgument, container, videoStream, imageStreamIndex, threedFormat, offset, true, cancellationToken).ConfigureAwait(false);
  525. }
  526. catch (ArgumentException)
  527. {
  528. throw;
  529. }
  530. catch (Exception ex)
  531. {
  532. _logger.LogError(ex, "I-frame image extraction failed, will attempt standard way. Input: {arguments}", inputArgument);
  533. }
  534. }
  535. return await ExtractImageInternal(inputArgument, container, videoStream, imageStreamIndex, threedFormat, offset, false, cancellationToken).ConfigureAwait(false);
  536. }
  537. private async Task<string> ExtractImageInternal(string inputPath, string container, MediaStream videoStream, int? imageStreamIndex, Video3DFormat? threedFormat, TimeSpan? offset, bool useIFrame, CancellationToken cancellationToken)
  538. {
  539. if (string.IsNullOrEmpty(inputPath))
  540. {
  541. throw new ArgumentNullException("inputPath");
  542. }
  543. var tempExtractPath = Path.Combine(ConfigurationManager.ApplicationPaths.TempDirectory, Guid.NewGuid() + ".jpg");
  544. FileSystem.CreateDirectory(FileSystem.GetDirectoryName(tempExtractPath));
  545. // apply some filters to thumbnail extracted below (below) crop any black lines that we made and get the correct ar then scale to width 600.
  546. // This filter chain may have adverse effects on recorded tv thumbnails if ar changes during presentation ex. commercials @ diff ar
  547. var vf = "scale=600:trunc(600/dar/2)*2";
  548. if (threedFormat.HasValue)
  549. {
  550. switch (threedFormat.Value)
  551. {
  552. case Video3DFormat.HalfSideBySide:
  553. 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,scale=600:trunc(600/dar/2)*2";
  554. // hsbs crop width in half,scale to correct size, set the display aspect,crop out any black bars we may have made the scale width to 600. Work out the correct height based on the display aspect it will maintain the aspect where -1 in this case (3d) may not.
  555. break;
  556. case Video3DFormat.FullSideBySide:
  557. 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,scale=600:trunc(600/dar/2)*2";
  558. //fsbs crop width in half,set the display aspect,crop out any black bars we may have made the scale width to 600.
  559. break;
  560. case Video3DFormat.HalfTopAndBottom:
  561. 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,scale=600:trunc(600/dar/2)*2";
  562. //htab crop heigh in half,scale to correct size, set the display aspect,crop out any black bars we may have made the scale width to 600
  563. break;
  564. case Video3DFormat.FullTopAndBottom:
  565. 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,scale=600:trunc(600/dar/2)*2";
  566. // ftab crop heigt in half, set the display aspect,crop out any black bars we may have made the scale width to 600
  567. break;
  568. default:
  569. break;
  570. }
  571. }
  572. var mapArg = imageStreamIndex.HasValue ? (" -map 0:v:" + imageStreamIndex.Value.ToString(CultureInfo.InvariantCulture)) : string.Empty;
  573. var enableThumbnail = !new List<string> { "wtv" }.Contains(container ?? string.Empty, StringComparer.OrdinalIgnoreCase);
  574. // 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.
  575. var thumbnail = enableThumbnail ? ",thumbnail=24" : string.Empty;
  576. var args = useIFrame ? string.Format("-i {0}{3} -threads 0 -v quiet -vframes 1 -vf \"{2}{4}\" -f image2 \"{1}\"", inputPath, tempExtractPath, vf, mapArg, thumbnail) :
  577. string.Format("-i {0}{3} -threads 0 -v quiet -vframes 1 -vf \"{2}\" -f image2 \"{1}\"", inputPath, tempExtractPath, vf, mapArg);
  578. var probeSizeArgument = EncodingHelper.GetProbeSizeArgument(1);
  579. var analyzeDurationArgument = EncodingHelper.GetAnalyzeDurationArgument(1);
  580. if (!string.IsNullOrWhiteSpace(probeSizeArgument))
  581. {
  582. args = probeSizeArgument + " " + args;
  583. }
  584. if (!string.IsNullOrWhiteSpace(analyzeDurationArgument))
  585. {
  586. args = analyzeDurationArgument + " " + args;
  587. }
  588. if (offset.HasValue)
  589. {
  590. args = string.Format("-ss {0} ", GetTimeParameter(offset.Value)) + args;
  591. }
  592. var encodinghelper = new EncodingHelper(this, FileSystem, SubtitleEncoder());
  593. if (videoStream != null)
  594. {
  595. /* fix
  596. var decoder = encodinghelper.GetHardwareAcceleratedVideoDecoder(VideoType.VideoFile, videoStream, GetEncodingOptions());
  597. if (!string.IsNullOrWhiteSpace(decoder))
  598. {
  599. args = decoder + " " + args;
  600. }
  601. */
  602. }
  603. if (!string.IsNullOrWhiteSpace(container))
  604. {
  605. var inputFormat = encodinghelper.GetInputFormat(container);
  606. if (!string.IsNullOrWhiteSpace(inputFormat))
  607. {
  608. args = "-f " + inputFormat + " " + args;
  609. }
  610. }
  611. var process = _processFactory.Create(new ProcessOptions
  612. {
  613. CreateNoWindow = true,
  614. UseShellExecute = false,
  615. FileName = FFMpegPath,
  616. Arguments = args,
  617. IsHidden = true,
  618. ErrorDialog = false
  619. });
  620. _logger.LogDebug("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments);
  621. using (var processWrapper = new ProcessWrapper(process, this, _logger))
  622. {
  623. bool ranToCompletion;
  624. StartProcess(processWrapper);
  625. var timeoutMs = ConfigurationManager.Configuration.ImageExtractionTimeoutMs;
  626. if (timeoutMs <= 0)
  627. {
  628. timeoutMs = DefaultImageExtractionTimeoutMs;
  629. }
  630. ranToCompletion = await process.WaitForExitAsync(timeoutMs).ConfigureAwait(false);
  631. if (!ranToCompletion)
  632. {
  633. StopProcess(processWrapper, 1000);
  634. }
  635. var exitCode = ranToCompletion ? processWrapper.ExitCode ?? 0 : -1;
  636. var file = FileSystem.GetFileInfo(tempExtractPath);
  637. if (exitCode == -1 || !file.Exists || file.Length == 0)
  638. {
  639. var msg = string.Format("ffmpeg image extraction failed for {0}", inputPath);
  640. _logger.LogError(msg);
  641. throw new Exception(msg);
  642. }
  643. return tempExtractPath;
  644. }
  645. }
  646. public string GetTimeParameter(long ticks)
  647. {
  648. var time = TimeSpan.FromTicks(ticks);
  649. return GetTimeParameter(time);
  650. }
  651. public string GetTimeParameter(TimeSpan time)
  652. {
  653. return time.ToString(@"hh\:mm\:ss\.fff", UsCulture);
  654. }
  655. public async Task ExtractVideoImagesOnInterval(string[] inputFiles,
  656. string container,
  657. MediaStream videoStream,
  658. MediaProtocol protocol,
  659. Video3DFormat? threedFormat,
  660. TimeSpan interval,
  661. string targetDirectory,
  662. string filenamePrefix,
  663. int? maxWidth,
  664. CancellationToken cancellationToken)
  665. {
  666. var resourcePool = _thumbnailResourcePool;
  667. var inputArgument = GetInputArgument(inputFiles, protocol);
  668. var vf = "fps=fps=1/" + interval.TotalSeconds.ToString(UsCulture);
  669. if (maxWidth.HasValue)
  670. {
  671. var maxWidthParam = maxWidth.Value.ToString(UsCulture);
  672. vf += string.Format(",scale=min(iw\\,{0}):trunc(ow/dar/2)*2", maxWidthParam);
  673. }
  674. FileSystem.CreateDirectory(targetDirectory);
  675. var outputPath = Path.Combine(targetDirectory, filenamePrefix + "%05d.jpg");
  676. var args = string.Format("-i {0} -threads 0 -v quiet -vf \"{2}\" -f image2 \"{1}\"", inputArgument, outputPath, vf);
  677. var probeSizeArgument = EncodingHelper.GetProbeSizeArgument(1);
  678. var analyzeDurationArgument = EncodingHelper.GetAnalyzeDurationArgument(1);
  679. if (!string.IsNullOrWhiteSpace(probeSizeArgument))
  680. {
  681. args = probeSizeArgument + " " + args;
  682. }
  683. if (!string.IsNullOrWhiteSpace(analyzeDurationArgument))
  684. {
  685. args = analyzeDurationArgument + " " + args;
  686. }
  687. var encodinghelper = new EncodingHelper(this, FileSystem, SubtitleEncoder());
  688. if (videoStream != null)
  689. {
  690. /* fix
  691. var decoder = encodinghelper.GetHardwareAcceleratedVideoDecoder(VideoType.VideoFile, videoStream, GetEncodingOptions());
  692. if (!string.IsNullOrWhiteSpace(decoder))
  693. {
  694. args = decoder + " " + args;
  695. }
  696. */
  697. }
  698. if (!string.IsNullOrWhiteSpace(container))
  699. {
  700. var inputFormat = encodinghelper.GetInputFormat(container);
  701. if (!string.IsNullOrWhiteSpace(inputFormat))
  702. {
  703. args = "-f " + inputFormat + " " + args;
  704. }
  705. }
  706. var process = _processFactory.Create(new ProcessOptions
  707. {
  708. CreateNoWindow = true,
  709. UseShellExecute = false,
  710. FileName = FFMpegPath,
  711. Arguments = args,
  712. IsHidden = true,
  713. ErrorDialog = false
  714. });
  715. _logger.LogInformation(process.StartInfo.FileName + " " + process.StartInfo.Arguments);
  716. await resourcePool.WaitAsync(cancellationToken).ConfigureAwait(false);
  717. bool ranToCompletion = false;
  718. using (var processWrapper = new ProcessWrapper(process, this, _logger))
  719. {
  720. try
  721. {
  722. StartProcess(processWrapper);
  723. // Need to give ffmpeg enough time to make all the thumbnails, which could be a while,
  724. // but we still need to detect if the process hangs.
  725. // Making the assumption that as long as new jpegs are showing up, everything is good.
  726. bool isResponsive = true;
  727. int lastCount = 0;
  728. while (isResponsive)
  729. {
  730. if (await process.WaitForExitAsync(30000).ConfigureAwait(false))
  731. {
  732. ranToCompletion = true;
  733. break;
  734. }
  735. cancellationToken.ThrowIfCancellationRequested();
  736. var jpegCount = FileSystem.GetFilePaths(targetDirectory)
  737. .Count(i => string.Equals(Path.GetExtension(i), ".jpg", StringComparison.OrdinalIgnoreCase));
  738. isResponsive = (jpegCount > lastCount);
  739. lastCount = jpegCount;
  740. }
  741. if (!ranToCompletion)
  742. {
  743. StopProcess(processWrapper, 1000);
  744. }
  745. }
  746. finally
  747. {
  748. resourcePool.Release();
  749. }
  750. var exitCode = ranToCompletion ? processWrapper.ExitCode ?? 0 : -1;
  751. if (exitCode == -1)
  752. {
  753. var msg = string.Format("ffmpeg image extraction failed for {0}", inputArgument);
  754. _logger.LogError(msg);
  755. throw new Exception(msg);
  756. }
  757. }
  758. }
  759. public async Task<string> EncodeAudio(EncodingJobOptions options,
  760. IProgress<double> progress,
  761. CancellationToken cancellationToken)
  762. {
  763. var job = await new AudioEncoder(this,
  764. _logger,
  765. ConfigurationManager,
  766. FileSystem,
  767. IsoManager,
  768. LibraryManager,
  769. SessionManager,
  770. SubtitleEncoder(),
  771. MediaSourceManager(),
  772. _processFactory)
  773. .Start(options, progress, cancellationToken).ConfigureAwait(false);
  774. await job.TaskCompletionSource.Task.ConfigureAwait(false);
  775. return job.OutputFilePath;
  776. }
  777. public async Task<string> EncodeVideo(EncodingJobOptions options,
  778. IProgress<double> progress,
  779. CancellationToken cancellationToken)
  780. {
  781. _logger.LogError("EncodeVideo");
  782. var job = await new VideoEncoder(this,
  783. _logger,
  784. ConfigurationManager,
  785. FileSystem,
  786. IsoManager,
  787. LibraryManager,
  788. SessionManager,
  789. SubtitleEncoder(),
  790. MediaSourceManager(),
  791. _processFactory)
  792. .Start(options, progress, cancellationToken).ConfigureAwait(false);
  793. await job.TaskCompletionSource.Task.ConfigureAwait(false);
  794. return job.OutputFilePath;
  795. }
  796. private void StartProcess(ProcessWrapper process)
  797. {
  798. process.Process.Start();
  799. lock (_runningProcesses)
  800. {
  801. _runningProcesses.Add(process);
  802. }
  803. }
  804. private void StopProcess(ProcessWrapper process, int waitTimeMs)
  805. {
  806. try
  807. {
  808. if (process.Process.WaitForExit(waitTimeMs))
  809. {
  810. return;
  811. }
  812. }
  813. catch (Exception ex)
  814. {
  815. _logger.LogError(ex, "Error in WaitForExit");
  816. }
  817. try
  818. {
  819. _logger.LogInformation("Killing ffmpeg process");
  820. process.Process.Kill();
  821. }
  822. catch (Exception ex)
  823. {
  824. _logger.LogError(ex, "Error killing process");
  825. }
  826. }
  827. private void StopProcesses()
  828. {
  829. List<ProcessWrapper> proceses;
  830. lock (_runningProcesses)
  831. {
  832. proceses = _runningProcesses.ToList();
  833. _runningProcesses.Clear();
  834. }
  835. foreach (var process in proceses)
  836. {
  837. if (!process.HasExited)
  838. {
  839. StopProcess(process, 500);
  840. }
  841. }
  842. }
  843. public string EscapeSubtitleFilterPath(string path)
  844. {
  845. // https://ffmpeg.org/ffmpeg-filters.html#Notes-on-filtergraph-escaping
  846. // We need to double escape
  847. return path.Replace('\\', '/').Replace(":", "\\:").Replace("'", "'\\\\\\''");
  848. }
  849. /// <summary>
  850. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  851. /// </summary>
  852. public void Dispose()
  853. {
  854. Dispose(true);
  855. }
  856. /// <summary>
  857. /// Releases unmanaged and - optionally - managed resources.
  858. /// </summary>
  859. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  860. protected virtual void Dispose(bool dispose)
  861. {
  862. if (dispose)
  863. {
  864. StopProcesses();
  865. }
  866. }
  867. public Task ConvertImage(string inputPath, string outputPath)
  868. {
  869. throw new NotImplementedException();
  870. }
  871. public string[] GetPlayableStreamFileNames(string path, VideoType videoType)
  872. {
  873. throw new NotImplementedException();
  874. }
  875. public IEnumerable<string> GetPrimaryPlaylistVobFiles(string path, IIsoMount isoMount, uint? titleNumber)
  876. {
  877. throw new NotImplementedException();
  878. }
  879. public bool CanExtractSubtitles(string codec)
  880. {
  881. return false;
  882. }
  883. private class ProcessWrapper : IDisposable
  884. {
  885. public readonly IProcess Process;
  886. public bool HasExited;
  887. public int? ExitCode;
  888. private readonly MediaEncoder _mediaEncoder;
  889. private readonly ILogger _logger;
  890. public ProcessWrapper(IProcess process, MediaEncoder mediaEncoder, ILogger logger)
  891. {
  892. Process = process;
  893. _mediaEncoder = mediaEncoder;
  894. _logger = logger;
  895. Process.Exited += Process_Exited;
  896. }
  897. void Process_Exited(object sender, EventArgs e)
  898. {
  899. var process = (IProcess)sender;
  900. HasExited = true;
  901. try
  902. {
  903. ExitCode = process.ExitCode;
  904. }
  905. catch
  906. {
  907. }
  908. DisposeProcess(process);
  909. }
  910. private void DisposeProcess(IProcess process)
  911. {
  912. lock (_mediaEncoder._runningProcesses)
  913. {
  914. _mediaEncoder._runningProcesses.Remove(this);
  915. }
  916. try
  917. {
  918. process.Dispose();
  919. }
  920. catch
  921. {
  922. }
  923. }
  924. private bool _disposed;
  925. private readonly object _syncLock = new object();
  926. public void Dispose()
  927. {
  928. lock (_syncLock)
  929. {
  930. if (!_disposed)
  931. {
  932. if (Process != null)
  933. {
  934. Process.Exited -= Process_Exited;
  935. DisposeProcess(Process);
  936. }
  937. }
  938. _disposed = true;
  939. }
  940. }
  941. }
  942. }
  943. }