MediaEncoder.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465
  1. using MediaBrowser.Common.Configuration;
  2. using MediaBrowser.Common.IO;
  3. using MediaBrowser.Controller.MediaEncoding;
  4. using MediaBrowser.Model.Entities;
  5. using MediaBrowser.Model.Logging;
  6. using MediaBrowser.Model.Serialization;
  7. using System;
  8. using System.Collections.Concurrent;
  9. using System.Diagnostics;
  10. using System.Globalization;
  11. using System.IO;
  12. using System.Linq;
  13. using System.Text;
  14. using System.Threading;
  15. using System.Threading.Tasks;
  16. namespace MediaBrowser.MediaEncoding.Encoder
  17. {
  18. /// <summary>
  19. /// Class MediaEncoder
  20. /// </summary>
  21. public class MediaEncoder : IMediaEncoder, IDisposable
  22. {
  23. /// <summary>
  24. /// The _logger
  25. /// </summary>
  26. private readonly ILogger _logger;
  27. /// <summary>
  28. /// The _app paths
  29. /// </summary>
  30. private readonly IApplicationPaths _appPaths;
  31. /// <summary>
  32. /// Gets the json serializer.
  33. /// </summary>
  34. /// <value>The json serializer.</value>
  35. private readonly IJsonSerializer _jsonSerializer;
  36. /// <summary>
  37. /// The video image resource pool
  38. /// </summary>
  39. private readonly SemaphoreSlim _videoImageResourcePool = new SemaphoreSlim(1, 1);
  40. /// <summary>
  41. /// The audio image resource pool
  42. /// </summary>
  43. private readonly SemaphoreSlim _audioImageResourcePool = new SemaphoreSlim(2, 2);
  44. /// <summary>
  45. /// The FF probe resource pool
  46. /// </summary>
  47. private readonly SemaphoreSlim _ffProbeResourcePool = new SemaphoreSlim(2, 2);
  48. private readonly IFileSystem _fileSystem;
  49. public string FFMpegPath { get; private set; }
  50. public string FFProbePath { get; private set; }
  51. public string Version { get; private set; }
  52. public MediaEncoder(ILogger logger, IApplicationPaths appPaths,
  53. IJsonSerializer jsonSerializer, string ffMpegPath, string ffProbePath, string version,
  54. IFileSystem fileSystem)
  55. {
  56. _logger = logger;
  57. _appPaths = appPaths;
  58. _jsonSerializer = jsonSerializer;
  59. Version = version;
  60. _fileSystem = fileSystem;
  61. FFProbePath = ffProbePath;
  62. FFMpegPath = ffMpegPath;
  63. }
  64. /// <summary>
  65. /// Gets the encoder path.
  66. /// </summary>
  67. /// <value>The encoder path.</value>
  68. public string EncoderPath
  69. {
  70. get { return FFMpegPath; }
  71. }
  72. /// <summary>
  73. /// The _semaphoreLocks
  74. /// </summary>
  75. private readonly ConcurrentDictionary<string, SemaphoreSlim> _semaphoreLocks =
  76. new ConcurrentDictionary<string, SemaphoreSlim>();
  77. /// <summary>
  78. /// Gets the lock.
  79. /// </summary>
  80. /// <param name="filename">The filename.</param>
  81. /// <returns>System.Object.</returns>
  82. private SemaphoreSlim GetLock(string filename)
  83. {
  84. return _semaphoreLocks.GetOrAdd(filename, key => new SemaphoreSlim(1, 1));
  85. }
  86. /// <summary>
  87. /// Gets the media info.
  88. /// </summary>
  89. /// <param name="inputFiles">The input files.</param>
  90. /// <param name="type">The type.</param>
  91. /// <param name="isAudio">if set to <c>true</c> [is audio].</param>
  92. /// <param name="cancellationToken">The cancellation token.</param>
  93. /// <returns>Task.</returns>
  94. public Task<InternalMediaInfoResult> GetMediaInfo(string[] inputFiles, InputType type, bool isAudio,
  95. CancellationToken cancellationToken)
  96. {
  97. return GetMediaInfoInternal(GetInputArgument(inputFiles, type), !isAudio,
  98. GetProbeSizeArgument(type), cancellationToken);
  99. }
  100. /// <summary>
  101. /// Gets the input argument.
  102. /// </summary>
  103. /// <param name="inputFiles">The input files.</param>
  104. /// <param name="type">The type.</param>
  105. /// <returns>System.String.</returns>
  106. /// <exception cref="System.ArgumentException">Unrecognized InputType</exception>
  107. public string GetInputArgument(string[] inputFiles, InputType type)
  108. {
  109. return EncodingUtils.GetInputArgument(inputFiles.ToList(), type == InputType.Url);
  110. }
  111. /// <summary>
  112. /// Gets the probe size argument.
  113. /// </summary>
  114. /// <param name="type">The type.</param>
  115. /// <returns>System.String.</returns>
  116. public string GetProbeSizeArgument(InputType type)
  117. {
  118. return EncodingUtils.GetProbeSizeArgument(type == InputType.Dvd);
  119. }
  120. /// <summary>
  121. /// Gets the media info internal.
  122. /// </summary>
  123. /// <param name="inputPath">The input path.</param>
  124. /// <param name="extractChapters">if set to <c>true</c> [extract chapters].</param>
  125. /// <param name="probeSizeArgument">The probe size argument.</param>
  126. /// <param name="cancellationToken">The cancellation token.</param>
  127. /// <returns>Task{MediaInfoResult}.</returns>
  128. /// <exception cref="System.ApplicationException"></exception>
  129. private async Task<InternalMediaInfoResult> GetMediaInfoInternal(string inputPath, bool extractChapters,
  130. string probeSizeArgument,
  131. CancellationToken cancellationToken)
  132. {
  133. var args = extractChapters
  134. ? "{0} -i {1} -threads 0 -v info -print_format json -show_streams -show_chapters -show_format"
  135. : "{0} -i {1} -threads 0 -v info -print_format json -show_streams -show_format";
  136. var process = new Process
  137. {
  138. StartInfo = new ProcessStartInfo
  139. {
  140. CreateNoWindow = true,
  141. UseShellExecute = false,
  142. // Must consume both or ffmpeg may hang due to deadlocks. See comments below.
  143. RedirectStandardOutput = true,
  144. RedirectStandardError = true,
  145. FileName = FFProbePath,
  146. Arguments = string.Format(args,
  147. probeSizeArgument, inputPath).Trim(),
  148. WindowStyle = ProcessWindowStyle.Hidden,
  149. ErrorDialog = false
  150. },
  151. EnableRaisingEvents = true
  152. };
  153. _logger.Debug("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments);
  154. process.Exited += ProcessExited;
  155. await _ffProbeResourcePool.WaitAsync(cancellationToken).ConfigureAwait(false);
  156. InternalMediaInfoResult result;
  157. try
  158. {
  159. process.Start();
  160. }
  161. catch (Exception ex)
  162. {
  163. _ffProbeResourcePool.Release();
  164. _logger.ErrorException("Error starting ffprobe", ex);
  165. throw;
  166. }
  167. try
  168. {
  169. process.BeginErrorReadLine();
  170. result =
  171. _jsonSerializer.DeserializeFromStream<InternalMediaInfoResult>(process.StandardOutput.BaseStream);
  172. }
  173. catch
  174. {
  175. // Hate having to do this
  176. try
  177. {
  178. process.Kill();
  179. }
  180. catch (Exception ex1)
  181. {
  182. _logger.ErrorException("Error killing ffprobe", ex1);
  183. }
  184. throw;
  185. }
  186. finally
  187. {
  188. _ffProbeResourcePool.Release();
  189. }
  190. if (result == null)
  191. {
  192. throw new ApplicationException(string.Format("FFProbe failed for {0}", inputPath));
  193. }
  194. cancellationToken.ThrowIfCancellationRequested();
  195. if (result.streams != null)
  196. {
  197. // Normalize aspect ratio if invalid
  198. foreach (var stream in result.streams)
  199. {
  200. if (string.Equals(stream.display_aspect_ratio, "0:1", StringComparison.OrdinalIgnoreCase))
  201. {
  202. stream.display_aspect_ratio = string.Empty;
  203. }
  204. if (string.Equals(stream.sample_aspect_ratio, "0:1", StringComparison.OrdinalIgnoreCase))
  205. {
  206. stream.sample_aspect_ratio = string.Empty;
  207. }
  208. }
  209. }
  210. return result;
  211. }
  212. /// <summary>
  213. /// The us culture
  214. /// </summary>
  215. protected readonly CultureInfo UsCulture = new CultureInfo("en-US");
  216. /// <summary>
  217. /// Processes the exited.
  218. /// </summary>
  219. /// <param name="sender">The sender.</param>
  220. /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
  221. private void ProcessExited(object sender, EventArgs e)
  222. {
  223. ((Process)sender).Dispose();
  224. }
  225. private const int FastSeekOffsetSeconds = 1;
  226. protected string GetFastSeekCommandLineParameter(TimeSpan offset)
  227. {
  228. var seconds = offset.TotalSeconds - FastSeekOffsetSeconds;
  229. if (seconds > 0)
  230. {
  231. return string.Format("-ss {0} ", seconds.ToString(UsCulture));
  232. }
  233. return string.Empty;
  234. }
  235. protected string GetSlowSeekCommandLineParameter(TimeSpan offset)
  236. {
  237. if (offset.TotalSeconds - FastSeekOffsetSeconds > 0)
  238. {
  239. return string.Format(" -ss {0}", FastSeekOffsetSeconds.ToString(UsCulture));
  240. }
  241. return string.Empty;
  242. }
  243. public Task<Stream> ExtractAudioImage(string path, CancellationToken cancellationToken)
  244. {
  245. return ExtractImage(new[] { path }, InputType.File, true, null, null, cancellationToken);
  246. }
  247. public Task<Stream> ExtractVideoImage(string[] inputFiles, InputType type, Video3DFormat? threedFormat,
  248. TimeSpan? offset, CancellationToken cancellationToken)
  249. {
  250. return ExtractImage(inputFiles, type, false, threedFormat, offset, cancellationToken);
  251. }
  252. private async Task<Stream> ExtractImage(string[] inputFiles, InputType type, bool isAudio,
  253. Video3DFormat? threedFormat, TimeSpan? offset, CancellationToken cancellationToken)
  254. {
  255. var resourcePool = isAudio ? _audioImageResourcePool : _videoImageResourcePool;
  256. var inputArgument = GetInputArgument(inputFiles, type);
  257. if (!isAudio)
  258. {
  259. try
  260. {
  261. return await ExtractImageInternal(inputArgument, type, threedFormat, offset, true, resourcePool, cancellationToken).ConfigureAwait(false);
  262. }
  263. catch
  264. {
  265. _logger.Error("I-frame image extraction failed, will attempt standard way. Input: {0}", inputArgument);
  266. }
  267. }
  268. return await ExtractImageInternal(inputArgument, type, threedFormat, offset, false, resourcePool, cancellationToken).ConfigureAwait(false);
  269. }
  270. private async Task<Stream> ExtractImageInternal(string inputPath, InputType type, Video3DFormat? threedFormat, TimeSpan? offset, bool useIFrame, SemaphoreSlim resourcePool, CancellationToken cancellationToken)
  271. {
  272. if (string.IsNullOrEmpty(inputPath))
  273. {
  274. throw new ArgumentNullException("inputPath");
  275. }
  276. // 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.
  277. // This filter chain may have adverse effects on recorded tv thumbnails if ar changes during presentation ex. commercials @ diff ar
  278. var vf = "scale=600:trunc(600/dar/2)*2";
  279. //crop=min(iw\,ih*dar):min(ih\,iw/dar):(iw-min(iw\,iw*sar))/2:(ih - min (ih\,ih/sar))/2,scale=600:(600/dar),thumbnail" -f image2
  280. if (threedFormat.HasValue)
  281. {
  282. switch (threedFormat.Value)
  283. {
  284. case Video3DFormat.HalfSideBySide:
  285. 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";
  286. // 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.
  287. break;
  288. case Video3DFormat.FullSideBySide:
  289. 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";
  290. //fsbs crop width in half,set the display aspect,crop out any black bars we may have made the scale width to 600.
  291. break;
  292. case Video3DFormat.HalfTopAndBottom:
  293. 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";
  294. //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
  295. break;
  296. case Video3DFormat.FullTopAndBottom:
  297. 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";
  298. // ftab crop heigt in half, set the display aspect,crop out any black bars we may have made the scale width to 600
  299. break;
  300. }
  301. }
  302. // 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.
  303. var args = useIFrame ? string.Format("-i {0} -threads 0 -v quiet -vframes 1 -vf \"{2},thumbnail=30\" -f image2 \"{1}\"", inputPath, "-", vf) :
  304. string.Format("-i {0} -threads 0 -v quiet -vframes 1 -vf \"{2}\" -f image2 \"{1}\"", inputPath, "-", vf);
  305. var probeSize = GetProbeSizeArgument(type);
  306. if (!string.IsNullOrEmpty(probeSize))
  307. {
  308. args = probeSize + " " + args;
  309. }
  310. if (offset.HasValue)
  311. {
  312. args = string.Format("-ss {0} ", Convert.ToInt32(offset.Value.TotalSeconds)).ToString(UsCulture) + args;
  313. }
  314. var process = new Process
  315. {
  316. StartInfo = new ProcessStartInfo
  317. {
  318. CreateNoWindow = true,
  319. UseShellExecute = false,
  320. FileName = FFMpegPath,
  321. Arguments = args,
  322. WindowStyle = ProcessWindowStyle.Hidden,
  323. ErrorDialog = false,
  324. RedirectStandardOutput = true,
  325. RedirectStandardError = true
  326. }
  327. };
  328. await resourcePool.WaitAsync(cancellationToken).ConfigureAwait(false);
  329. process.Start();
  330. var memoryStream = new MemoryStream();
  331. #pragma warning disable 4014
  332. // Important - don't await the log task or we won't be able to kill ffmpeg when the user stops playback
  333. process.StandardOutput.BaseStream.CopyToAsync(memoryStream);
  334. #pragma warning restore 4014
  335. // MUST read both stdout and stderr asynchronously or a deadlock may occurr
  336. process.BeginErrorReadLine();
  337. var ranToCompletion = process.WaitForExit(10000);
  338. if (!ranToCompletion)
  339. {
  340. try
  341. {
  342. _logger.Info("Killing ffmpeg process");
  343. process.Kill();
  344. process.WaitForExit(1000);
  345. }
  346. catch (Exception ex)
  347. {
  348. _logger.ErrorException("Error killing process", ex);
  349. }
  350. }
  351. resourcePool.Release();
  352. var exitCode = ranToCompletion ? process.ExitCode : -1;
  353. process.Dispose();
  354. if (exitCode == -1 || memoryStream.Length == 0)
  355. {
  356. memoryStream.Dispose();
  357. var msg = string.Format("ffmpeg image extraction failed for {0}", inputPath);
  358. _logger.Error(msg);
  359. throw new ApplicationException(msg);
  360. }
  361. memoryStream.Position = 0;
  362. return memoryStream;
  363. }
  364. public Task<Stream> EncodeImage(ImageEncodingOptions options, CancellationToken cancellationToken)
  365. {
  366. throw new NotImplementedException();
  367. }
  368. /// <summary>
  369. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  370. /// </summary>
  371. public void Dispose()
  372. {
  373. Dispose(true);
  374. }
  375. /// <summary>
  376. /// Releases unmanaged and - optionally - managed resources.
  377. /// </summary>
  378. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  379. protected virtual void Dispose(bool dispose)
  380. {
  381. if (dispose)
  382. {
  383. _videoImageResourcePool.Dispose();
  384. }
  385. }
  386. }
  387. }