MediaEncoder.cs 42 KB

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