MediaEncoder.cs 45 KB

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