MediaEncoder.cs 18 KB

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