MediaEncoder.cs 42 KB

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