2
0

MediaEncoder.cs 43 KB

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