MediaEncoder.cs 41 KB

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