2
0

MediaEncoder.cs 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087
  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.Dto;
  11. using MediaBrowser.Model.Entities;
  12. using MediaBrowser.Model.Extensions;
  13. using MediaBrowser.Model.IO;
  14. using MediaBrowser.Model.Logging;
  15. using MediaBrowser.Model.MediaInfo;
  16. using MediaBrowser.Model.Serialization;
  17. using System;
  18. using System.Collections.Generic;
  19. using System.Diagnostics;
  20. using System.Globalization;
  21. using System.IO;
  22. using System.Linq;
  23. using System.Threading;
  24. using System.Threading.Tasks;
  25. using CommonIO;
  26. namespace MediaBrowser.MediaEncoding.Encoder
  27. {
  28. /// <summary>
  29. /// Class MediaEncoder
  30. /// </summary>
  31. public class MediaEncoder : IMediaEncoder, IDisposable
  32. {
  33. /// <summary>
  34. /// The _logger
  35. /// </summary>
  36. private readonly ILogger _logger;
  37. /// <summary>
  38. /// Gets the json serializer.
  39. /// </summary>
  40. /// <value>The json serializer.</value>
  41. private readonly IJsonSerializer _jsonSerializer;
  42. /// <summary>
  43. /// The _thumbnail resource pool
  44. /// </summary>
  45. private readonly SemaphoreSlim _thumbnailResourcePool = new SemaphoreSlim(1, 1);
  46. /// <summary>
  47. /// The video image resource pool
  48. /// </summary>
  49. private readonly SemaphoreSlim _videoImageResourcePool = new SemaphoreSlim(1, 1);
  50. /// <summary>
  51. /// The audio image resource pool
  52. /// </summary>
  53. private readonly SemaphoreSlim _audioImageResourcePool = new SemaphoreSlim(2, 2);
  54. /// <summary>
  55. /// The FF probe resource pool
  56. /// </summary>
  57. private readonly SemaphoreSlim _ffProbeResourcePool = new SemaphoreSlim(2, 2);
  58. public string FFMpegPath { get; private set; }
  59. public string FFProbePath { get; private set; }
  60. public string Version { 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. 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)
  72. {
  73. _logger = logger;
  74. _jsonSerializer = jsonSerializer;
  75. Version = version;
  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. }
  88. public void SetAvailableEncoders(List<string> list)
  89. {
  90. }
  91. private List<string> _decoders = new List<string>();
  92. public void SetAvailableDecoders(List<string> list)
  93. {
  94. _decoders = list.ToList();
  95. }
  96. public bool SupportsDecoder(string decoder)
  97. {
  98. return _decoders.Contains(decoder, StringComparer.OrdinalIgnoreCase);
  99. }
  100. /// <summary>
  101. /// Gets the encoder path.
  102. /// </summary>
  103. /// <value>The encoder path.</value>
  104. public string EncoderPath
  105. {
  106. get { return FFMpegPath; }
  107. }
  108. /// <summary>
  109. /// Gets the media info.
  110. /// </summary>
  111. /// <param name="request">The request.</param>
  112. /// <param name="cancellationToken">The cancellation token.</param>
  113. /// <returns>Task.</returns>
  114. public Task<Model.MediaInfo.MediaInfo> GetMediaInfo(MediaInfoRequest request, CancellationToken cancellationToken)
  115. {
  116. var extractChapters = request.MediaType == DlnaProfileType.Video && request.ExtractChapters;
  117. var inputFiles = MediaEncoderHelpers.GetInputArgument(FileSystem, request.InputPath, request.Protocol, request.MountedIso, request.PlayableStreamFileNames);
  118. var extractKeyFrameInterval = request.ExtractKeyFrameInterval && request.Protocol == MediaProtocol.File && request.VideoType == VideoType.VideoFile;
  119. return GetMediaInfoInternal(GetInputArgument(inputFiles, request.Protocol), request.InputPath, request.Protocol, extractChapters, extractKeyFrameInterval,
  120. GetProbeSizeArgument(inputFiles, request.Protocol), request.MediaType == DlnaProfileType.Audio, request.VideoType, cancellationToken);
  121. }
  122. /// <summary>
  123. /// Gets the input argument.
  124. /// </summary>
  125. /// <param name="inputFiles">The input files.</param>
  126. /// <param name="protocol">The protocol.</param>
  127. /// <returns>System.String.</returns>
  128. /// <exception cref="System.ArgumentException">Unrecognized InputType</exception>
  129. public string GetInputArgument(string[] inputFiles, MediaProtocol protocol)
  130. {
  131. return EncodingUtils.GetInputArgument(inputFiles.ToList(), protocol);
  132. }
  133. /// <summary>
  134. /// Gets the probe size argument.
  135. /// </summary>
  136. /// <param name="inputFiles">The input files.</param>
  137. /// <param name="protocol">The protocol.</param>
  138. /// <returns>System.String.</returns>
  139. public string GetProbeSizeArgument(string[] inputFiles, MediaProtocol protocol)
  140. {
  141. return EncodingUtils.GetProbeSizeArgument(inputFiles.Length > 1);
  142. }
  143. /// <summary>
  144. /// Gets the media info internal.
  145. /// </summary>
  146. /// <param name="inputPath">The input path.</param>
  147. /// <param name="primaryPath">The primary path.</param>
  148. /// <param name="protocol">The protocol.</param>
  149. /// <param name="extractChapters">if set to <c>true</c> [extract chapters].</param>
  150. /// <param name="extractKeyFrameInterval">if set to <c>true</c> [extract key frame interval].</param>
  151. /// <param name="probeSizeArgument">The probe size argument.</param>
  152. /// <param name="isAudio">if set to <c>true</c> [is audio].</param>
  153. /// <param name="videoType">Type of the video.</param>
  154. /// <param name="cancellationToken">The cancellation token.</param>
  155. /// <returns>Task{MediaInfoResult}.</returns>
  156. /// <exception cref="System.ApplicationException"></exception>
  157. private async Task<Model.MediaInfo.MediaInfo> GetMediaInfoInternal(string inputPath,
  158. string primaryPath,
  159. MediaProtocol protocol,
  160. bool extractChapters,
  161. bool extractKeyFrameInterval,
  162. string probeSizeArgument,
  163. bool isAudio,
  164. VideoType videoType,
  165. CancellationToken cancellationToken)
  166. {
  167. var args = extractChapters
  168. ? "{0} -i {1} -threads 0 -v info -print_format json -show_streams -show_chapters -show_format"
  169. : "{0} -i {1} -threads 0 -v info -print_format json -show_streams -show_format";
  170. var process = new Process
  171. {
  172. StartInfo = new ProcessStartInfo
  173. {
  174. CreateNoWindow = true,
  175. UseShellExecute = false,
  176. // Must consume both or ffmpeg may hang due to deadlocks. See comments below.
  177. RedirectStandardOutput = true,
  178. RedirectStandardError = true,
  179. RedirectStandardInput = true,
  180. FileName = FFProbePath,
  181. Arguments = string.Format(args,
  182. probeSizeArgument, inputPath).Trim(),
  183. WindowStyle = ProcessWindowStyle.Hidden,
  184. ErrorDialog = false
  185. },
  186. EnableRaisingEvents = true
  187. };
  188. _logger.Debug("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments);
  189. using (var processWrapper = new ProcessWrapper(process, this, _logger))
  190. {
  191. await _ffProbeResourcePool.WaitAsync(cancellationToken).ConfigureAwait(false);
  192. try
  193. {
  194. StartProcess(processWrapper);
  195. }
  196. catch (Exception ex)
  197. {
  198. _ffProbeResourcePool.Release();
  199. _logger.ErrorException("Error starting ffprobe", ex);
  200. throw;
  201. }
  202. try
  203. {
  204. process.BeginErrorReadLine();
  205. var result = _jsonSerializer.DeserializeFromStream<InternalMediaInfoResult>(process.StandardOutput.BaseStream);
  206. if (result.streams == null && result.format == null)
  207. {
  208. throw new ApplicationException("ffprobe failed - streams and format are both null.");
  209. }
  210. if (result.streams != null)
  211. {
  212. // Normalize aspect ratio if invalid
  213. foreach (var stream in result.streams)
  214. {
  215. if (string.Equals(stream.display_aspect_ratio, "0:1", StringComparison.OrdinalIgnoreCase))
  216. {
  217. stream.display_aspect_ratio = string.Empty;
  218. }
  219. if (string.Equals(stream.sample_aspect_ratio, "0:1", StringComparison.OrdinalIgnoreCase))
  220. {
  221. stream.sample_aspect_ratio = string.Empty;
  222. }
  223. }
  224. }
  225. var mediaInfo = new ProbeResultNormalizer(_logger, FileSystem).GetMediaInfo(result, videoType, isAudio, primaryPath, protocol);
  226. var videoStream = mediaInfo.MediaStreams.FirstOrDefault(i => i.Type == MediaStreamType.Video);
  227. if (videoStream != null)
  228. {
  229. var isInterlaced = await DetectInterlaced(mediaInfo, videoStream, inputPath, probeSizeArgument).ConfigureAwait(false);
  230. if (isInterlaced)
  231. {
  232. videoStream.IsInterlaced = true;
  233. }
  234. }
  235. if (extractKeyFrameInterval && mediaInfo.RunTimeTicks.HasValue)
  236. {
  237. if (ConfigurationManager.Configuration.EnableVideoFrameByFrameAnalysis && mediaInfo.Size.HasValue)
  238. {
  239. foreach (var stream in mediaInfo.MediaStreams)
  240. {
  241. if (EnableKeyframeExtraction(mediaInfo, stream))
  242. {
  243. try
  244. {
  245. stream.KeyFrames = await GetKeyFrames(inputPath, stream.Index, cancellationToken).ConfigureAwait(false);
  246. }
  247. catch (OperationCanceledException)
  248. {
  249. }
  250. catch (Exception ex)
  251. {
  252. _logger.ErrorException("Error getting key frame interval", ex);
  253. }
  254. }
  255. }
  256. }
  257. }
  258. return mediaInfo;
  259. }
  260. catch
  261. {
  262. StopProcess(processWrapper, 100, true);
  263. throw;
  264. }
  265. finally
  266. {
  267. _ffProbeResourcePool.Release();
  268. }
  269. }
  270. throw new ApplicationException(string.Format("FFProbe failed for {0}", inputPath));
  271. }
  272. private async Task<bool> DetectInterlaced(MediaSourceInfo video, MediaStream videoStream, string inputPath, string probeSizeArgument)
  273. {
  274. if (video.Protocol != MediaProtocol.File)
  275. {
  276. return false;
  277. }
  278. var formats = (video.Container ?? string.Empty).Split(',').ToList();
  279. // Take a shortcut and limit this to containers that are likely to have interlaced content
  280. if (!formats.Contains("ts", StringComparer.OrdinalIgnoreCase) &&
  281. !formats.Contains("mpegts", StringComparer.OrdinalIgnoreCase) &&
  282. !formats.Contains("wtv", StringComparer.OrdinalIgnoreCase))
  283. {
  284. return false;
  285. }
  286. var args = "{0} -i {1} -map 0:v:{2} -filter:v idet -frames:v 500 -an -f null /dev/null";
  287. var process = new Process
  288. {
  289. StartInfo = new ProcessStartInfo
  290. {
  291. CreateNoWindow = true,
  292. UseShellExecute = false,
  293. // Must consume both or ffmpeg may hang due to deadlocks. See comments below.
  294. RedirectStandardOutput = true,
  295. RedirectStandardError = true,
  296. RedirectStandardInput = true,
  297. FileName = FFMpegPath,
  298. Arguments = string.Format(args, probeSizeArgument, inputPath, videoStream.Index.ToString(CultureInfo.InvariantCulture)).Trim(),
  299. WindowStyle = ProcessWindowStyle.Hidden,
  300. ErrorDialog = false
  301. },
  302. EnableRaisingEvents = true
  303. };
  304. _logger.Info("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments);
  305. var idetFoundInterlaced = false;
  306. using (var processWrapper = new ProcessWrapper(process, this, _logger))
  307. {
  308. try
  309. {
  310. StartProcess(processWrapper);
  311. }
  312. catch (Exception ex)
  313. {
  314. _logger.ErrorException("Error starting ffprobe", ex);
  315. throw;
  316. }
  317. try
  318. {
  319. process.BeginOutputReadLine();
  320. using (var reader = new StreamReader(process.StandardError.BaseStream))
  321. {
  322. while (!reader.EndOfStream)
  323. {
  324. var line = await reader.ReadLineAsync().ConfigureAwait(false);
  325. if (line.StartsWith("[Parsed_idet", StringComparison.OrdinalIgnoreCase))
  326. {
  327. var idetResult = AnalyzeIdetResult(line);
  328. if (idetResult.HasValue)
  329. {
  330. if (!idetResult.Value)
  331. {
  332. return false;
  333. }
  334. idetFoundInterlaced = true;
  335. }
  336. }
  337. }
  338. }
  339. }
  340. catch
  341. {
  342. StopProcess(processWrapper, 100, true);
  343. throw;
  344. }
  345. }
  346. return idetFoundInterlaced;
  347. }
  348. private bool? AnalyzeIdetResult(string line)
  349. {
  350. // As you can see, the filter only guessed one frame as progressive.
  351. // 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.
  352. // 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.
  353. // http://awel.domblogger.net/videoTranscode/interlace.html
  354. var index = line.IndexOf("detection:", StringComparison.OrdinalIgnoreCase);
  355. if (index == -1)
  356. {
  357. return null;
  358. }
  359. line = line.Substring(index).Trim();
  360. var parts = line.Split(' ').Where(i => !string.IsNullOrWhiteSpace(i)).Select(i => i.Trim()).ToList();
  361. if (parts.Count < 2)
  362. {
  363. return null;
  364. }
  365. double tff = 0;
  366. double bff = 0;
  367. double progressive = 0;
  368. double undetermined = 0;
  369. double total = 0;
  370. for (var i = 0; i < parts.Count - 1; i++)
  371. {
  372. var part = parts[i];
  373. if (string.Equals(part, "tff:", StringComparison.OrdinalIgnoreCase))
  374. {
  375. tff = GetNextPart(parts, i);
  376. total += tff;
  377. }
  378. else if (string.Equals(part, "bff:", StringComparison.OrdinalIgnoreCase))
  379. {
  380. bff = GetNextPart(parts, i);
  381. total += tff;
  382. }
  383. else if (string.Equals(part, "progressive:", StringComparison.OrdinalIgnoreCase))
  384. {
  385. progressive = GetNextPart(parts, i);
  386. total += progressive;
  387. }
  388. else if (string.Equals(part, "undetermined:", StringComparison.OrdinalIgnoreCase))
  389. {
  390. undetermined = GetNextPart(parts, i);
  391. total += undetermined;
  392. }
  393. }
  394. if (total == 0)
  395. {
  396. return null;
  397. }
  398. if ((undetermined / total) >= .3)
  399. {
  400. return false;
  401. }
  402. if (((tff + bff) / total) >= .65)
  403. {
  404. return true;
  405. }
  406. return false;
  407. }
  408. private int GetNextPart(List<string> parts, int index)
  409. {
  410. var next = parts[index + 1];
  411. int value;
  412. if (int.TryParse(next, NumberStyles.Any, CultureInfo.InvariantCulture, out value))
  413. {
  414. return value;
  415. }
  416. return 0;
  417. }
  418. private bool EnableKeyframeExtraction(MediaSourceInfo mediaSource, MediaStream videoStream)
  419. {
  420. if (videoStream.Type == MediaStreamType.Video && string.Equals(videoStream.Codec, "h264", StringComparison.OrdinalIgnoreCase) &&
  421. !videoStream.IsInterlaced &&
  422. !(videoStream.IsAnamorphic ?? false))
  423. {
  424. var audioStreams = mediaSource.MediaStreams.Where(i => i.Type == MediaStreamType.Audio).ToList();
  425. // If it has aac audio then it will probably direct stream anyway, so don't bother with this
  426. if (audioStreams.Count == 1 && string.Equals(audioStreams[0].Codec, "aac", StringComparison.OrdinalIgnoreCase))
  427. {
  428. return false;
  429. }
  430. return true;
  431. }
  432. return false;
  433. }
  434. private async Task<List<int>> GetKeyFrames(string inputPath, int videoStreamIndex, CancellationToken cancellationToken)
  435. {
  436. inputPath = inputPath.Split(new[] { ':' }, 2).Last().Trim('"');
  437. const string args = "-show_packets -print_format compact -select_streams v:{1} -show_entries packet=flags -show_entries packet=pts_time \"{0}\"";
  438. var process = new Process
  439. {
  440. StartInfo = new ProcessStartInfo
  441. {
  442. CreateNoWindow = true,
  443. UseShellExecute = false,
  444. // Must consume both or ffmpeg may hang due to deadlocks. See comments below.
  445. RedirectStandardOutput = true,
  446. RedirectStandardError = true,
  447. FileName = FFProbePath,
  448. Arguments = string.Format(args, inputPath, videoStreamIndex.ToString(CultureInfo.InvariantCulture)).Trim(),
  449. WindowStyle = ProcessWindowStyle.Hidden,
  450. ErrorDialog = false
  451. },
  452. EnableRaisingEvents = true
  453. };
  454. _logger.Info("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments);
  455. using (process)
  456. {
  457. var start = DateTime.UtcNow;
  458. process.Start();
  459. var lines = new List<int>();
  460. try
  461. {
  462. process.BeginErrorReadLine();
  463. await StartReadingOutput(process.StandardOutput.BaseStream, lines, cancellationToken).ConfigureAwait(false);
  464. }
  465. catch (OperationCanceledException)
  466. {
  467. if (cancellationToken.IsCancellationRequested)
  468. {
  469. throw;
  470. }
  471. }
  472. process.WaitForExit();
  473. _logger.Info("Keyframe extraction took {0} seconds", (DateTime.UtcNow - start).TotalSeconds);
  474. //_logger.Debug("Found keyframes {0}", string.Join(",", lines.ToArray()));
  475. return lines;
  476. }
  477. }
  478. private async Task StartReadingOutput(Stream source, List<int> keyframes, CancellationToken cancellationToken)
  479. {
  480. try
  481. {
  482. using (var reader = new StreamReader(source))
  483. {
  484. var text = await reader.ReadToEndAsync().ConfigureAwait(false);
  485. var lines = StringHelper.RegexSplit(text, "[\r\n]+");
  486. foreach (var line in lines)
  487. {
  488. if (string.IsNullOrWhiteSpace(line))
  489. {
  490. continue;
  491. }
  492. var values = line.Split('|')
  493. .Where(i => !string.IsNullOrWhiteSpace(i))
  494. .Select(i => i.Split('='))
  495. .Where(i => i.Length == 2)
  496. .ToDictionary(i => i[0], i => i[1]);
  497. string flags;
  498. if (values.TryGetValue("flags", out flags) && string.Equals(flags, "k", StringComparison.OrdinalIgnoreCase))
  499. {
  500. string pts_time;
  501. double frameSeconds;
  502. if (values.TryGetValue("pts_time", out pts_time) && double.TryParse(pts_time, NumberStyles.Any, CultureInfo.InvariantCulture, out frameSeconds))
  503. {
  504. var ms = frameSeconds * 1000;
  505. keyframes.Add(Convert.ToInt32(ms));
  506. }
  507. }
  508. }
  509. }
  510. }
  511. catch (OperationCanceledException)
  512. {
  513. throw;
  514. }
  515. catch (Exception ex)
  516. {
  517. _logger.ErrorException("Error reading ffprobe output", ex);
  518. }
  519. }
  520. /// <summary>
  521. /// The us culture
  522. /// </summary>
  523. protected readonly CultureInfo UsCulture = new CultureInfo("en-US");
  524. public Task<Stream> ExtractAudioImage(string path, CancellationToken cancellationToken)
  525. {
  526. return ExtractImage(new[] { path }, MediaProtocol.File, true, null, null, cancellationToken);
  527. }
  528. public Task<Stream> ExtractVideoImage(string[] inputFiles, MediaProtocol protocol, Video3DFormat? threedFormat,
  529. TimeSpan? offset, CancellationToken cancellationToken)
  530. {
  531. return ExtractImage(inputFiles, protocol, false, threedFormat, offset, cancellationToken);
  532. }
  533. private async Task<Stream> ExtractImage(string[] inputFiles, MediaProtocol protocol, bool isAudio,
  534. Video3DFormat? threedFormat, TimeSpan? offset, CancellationToken cancellationToken)
  535. {
  536. var resourcePool = isAudio ? _audioImageResourcePool : _videoImageResourcePool;
  537. var inputArgument = GetInputArgument(inputFiles, protocol);
  538. if (!isAudio)
  539. {
  540. try
  541. {
  542. return await ExtractImageInternal(inputArgument, protocol, threedFormat, offset, true, resourcePool, cancellationToken).ConfigureAwait(false);
  543. }
  544. catch (ArgumentException)
  545. {
  546. throw;
  547. }
  548. catch
  549. {
  550. _logger.Error("I-frame image extraction failed, will attempt standard way. Input: {0}", inputArgument);
  551. }
  552. }
  553. return await ExtractImageInternal(inputArgument, protocol, threedFormat, offset, false, resourcePool, cancellationToken).ConfigureAwait(false);
  554. }
  555. private async Task<Stream> ExtractImageInternal(string inputPath, MediaProtocol protocol, Video3DFormat? threedFormat, TimeSpan? offset, bool useIFrame, SemaphoreSlim resourcePool, CancellationToken cancellationToken)
  556. {
  557. if (string.IsNullOrEmpty(inputPath))
  558. {
  559. throw new ArgumentNullException("inputPath");
  560. }
  561. // 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.
  562. // This filter chain may have adverse effects on recorded tv thumbnails if ar changes during presentation ex. commercials @ diff ar
  563. var vf = "scale=600:trunc(600/dar/2)*2";
  564. if (threedFormat.HasValue)
  565. {
  566. switch (threedFormat.Value)
  567. {
  568. case Video3DFormat.HalfSideBySide:
  569. 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";
  570. // 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.
  571. break;
  572. case Video3DFormat.FullSideBySide:
  573. 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";
  574. //fsbs crop width in half,set the display aspect,crop out any black bars we may have made the scale width to 600.
  575. break;
  576. case Video3DFormat.HalfTopAndBottom:
  577. 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";
  578. //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
  579. break;
  580. case Video3DFormat.FullTopAndBottom:
  581. 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";
  582. // ftab crop heigt in half, set the display aspect,crop out any black bars we may have made the scale width to 600
  583. break;
  584. }
  585. }
  586. // 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.
  587. var args = useIFrame ? string.Format("-i {0} -threads 1 -v quiet -vframes 1 -vf \"{2},thumbnail=30\" -f image2 \"{1}\"", inputPath, "-", vf) :
  588. string.Format("-i {0} -threads 1 -v quiet -vframes 1 -vf \"{2}\" -f image2 \"{1}\"", inputPath, "-", vf);
  589. var probeSize = GetProbeSizeArgument(new[] { inputPath }, protocol);
  590. if (!string.IsNullOrEmpty(probeSize))
  591. {
  592. args = probeSize + " " + args;
  593. }
  594. if (offset.HasValue)
  595. {
  596. args = string.Format("-ss {0} ", GetTimeParameter(offset.Value)) + args;
  597. }
  598. var process = new Process
  599. {
  600. StartInfo = new ProcessStartInfo
  601. {
  602. CreateNoWindow = true,
  603. UseShellExecute = false,
  604. FileName = FFMpegPath,
  605. Arguments = args,
  606. WindowStyle = ProcessWindowStyle.Hidden,
  607. ErrorDialog = false,
  608. RedirectStandardOutput = true,
  609. RedirectStandardError = true,
  610. RedirectStandardInput = true
  611. }
  612. };
  613. _logger.Debug("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments);
  614. using (var processWrapper = new ProcessWrapper(process, this, _logger))
  615. {
  616. await resourcePool.WaitAsync(cancellationToken).ConfigureAwait(false);
  617. bool ranToCompletion;
  618. var memoryStream = new MemoryStream();
  619. try
  620. {
  621. StartProcess(processWrapper);
  622. #pragma warning disable 4014
  623. // Important - don't await the log task or we won't be able to kill ffmpeg when the user stops playback
  624. process.StandardOutput.BaseStream.CopyToAsync(memoryStream);
  625. #pragma warning restore 4014
  626. // MUST read both stdout and stderr asynchronously or a deadlock may occurr
  627. process.BeginErrorReadLine();
  628. ranToCompletion = process.WaitForExit(10000);
  629. if (!ranToCompletion)
  630. {
  631. StopProcess(processWrapper, 1000, false);
  632. }
  633. }
  634. finally
  635. {
  636. resourcePool.Release();
  637. }
  638. var exitCode = ranToCompletion ? processWrapper.ExitCode ?? 0 : -1;
  639. if (exitCode == -1 || memoryStream.Length == 0)
  640. {
  641. memoryStream.Dispose();
  642. var msg = string.Format("ffmpeg image extraction failed for {0}", inputPath);
  643. _logger.Error(msg);
  644. throw new ApplicationException(msg);
  645. }
  646. memoryStream.Position = 0;
  647. return memoryStream;
  648. }
  649. }
  650. public string GetTimeParameter(long ticks)
  651. {
  652. var time = TimeSpan.FromTicks(ticks);
  653. return GetTimeParameter(time);
  654. }
  655. public string GetTimeParameter(TimeSpan time)
  656. {
  657. return time.ToString(@"hh\:mm\:ss\.fff", UsCulture);
  658. }
  659. public async Task ExtractVideoImagesOnInterval(string[] inputFiles,
  660. MediaProtocol protocol,
  661. Video3DFormat? threedFormat,
  662. TimeSpan interval,
  663. string targetDirectory,
  664. string filenamePrefix,
  665. int? maxWidth,
  666. CancellationToken cancellationToken)
  667. {
  668. var resourcePool = _thumbnailResourcePool;
  669. var inputArgument = GetInputArgument(inputFiles, protocol);
  670. var vf = "fps=fps=1/" + interval.TotalSeconds.ToString(UsCulture);
  671. if (maxWidth.HasValue)
  672. {
  673. var maxWidthParam = maxWidth.Value.ToString(UsCulture);
  674. vf += string.Format(",scale=min(iw\\,{0}):trunc(ow/dar/2)*2", maxWidthParam);
  675. }
  676. FileSystem.CreateDirectory(targetDirectory);
  677. var outputPath = Path.Combine(targetDirectory, filenamePrefix + "%05d.jpg");
  678. var args = string.Format("-i {0} -threads 1 -v quiet -vf \"{2}\" -f image2 \"{1}\"", inputArgument, outputPath, vf);
  679. var probeSize = GetProbeSizeArgument(new[] { inputArgument }, protocol);
  680. if (!string.IsNullOrEmpty(probeSize))
  681. {
  682. args = probeSize + " " + args;
  683. }
  684. var process = new Process
  685. {
  686. StartInfo = new ProcessStartInfo
  687. {
  688. CreateNoWindow = true,
  689. UseShellExecute = false,
  690. FileName = FFMpegPath,
  691. Arguments = args,
  692. WindowStyle = ProcessWindowStyle.Hidden,
  693. ErrorDialog = false,
  694. RedirectStandardInput = true
  695. }
  696. };
  697. _logger.Info(process.StartInfo.FileName + " " + process.StartInfo.Arguments);
  698. await resourcePool.WaitAsync(cancellationToken).ConfigureAwait(false);
  699. bool ranToCompletion = false;
  700. using (var processWrapper = new ProcessWrapper(process, this, _logger))
  701. {
  702. try
  703. {
  704. StartProcess(processWrapper);
  705. // Need to give ffmpeg enough time to make all the thumbnails, which could be a while,
  706. // but we still need to detect if the process hangs.
  707. // Making the assumption that as long as new jpegs are showing up, everything is good.
  708. bool isResponsive = true;
  709. int lastCount = 0;
  710. while (isResponsive)
  711. {
  712. if (process.WaitForExit(30000))
  713. {
  714. ranToCompletion = true;
  715. break;
  716. }
  717. cancellationToken.ThrowIfCancellationRequested();
  718. var jpegCount = Directory.GetFiles(targetDirectory)
  719. .Count(i => string.Equals(Path.GetExtension(i), ".jpg", StringComparison.OrdinalIgnoreCase));
  720. isResponsive = (jpegCount > lastCount);
  721. lastCount = jpegCount;
  722. }
  723. if (!ranToCompletion)
  724. {
  725. StopProcess(processWrapper, 1000, false);
  726. }
  727. }
  728. finally
  729. {
  730. resourcePool.Release();
  731. }
  732. var exitCode = ranToCompletion ? processWrapper.ExitCode ?? 0 : -1;
  733. if (exitCode == -1)
  734. {
  735. var msg = string.Format("ffmpeg image extraction failed for {0}", inputArgument);
  736. _logger.Error(msg);
  737. throw new ApplicationException(msg);
  738. }
  739. }
  740. }
  741. public async Task<string> EncodeAudio(EncodingJobOptions options,
  742. IProgress<double> progress,
  743. CancellationToken cancellationToken)
  744. {
  745. var job = await new AudioEncoder(this,
  746. _logger,
  747. ConfigurationManager,
  748. FileSystem,
  749. IsoManager,
  750. LibraryManager,
  751. SessionManager,
  752. SubtitleEncoder(),
  753. MediaSourceManager())
  754. .Start(options, progress, cancellationToken).ConfigureAwait(false);
  755. await job.TaskCompletionSource.Task.ConfigureAwait(false);
  756. return job.OutputFilePath;
  757. }
  758. public async Task<string> EncodeVideo(EncodingJobOptions options,
  759. IProgress<double> progress,
  760. CancellationToken cancellationToken)
  761. {
  762. var job = await new VideoEncoder(this,
  763. _logger,
  764. ConfigurationManager,
  765. FileSystem,
  766. IsoManager,
  767. LibraryManager,
  768. SessionManager,
  769. SubtitleEncoder(),
  770. MediaSourceManager())
  771. .Start(options, progress, cancellationToken).ConfigureAwait(false);
  772. await job.TaskCompletionSource.Task.ConfigureAwait(false);
  773. return job.OutputFilePath;
  774. }
  775. private void StartProcess(ProcessWrapper process)
  776. {
  777. process.Process.Start();
  778. lock (_runningProcesses)
  779. {
  780. _runningProcesses.Add(process);
  781. }
  782. }
  783. private void StopProcess(ProcessWrapper process, int waitTimeMs, bool enableForceKill)
  784. {
  785. try
  786. {
  787. _logger.Info("Killing ffmpeg process");
  788. try
  789. {
  790. process.Process.StandardInput.WriteLine("q");
  791. }
  792. catch (Exception)
  793. {
  794. _logger.Error("Error sending q command to process");
  795. }
  796. try
  797. {
  798. if (process.Process.WaitForExit(waitTimeMs))
  799. {
  800. return;
  801. }
  802. }
  803. catch (Exception ex)
  804. {
  805. _logger.Error("Error in WaitForExit", ex);
  806. }
  807. if (enableForceKill)
  808. {
  809. process.Process.Kill();
  810. }
  811. }
  812. catch (Exception ex)
  813. {
  814. _logger.ErrorException("Error killing process", ex);
  815. }
  816. }
  817. private void StopProcesses()
  818. {
  819. List<ProcessWrapper> proceses;
  820. lock (_runningProcesses)
  821. {
  822. proceses = _runningProcesses.ToList();
  823. }
  824. _runningProcesses.Clear();
  825. foreach (var process in proceses)
  826. {
  827. if (!process.HasExited)
  828. {
  829. StopProcess(process, 500, true);
  830. }
  831. }
  832. }
  833. public string EscapeSubtitleFilterPath(string path)
  834. {
  835. return path.Replace('\\', '/').Replace(":/", "\\:/").Replace("'", "'\\\\\\''");
  836. }
  837. /// <summary>
  838. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  839. /// </summary>
  840. public void Dispose()
  841. {
  842. Dispose(true);
  843. }
  844. /// <summary>
  845. /// Releases unmanaged and - optionally - managed resources.
  846. /// </summary>
  847. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  848. protected virtual void Dispose(bool dispose)
  849. {
  850. if (dispose)
  851. {
  852. _videoImageResourcePool.Dispose();
  853. StopProcesses();
  854. }
  855. }
  856. private class ProcessWrapper : IDisposable
  857. {
  858. public readonly Process Process;
  859. public bool HasExited;
  860. public int? ExitCode;
  861. private readonly MediaEncoder _mediaEncoder;
  862. private readonly ILogger _logger;
  863. public ProcessWrapper(Process process, MediaEncoder mediaEncoder, ILogger logger)
  864. {
  865. Process = process;
  866. _mediaEncoder = mediaEncoder;
  867. _logger = logger;
  868. Process.Exited += Process_Exited;
  869. }
  870. void Process_Exited(object sender, EventArgs e)
  871. {
  872. var process = (Process)sender;
  873. HasExited = true;
  874. try
  875. {
  876. ExitCode = process.ExitCode;
  877. }
  878. catch (Exception ex)
  879. {
  880. }
  881. lock (_mediaEncoder._runningProcesses)
  882. {
  883. _mediaEncoder._runningProcesses.Remove(this);
  884. }
  885. process.Dispose();
  886. }
  887. private bool _disposed;
  888. private readonly object _syncLock = new object();
  889. public void Dispose()
  890. {
  891. lock (_syncLock)
  892. {
  893. if (!_disposed)
  894. {
  895. if (Process != null)
  896. {
  897. Process.Exited -= Process_Exited;
  898. Process.Dispose();
  899. }
  900. }
  901. _disposed = true;
  902. }
  903. }
  904. }
  905. }
  906. }