MediaEncoder.cs 20 KB

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