MediaEncoder.cs 44 KB

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