MediaEncoder.cs 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806
  1. using MediaBrowser.Common.IO;
  2. using MediaBrowser.Controller.Channels;
  3. using MediaBrowser.Controller.Configuration;
  4. using MediaBrowser.Controller.Library;
  5. using MediaBrowser.Controller.LiveTv;
  6. using MediaBrowser.Controller.MediaEncoding;
  7. using MediaBrowser.Controller.Session;
  8. using MediaBrowser.MediaEncoding.Probing;
  9. using MediaBrowser.Model.Dlna;
  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. namespace MediaBrowser.MediaEncoding.Encoder
  24. {
  25. /// <summary>
  26. /// Class MediaEncoder
  27. /// </summary>
  28. public class MediaEncoder : IMediaEncoder, IDisposable
  29. {
  30. /// <summary>
  31. /// The _logger
  32. /// </summary>
  33. private readonly ILogger _logger;
  34. /// <summary>
  35. /// Gets the json serializer.
  36. /// </summary>
  37. /// <value>The json serializer.</value>
  38. private readonly IJsonSerializer _jsonSerializer;
  39. /// <summary>
  40. /// The _thumbnail resource pool
  41. /// </summary>
  42. private readonly SemaphoreSlim _thumbnailResourcePool = new SemaphoreSlim(1, 1);
  43. /// <summary>
  44. /// The video image resource pool
  45. /// </summary>
  46. private readonly SemaphoreSlim _videoImageResourcePool = new SemaphoreSlim(1, 1);
  47. /// <summary>
  48. /// The audio image resource pool
  49. /// </summary>
  50. private readonly SemaphoreSlim _audioImageResourcePool = new SemaphoreSlim(2, 2);
  51. /// <summary>
  52. /// The FF probe resource pool
  53. /// </summary>
  54. private readonly SemaphoreSlim _ffProbeResourcePool = new SemaphoreSlim(2, 2);
  55. public string FFMpegPath { get; private set; }
  56. public string FFProbePath { get; private set; }
  57. public string Version { get; private set; }
  58. protected readonly IServerConfigurationManager ConfigurationManager;
  59. protected readonly IFileSystem FileSystem;
  60. protected readonly ILiveTvManager LiveTvManager;
  61. protected readonly IIsoManager IsoManager;
  62. protected readonly ILibraryManager LibraryManager;
  63. protected readonly IChannelManager ChannelManager;
  64. protected readonly ISessionManager SessionManager;
  65. protected readonly Func<ISubtitleEncoder> SubtitleEncoder;
  66. protected readonly Func<IMediaSourceManager> MediaSourceManager;
  67. private readonly List<ProcessWrapper> _runningProcesses = new List<ProcessWrapper>();
  68. public MediaEncoder(ILogger logger, IJsonSerializer jsonSerializer, string ffMpegPath, string ffProbePath, string version, IServerConfigurationManager configurationManager, IFileSystem fileSystem, ILiveTvManager liveTvManager, IIsoManager isoManager, ILibraryManager libraryManager, IChannelManager channelManager, ISessionManager sessionManager, Func<ISubtitleEncoder> subtitleEncoder, Func<IMediaSourceManager> mediaSourceManager)
  69. {
  70. _logger = logger;
  71. _jsonSerializer = jsonSerializer;
  72. Version = version;
  73. ConfigurationManager = configurationManager;
  74. FileSystem = fileSystem;
  75. LiveTvManager = liveTvManager;
  76. IsoManager = isoManager;
  77. LibraryManager = libraryManager;
  78. ChannelManager = channelManager;
  79. SessionManager = sessionManager;
  80. SubtitleEncoder = subtitleEncoder;
  81. MediaSourceManager = mediaSourceManager;
  82. FFProbePath = ffProbePath;
  83. FFMpegPath = ffMpegPath;
  84. }
  85. /// <summary>
  86. /// Gets the encoder path.
  87. /// </summary>
  88. /// <value>The encoder path.</value>
  89. public string EncoderPath
  90. {
  91. get { return FFMpegPath; }
  92. }
  93. /// <summary>
  94. /// Gets the media info.
  95. /// </summary>
  96. /// <param name="request">The request.</param>
  97. /// <param name="cancellationToken">The cancellation token.</param>
  98. /// <returns>Task.</returns>
  99. public Task<Model.MediaInfo.MediaInfo> GetMediaInfo(MediaInfoRequest request, CancellationToken cancellationToken)
  100. {
  101. var extractChapters = request.MediaType == DlnaProfileType.Video && request.ExtractChapters;
  102. var inputFiles = MediaEncoderHelpers.GetInputArgument(request.InputPath, request.Protocol, request.MountedIso, request.PlayableStreamFileNames);
  103. var extractKeyFrameInterval = request.ExtractKeyFrameInterval && request.Protocol == MediaProtocol.File && request.VideoType == VideoType.VideoFile;
  104. return GetMediaInfoInternal(GetInputArgument(inputFiles, request.Protocol), request.InputPath, request.Protocol, extractChapters, extractKeyFrameInterval,
  105. GetProbeSizeArgument(inputFiles, request.Protocol), request.MediaType == DlnaProfileType.Audio, cancellationToken);
  106. }
  107. /// <summary>
  108. /// Gets the input argument.
  109. /// </summary>
  110. /// <param name="inputFiles">The input files.</param>
  111. /// <param name="protocol">The protocol.</param>
  112. /// <returns>System.String.</returns>
  113. /// <exception cref="System.ArgumentException">Unrecognized InputType</exception>
  114. public string GetInputArgument(string[] inputFiles, MediaProtocol protocol)
  115. {
  116. return EncodingUtils.GetInputArgument(inputFiles.ToList(), protocol);
  117. }
  118. /// <summary>
  119. /// Gets the probe size argument.
  120. /// </summary>
  121. /// <param name="inputFiles">The input files.</param>
  122. /// <param name="protocol">The protocol.</param>
  123. /// <returns>System.String.</returns>
  124. public string GetProbeSizeArgument(string[] inputFiles, MediaProtocol protocol)
  125. {
  126. return EncodingUtils.GetProbeSizeArgument(inputFiles.Length > 1);
  127. }
  128. /// <summary>
  129. /// Gets the media info internal.
  130. /// </summary>
  131. /// <param name="inputPath">The input path.</param>
  132. /// <param name="primaryPath">The primary path.</param>
  133. /// <param name="protocol">The protocol.</param>
  134. /// <param name="extractChapters">if set to <c>true</c> [extract chapters].</param>
  135. /// <param name="extractKeyFrameInterval">if set to <c>true</c> [extract key frame interval].</param>
  136. /// <param name="probeSizeArgument">The probe size argument.</param>
  137. /// <param name="isAudio">if set to <c>true</c> [is audio].</param>
  138. /// <param name="cancellationToken">The cancellation token.</param>
  139. /// <returns>Task{MediaInfoResult}.</returns>
  140. /// <exception cref="System.ApplicationException"></exception>
  141. private async Task<Model.MediaInfo.MediaInfo> GetMediaInfoInternal(string inputPath,
  142. string primaryPath,
  143. MediaProtocol protocol,
  144. bool extractChapters,
  145. bool extractKeyFrameInterval,
  146. string probeSizeArgument,
  147. bool isAudio,
  148. CancellationToken cancellationToken)
  149. {
  150. var args = extractChapters
  151. ? "{0} -i {1} -threads 0 -v info -print_format json -show_streams -show_chapters -show_format"
  152. : "{0} -i {1} -threads 0 -v info -print_format json -show_streams -show_format";
  153. var process = new Process
  154. {
  155. StartInfo = new ProcessStartInfo
  156. {
  157. CreateNoWindow = true,
  158. UseShellExecute = false,
  159. // Must consume both or ffmpeg may hang due to deadlocks. See comments below.
  160. RedirectStandardOutput = true,
  161. RedirectStandardError = true,
  162. RedirectStandardInput = true,
  163. FileName = FFProbePath,
  164. Arguments = string.Format(args,
  165. probeSizeArgument, inputPath).Trim(),
  166. WindowStyle = ProcessWindowStyle.Hidden,
  167. ErrorDialog = false
  168. },
  169. EnableRaisingEvents = true
  170. };
  171. _logger.Debug("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments);
  172. await _ffProbeResourcePool.WaitAsync(cancellationToken).ConfigureAwait(false);
  173. var processWrapper = new ProcessWrapper(process, this);
  174. try
  175. {
  176. StartProcess(processWrapper);
  177. }
  178. catch (Exception ex)
  179. {
  180. _ffProbeResourcePool.Release();
  181. _logger.ErrorException("Error starting ffprobe", ex);
  182. throw;
  183. }
  184. try
  185. {
  186. process.BeginErrorReadLine();
  187. var result = _jsonSerializer.DeserializeFromStream<InternalMediaInfoResult>(process.StandardOutput.BaseStream);
  188. if (result != null)
  189. {
  190. if (result.streams != null)
  191. {
  192. // Normalize aspect ratio if invalid
  193. foreach (var stream in result.streams)
  194. {
  195. if (string.Equals(stream.display_aspect_ratio, "0:1", StringComparison.OrdinalIgnoreCase))
  196. {
  197. stream.display_aspect_ratio = string.Empty;
  198. }
  199. if (string.Equals(stream.sample_aspect_ratio, "0:1", StringComparison.OrdinalIgnoreCase))
  200. {
  201. stream.sample_aspect_ratio = string.Empty;
  202. }
  203. }
  204. }
  205. var mediaInfo = new ProbeResultNormalizer(_logger, FileSystem).GetMediaInfo(result, isAudio, primaryPath, protocol);
  206. if (extractKeyFrameInterval && mediaInfo.RunTimeTicks.HasValue)
  207. {
  208. foreach (var stream in mediaInfo.MediaStreams)
  209. {
  210. if (stream.Type == MediaStreamType.Video && string.Equals(stream.Codec, "h264", StringComparison.OrdinalIgnoreCase))
  211. {
  212. try
  213. {
  214. //stream.KeyFrames = await GetKeyFrames(inputPath, stream.Index, cancellationToken)
  215. // .ConfigureAwait(false);
  216. }
  217. catch (OperationCanceledException)
  218. {
  219. }
  220. catch (Exception ex)
  221. {
  222. _logger.ErrorException("Error getting key frame interval", ex);
  223. }
  224. }
  225. }
  226. }
  227. return mediaInfo;
  228. }
  229. }
  230. catch
  231. {
  232. StopProcess(processWrapper, 100, true);
  233. throw;
  234. }
  235. finally
  236. {
  237. _ffProbeResourcePool.Release();
  238. }
  239. throw new ApplicationException(string.Format("FFProbe failed for {0}", inputPath));
  240. }
  241. private async Task<List<int>> GetKeyFrames(string inputPath, int videoStreamIndex, CancellationToken cancellationToken)
  242. {
  243. const string args = "-i {0} -select_streams v:{1} -show_frames -show_entries frame=pkt_dts,key_frame -print_format compact";
  244. var process = new Process
  245. {
  246. StartInfo = new ProcessStartInfo
  247. {
  248. CreateNoWindow = true,
  249. UseShellExecute = false,
  250. // Must consume both or ffmpeg may hang due to deadlocks. See comments below.
  251. RedirectStandardOutput = true,
  252. RedirectStandardError = true,
  253. RedirectStandardInput = true,
  254. FileName = FFProbePath,
  255. Arguments = string.Format(args, inputPath, videoStreamIndex.ToString(CultureInfo.InvariantCulture)).Trim(),
  256. WindowStyle = ProcessWindowStyle.Hidden,
  257. ErrorDialog = false
  258. },
  259. EnableRaisingEvents = true
  260. };
  261. _logger.Debug("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments);
  262. var processWrapper = new ProcessWrapper(process, this);
  263. StartProcess(processWrapper);
  264. var lines = new List<int>();
  265. try
  266. {
  267. process.BeginErrorReadLine();
  268. await StartReadingOutput(process.StandardOutput.BaseStream, lines, 120000, cancellationToken).ConfigureAwait(false);
  269. }
  270. catch (OperationCanceledException)
  271. {
  272. if (cancellationToken.IsCancellationRequested)
  273. {
  274. throw;
  275. }
  276. }
  277. finally
  278. {
  279. StopProcess(processWrapper, 100, true);
  280. }
  281. return lines;
  282. }
  283. private async Task StartReadingOutput(Stream source, List<int> lines, int timeoutMs, CancellationToken cancellationToken)
  284. {
  285. try
  286. {
  287. using (var reader = new StreamReader(source))
  288. {
  289. while (!reader.EndOfStream)
  290. {
  291. cancellationToken.ThrowIfCancellationRequested();
  292. var line = await reader.ReadLineAsync().ConfigureAwait(false);
  293. var values = (line ?? string.Empty).Split('|')
  294. .Where(i => !string.IsNullOrWhiteSpace(i))
  295. .Select(i => i.Split('='))
  296. .Where(i => i.Length == 2)
  297. .ToDictionary(i => i[0], i => i[1]);
  298. string pktDts;
  299. int frameMs;
  300. if (values.TryGetValue("pkt_dts", out pktDts) && int.TryParse(pktDts, NumberStyles.Any, CultureInfo.InvariantCulture, out frameMs))
  301. {
  302. string keyFrame;
  303. if (values.TryGetValue("key_frame", out keyFrame) && string.Equals(keyFrame, "1", StringComparison.OrdinalIgnoreCase))
  304. {
  305. lines.Add(frameMs);
  306. }
  307. }
  308. }
  309. }
  310. }
  311. catch (OperationCanceledException)
  312. {
  313. throw;
  314. }
  315. catch (Exception ex)
  316. {
  317. _logger.ErrorException("Error reading ffprobe output", ex);
  318. }
  319. }
  320. /// <summary>
  321. /// The us culture
  322. /// </summary>
  323. protected readonly CultureInfo UsCulture = new CultureInfo("en-US");
  324. public Task<Stream> ExtractAudioImage(string path, CancellationToken cancellationToken)
  325. {
  326. return ExtractImage(new[] { path }, MediaProtocol.File, true, null, null, cancellationToken);
  327. }
  328. public Task<Stream> ExtractVideoImage(string[] inputFiles, MediaProtocol protocol, Video3DFormat? threedFormat,
  329. TimeSpan? offset, CancellationToken cancellationToken)
  330. {
  331. return ExtractImage(inputFiles, protocol, false, threedFormat, offset, cancellationToken);
  332. }
  333. private async Task<Stream> ExtractImage(string[] inputFiles, MediaProtocol protocol, bool isAudio,
  334. Video3DFormat? threedFormat, TimeSpan? offset, CancellationToken cancellationToken)
  335. {
  336. var resourcePool = isAudio ? _audioImageResourcePool : _videoImageResourcePool;
  337. var inputArgument = GetInputArgument(inputFiles, protocol);
  338. if (!isAudio)
  339. {
  340. try
  341. {
  342. return await ExtractImageInternal(inputArgument, protocol, threedFormat, offset, true, resourcePool, cancellationToken).ConfigureAwait(false);
  343. }
  344. catch (ArgumentException)
  345. {
  346. throw;
  347. }
  348. catch
  349. {
  350. _logger.Error("I-frame image extraction failed, will attempt standard way. Input: {0}", inputArgument);
  351. }
  352. }
  353. return await ExtractImageInternal(inputArgument, protocol, threedFormat, offset, false, resourcePool, cancellationToken).ConfigureAwait(false);
  354. }
  355. private async Task<Stream> ExtractImageInternal(string inputPath, MediaProtocol protocol, Video3DFormat? threedFormat, TimeSpan? offset, bool useIFrame, SemaphoreSlim resourcePool, CancellationToken cancellationToken)
  356. {
  357. if (string.IsNullOrEmpty(inputPath))
  358. {
  359. throw new ArgumentNullException("inputPath");
  360. }
  361. // 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.
  362. // This filter chain may have adverse effects on recorded tv thumbnails if ar changes during presentation ex. commercials @ diff ar
  363. var vf = "scale=600:trunc(600/dar/2)*2";
  364. if (threedFormat.HasValue)
  365. {
  366. switch (threedFormat.Value)
  367. {
  368. case Video3DFormat.HalfSideBySide:
  369. 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";
  370. // 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.
  371. break;
  372. case Video3DFormat.FullSideBySide:
  373. 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";
  374. //fsbs crop width in half,set the display aspect,crop out any black bars we may have made the scale width to 600.
  375. break;
  376. case Video3DFormat.HalfTopAndBottom:
  377. 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";
  378. //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
  379. break;
  380. case Video3DFormat.FullTopAndBottom:
  381. 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";
  382. // ftab crop heigt in half, set the display aspect,crop out any black bars we may have made the scale width to 600
  383. break;
  384. }
  385. }
  386. // TODO: Output in webp for smaller sizes
  387. // -f image2 -f webp
  388. // 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.
  389. var args = useIFrame ? string.Format("-i {0} -threads 1 -v quiet -vframes 1 -vf \"{2},thumbnail=30\" -f image2 \"{1}\"", inputPath, "-", vf) :
  390. string.Format("-i {0} -threads 1 -v quiet -vframes 1 -vf \"{2}\" -f image2 \"{1}\"", inputPath, "-", vf);
  391. var probeSize = GetProbeSizeArgument(new[] { inputPath }, protocol);
  392. if (!string.IsNullOrEmpty(probeSize))
  393. {
  394. args = probeSize + " " + args;
  395. }
  396. if (offset.HasValue)
  397. {
  398. args = string.Format("-ss {0} ", GetTimeParameter(offset.Value)) + args;
  399. }
  400. var process = new Process
  401. {
  402. StartInfo = new ProcessStartInfo
  403. {
  404. CreateNoWindow = true,
  405. UseShellExecute = false,
  406. FileName = FFMpegPath,
  407. Arguments = args,
  408. WindowStyle = ProcessWindowStyle.Hidden,
  409. ErrorDialog = false,
  410. RedirectStandardOutput = true,
  411. RedirectStandardError = true,
  412. RedirectStandardInput = true
  413. }
  414. };
  415. _logger.Debug("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments);
  416. await resourcePool.WaitAsync(cancellationToken).ConfigureAwait(false);
  417. var processWrapper = new ProcessWrapper(process, this);
  418. StartProcess(processWrapper);
  419. var memoryStream = new MemoryStream();
  420. #pragma warning disable 4014
  421. // Important - don't await the log task or we won't be able to kill ffmpeg when the user stops playback
  422. process.StandardOutput.BaseStream.CopyToAsync(memoryStream);
  423. #pragma warning restore 4014
  424. // MUST read both stdout and stderr asynchronously or a deadlock may occurr
  425. process.BeginErrorReadLine();
  426. var ranToCompletion = process.WaitForExit(10000);
  427. if (!ranToCompletion)
  428. {
  429. StopProcess(processWrapper, 1000, false);
  430. }
  431. resourcePool.Release();
  432. var exitCode = ranToCompletion ? processWrapper.ExitCode ?? 0 : -1;
  433. process.Dispose();
  434. if (exitCode == -1 || memoryStream.Length == 0)
  435. {
  436. memoryStream.Dispose();
  437. var msg = string.Format("ffmpeg image extraction failed for {0}", inputPath);
  438. _logger.Error(msg);
  439. throw new ApplicationException(msg);
  440. }
  441. memoryStream.Position = 0;
  442. return memoryStream;
  443. }
  444. public string GetTimeParameter(long ticks)
  445. {
  446. var time = TimeSpan.FromTicks(ticks);
  447. return GetTimeParameter(time);
  448. }
  449. public string GetTimeParameter(TimeSpan time)
  450. {
  451. return time.ToString(@"hh\:mm\:ss\.fff", UsCulture);
  452. }
  453. public async Task ExtractVideoImagesOnInterval(string[] inputFiles,
  454. MediaProtocol protocol,
  455. Video3DFormat? threedFormat,
  456. TimeSpan interval,
  457. string targetDirectory,
  458. string filenamePrefix,
  459. int? maxWidth,
  460. CancellationToken cancellationToken)
  461. {
  462. var resourcePool = _thumbnailResourcePool;
  463. var inputArgument = GetInputArgument(inputFiles, protocol);
  464. var vf = "fps=fps=1/" + interval.TotalSeconds.ToString(UsCulture);
  465. if (maxWidth.HasValue)
  466. {
  467. var maxWidthParam = maxWidth.Value.ToString(UsCulture);
  468. vf += string.Format(",scale=min(iw\\,{0}):trunc(ow/dar/2)*2", maxWidthParam);
  469. }
  470. Directory.CreateDirectory(targetDirectory);
  471. var outputPath = Path.Combine(targetDirectory, filenamePrefix + "%05d.jpg");
  472. var args = string.Format("-i {0} -threads 1 -v quiet -vf \"{2}\" -f image2 \"{1}\"", inputArgument, outputPath, vf);
  473. var probeSize = GetProbeSizeArgument(new[] { inputArgument }, protocol);
  474. if (!string.IsNullOrEmpty(probeSize))
  475. {
  476. args = probeSize + " " + args;
  477. }
  478. var process = new Process
  479. {
  480. StartInfo = new ProcessStartInfo
  481. {
  482. CreateNoWindow = true,
  483. UseShellExecute = false,
  484. FileName = FFMpegPath,
  485. Arguments = args,
  486. WindowStyle = ProcessWindowStyle.Hidden,
  487. ErrorDialog = false,
  488. RedirectStandardInput = true
  489. }
  490. };
  491. _logger.Info(process.StartInfo.FileName + " " + process.StartInfo.Arguments);
  492. await resourcePool.WaitAsync(cancellationToken).ConfigureAwait(false);
  493. bool ranToCompletion;
  494. var processWrapper = new ProcessWrapper(process, this);
  495. try
  496. {
  497. StartProcess(processWrapper);
  498. // Need to give ffmpeg enough time to make all the thumbnails, which could be a while,
  499. // but we still need to detect if the process hangs.
  500. // Making the assumption that as long as new jpegs are showing up, everything is good.
  501. bool isResponsive = true;
  502. int lastCount = 0;
  503. while (isResponsive && !process.WaitForExit(30000))
  504. {
  505. cancellationToken.ThrowIfCancellationRequested();
  506. int jpegCount = Directory.GetFiles(targetDirectory)
  507. .Count(i => string.Equals(Path.GetExtension(i), ".jpg", StringComparison.OrdinalIgnoreCase));
  508. isResponsive = (jpegCount > lastCount);
  509. lastCount = jpegCount;
  510. }
  511. ranToCompletion = process.HasExited;
  512. if (!ranToCompletion)
  513. {
  514. StopProcess(processWrapper, 1000, false);
  515. }
  516. }
  517. finally
  518. {
  519. resourcePool.Release();
  520. }
  521. var exitCode = ranToCompletion ? processWrapper.ExitCode ?? 0 : -1;
  522. process.Dispose();
  523. if (exitCode == -1)
  524. {
  525. var msg = string.Format("ffmpeg image extraction failed for {0}", inputArgument);
  526. _logger.Error(msg);
  527. throw new ApplicationException(msg);
  528. }
  529. }
  530. public async Task<string> EncodeAudio(EncodingJobOptions options,
  531. IProgress<double> progress,
  532. CancellationToken cancellationToken)
  533. {
  534. var job = await new AudioEncoder(this,
  535. _logger,
  536. ConfigurationManager,
  537. FileSystem,
  538. IsoManager,
  539. LibraryManager,
  540. SessionManager,
  541. SubtitleEncoder(),
  542. MediaSourceManager())
  543. .Start(options, progress, cancellationToken).ConfigureAwait(false);
  544. await job.TaskCompletionSource.Task.ConfigureAwait(false);
  545. return job.OutputFilePath;
  546. }
  547. public async Task<string> EncodeVideo(EncodingJobOptions options,
  548. IProgress<double> progress,
  549. CancellationToken cancellationToken)
  550. {
  551. var job = await new VideoEncoder(this,
  552. _logger,
  553. ConfigurationManager,
  554. FileSystem,
  555. IsoManager,
  556. LibraryManager,
  557. SessionManager,
  558. SubtitleEncoder(),
  559. MediaSourceManager())
  560. .Start(options, progress, cancellationToken).ConfigureAwait(false);
  561. await job.TaskCompletionSource.Task.ConfigureAwait(false);
  562. return job.OutputFilePath;
  563. }
  564. private void StartProcess(ProcessWrapper process)
  565. {
  566. process.Process.Start();
  567. lock (_runningProcesses)
  568. {
  569. _runningProcesses.Add(process);
  570. }
  571. }
  572. private void StopProcess(ProcessWrapper process, int waitTimeMs, bool enableForceKill)
  573. {
  574. try
  575. {
  576. _logger.Info("Killing ffmpeg process");
  577. try
  578. {
  579. process.Process.StandardInput.WriteLine("q");
  580. }
  581. catch (Exception)
  582. {
  583. _logger.Error("Error sending q command to process");
  584. }
  585. try
  586. {
  587. if (process.Process.WaitForExit(waitTimeMs))
  588. {
  589. return;
  590. }
  591. }
  592. catch (Exception ex)
  593. {
  594. _logger.Error("Error in WaitForExit", ex);
  595. }
  596. if (enableForceKill)
  597. {
  598. process.Process.Kill();
  599. }
  600. }
  601. catch (Exception ex)
  602. {
  603. _logger.ErrorException("Error killing process", ex);
  604. }
  605. }
  606. private void StopProcesses()
  607. {
  608. List<ProcessWrapper> proceses;
  609. lock (_runningProcesses)
  610. {
  611. proceses = _runningProcesses.ToList();
  612. }
  613. _runningProcesses.Clear();
  614. foreach (var process in proceses)
  615. {
  616. if (!process.HasExited)
  617. {
  618. StopProcess(process, 500, true);
  619. }
  620. }
  621. }
  622. /// <summary>
  623. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  624. /// </summary>
  625. public void Dispose()
  626. {
  627. Dispose(true);
  628. }
  629. /// <summary>
  630. /// Releases unmanaged and - optionally - managed resources.
  631. /// </summary>
  632. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  633. protected virtual void Dispose(bool dispose)
  634. {
  635. if (dispose)
  636. {
  637. _videoImageResourcePool.Dispose();
  638. StopProcesses();
  639. }
  640. }
  641. private class ProcessWrapper
  642. {
  643. public readonly Process Process;
  644. public bool HasExited;
  645. public int? ExitCode;
  646. private readonly MediaEncoder _mediaEncoder;
  647. public ProcessWrapper(Process process, MediaEncoder mediaEncoder)
  648. {
  649. Process = process;
  650. this._mediaEncoder = mediaEncoder;
  651. Process.Exited += Process_Exited;
  652. }
  653. void Process_Exited(object sender, EventArgs e)
  654. {
  655. var process = (Process)sender;
  656. HasExited = true;
  657. ExitCode = process.ExitCode;
  658. lock (_mediaEncoder._runningProcesses)
  659. {
  660. _mediaEncoder._runningProcesses.Remove(this);
  661. }
  662. process.Dispose();
  663. }
  664. }
  665. }
  666. }