MediaEncoder.cs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612
  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.Model.Entities;
  9. using MediaBrowser.Model.IO;
  10. using MediaBrowser.Model.Logging;
  11. using MediaBrowser.Model.MediaInfo;
  12. using MediaBrowser.Model.Serialization;
  13. using System;
  14. using System.Diagnostics;
  15. using System.Globalization;
  16. using System.IO;
  17. using System.Linq;
  18. using System.Threading;
  19. using System.Threading.Tasks;
  20. namespace MediaBrowser.MediaEncoding.Encoder
  21. {
  22. /// <summary>
  23. /// Class MediaEncoder
  24. /// </summary>
  25. public class MediaEncoder : IMediaEncoder, IDisposable
  26. {
  27. /// <summary>
  28. /// The _logger
  29. /// </summary>
  30. private readonly ILogger _logger;
  31. /// <summary>
  32. /// Gets the json serializer.
  33. /// </summary>
  34. /// <value>The json serializer.</value>
  35. private readonly IJsonSerializer _jsonSerializer;
  36. /// <summary>
  37. /// The _thumbnail resource pool
  38. /// </summary>
  39. private readonly SemaphoreSlim _thumbnailResourcePool = new SemaphoreSlim(1, 1);
  40. /// <summary>
  41. /// The video image resource pool
  42. /// </summary>
  43. private readonly SemaphoreSlim _videoImageResourcePool = new SemaphoreSlim(1, 1);
  44. /// <summary>
  45. /// The audio image resource pool
  46. /// </summary>
  47. private readonly SemaphoreSlim _audioImageResourcePool = new SemaphoreSlim(2, 2);
  48. /// <summary>
  49. /// The FF probe resource pool
  50. /// </summary>
  51. private readonly SemaphoreSlim _ffProbeResourcePool = new SemaphoreSlim(2, 2);
  52. public string FFMpegPath { get; private set; }
  53. public string FFProbePath { get; private set; }
  54. public string Version { get; private set; }
  55. protected readonly IServerConfigurationManager ConfigurationManager;
  56. protected readonly IFileSystem FileSystem;
  57. protected readonly ILiveTvManager LiveTvManager;
  58. protected readonly IIsoManager IsoManager;
  59. protected readonly ILibraryManager LibraryManager;
  60. protected readonly IChannelManager ChannelManager;
  61. protected readonly ISessionManager SessionManager;
  62. protected readonly Func<ISubtitleEncoder> SubtitleEncoder;
  63. 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)
  64. {
  65. _logger = logger;
  66. _jsonSerializer = jsonSerializer;
  67. Version = version;
  68. ConfigurationManager = configurationManager;
  69. FileSystem = fileSystem;
  70. LiveTvManager = liveTvManager;
  71. IsoManager = isoManager;
  72. LibraryManager = libraryManager;
  73. ChannelManager = channelManager;
  74. SessionManager = sessionManager;
  75. SubtitleEncoder = subtitleEncoder;
  76. FFProbePath = ffProbePath;
  77. FFMpegPath = ffMpegPath;
  78. }
  79. /// <summary>
  80. /// Gets the encoder path.
  81. /// </summary>
  82. /// <value>The encoder path.</value>
  83. public string EncoderPath
  84. {
  85. get { return FFMpegPath; }
  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 = _jsonSerializer.DeserializeFromStream<InternalMediaInfoResult>(process.StandardOutput.BaseStream);
  173. }
  174. catch
  175. {
  176. // Hate having to do this
  177. try
  178. {
  179. process.Kill();
  180. }
  181. catch (Exception ex1)
  182. {
  183. _logger.ErrorException("Error killing ffprobe", ex1);
  184. }
  185. throw;
  186. }
  187. finally
  188. {
  189. _ffProbeResourcePool.Release();
  190. }
  191. if (result == null)
  192. {
  193. throw new ApplicationException(string.Format("FFProbe failed for {0}", inputPath));
  194. }
  195. cancellationToken.ThrowIfCancellationRequested();
  196. if (result.streams != null)
  197. {
  198. // Normalize aspect ratio if invalid
  199. foreach (var stream in result.streams)
  200. {
  201. if (string.Equals(stream.display_aspect_ratio, "0:1", StringComparison.OrdinalIgnoreCase))
  202. {
  203. stream.display_aspect_ratio = string.Empty;
  204. }
  205. if (string.Equals(stream.sample_aspect_ratio, "0:1", StringComparison.OrdinalIgnoreCase))
  206. {
  207. stream.sample_aspect_ratio = string.Empty;
  208. }
  209. }
  210. }
  211. return result;
  212. }
  213. /// <summary>
  214. /// The us culture
  215. /// </summary>
  216. protected readonly CultureInfo UsCulture = new CultureInfo("en-US");
  217. /// <summary>
  218. /// Processes the exited.
  219. /// </summary>
  220. /// <param name="sender">The sender.</param>
  221. /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
  222. private void ProcessExited(object sender, EventArgs e)
  223. {
  224. ((Process)sender).Dispose();
  225. }
  226. public Task<Stream> ExtractAudioImage(string path, CancellationToken cancellationToken)
  227. {
  228. return ExtractImage(new[] { path }, MediaProtocol.File, true, null, null, cancellationToken);
  229. }
  230. public Task<Stream> ExtractVideoImage(string[] inputFiles, MediaProtocol protocol, Video3DFormat? threedFormat,
  231. TimeSpan? offset, CancellationToken cancellationToken)
  232. {
  233. return ExtractImage(inputFiles, protocol, false, threedFormat, offset, cancellationToken);
  234. }
  235. private async Task<Stream> ExtractImage(string[] inputFiles, MediaProtocol protocol, bool isAudio,
  236. Video3DFormat? threedFormat, TimeSpan? offset, CancellationToken cancellationToken)
  237. {
  238. var resourcePool = isAudio ? _audioImageResourcePool : _videoImageResourcePool;
  239. var inputArgument = GetInputArgument(inputFiles, protocol);
  240. if (!isAudio)
  241. {
  242. try
  243. {
  244. return await ExtractImageInternal(inputArgument, protocol, threedFormat, offset, true, resourcePool, cancellationToken).ConfigureAwait(false);
  245. }
  246. catch
  247. {
  248. _logger.Error("I-frame image extraction failed, will attempt standard way. Input: {0}", inputArgument);
  249. }
  250. }
  251. return await ExtractImageInternal(inputArgument, protocol, threedFormat, offset, false, resourcePool, cancellationToken).ConfigureAwait(false);
  252. }
  253. private async Task<Stream> ExtractImageInternal(string inputPath, MediaProtocol protocol, Video3DFormat? threedFormat, TimeSpan? offset, bool useIFrame, SemaphoreSlim resourcePool, CancellationToken cancellationToken)
  254. {
  255. if (string.IsNullOrEmpty(inputPath))
  256. {
  257. throw new ArgumentNullException("inputPath");
  258. }
  259. // 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.
  260. // This filter chain may have adverse effects on recorded tv thumbnails if ar changes during presentation ex. commercials @ diff ar
  261. var vf = "scale=600:trunc(600/dar/2)*2";
  262. if (threedFormat.HasValue)
  263. {
  264. switch (threedFormat.Value)
  265. {
  266. case Video3DFormat.HalfSideBySide:
  267. 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";
  268. // 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.
  269. break;
  270. case Video3DFormat.FullSideBySide:
  271. 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";
  272. //fsbs crop width in half,set the display aspect,crop out any black bars we may have made the scale width to 600.
  273. break;
  274. case Video3DFormat.HalfTopAndBottom:
  275. 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";
  276. //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
  277. break;
  278. case Video3DFormat.FullTopAndBottom:
  279. 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";
  280. // ftab crop heigt in half, set the display aspect,crop out any black bars we may have made the scale width to 600
  281. break;
  282. }
  283. }
  284. // TODO: Output in webp for smaller sizes
  285. // -f image2 -f webp
  286. // 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.
  287. var args = useIFrame ? string.Format("-i {0} -threads 1 -v quiet -vframes 1 -vf \"{2},thumbnail=30\" -f image2 \"{1}\"", inputPath, "-", vf) :
  288. string.Format("-i {0} -threads 1 -v quiet -vframes 1 -vf \"{2}\" -f image2 \"{1}\"", inputPath, "-", vf);
  289. var probeSize = GetProbeSizeArgument(new[] { inputPath }, protocol);
  290. if (!string.IsNullOrEmpty(probeSize))
  291. {
  292. args = probeSize + " " + args;
  293. }
  294. if (offset.HasValue)
  295. {
  296. args = string.Format("-ss {0} ", GetTimeParameter(offset.Value)) + args;
  297. }
  298. var process = new Process
  299. {
  300. StartInfo = new ProcessStartInfo
  301. {
  302. CreateNoWindow = true,
  303. UseShellExecute = false,
  304. FileName = FFMpegPath,
  305. Arguments = args,
  306. WindowStyle = ProcessWindowStyle.Hidden,
  307. ErrorDialog = false,
  308. RedirectStandardOutput = true,
  309. RedirectStandardError = true,
  310. RedirectStandardInput = true
  311. }
  312. };
  313. _logger.Debug("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments);
  314. await resourcePool.WaitAsync(cancellationToken).ConfigureAwait(false);
  315. process.Start();
  316. var memoryStream = new MemoryStream();
  317. #pragma warning disable 4014
  318. // Important - don't await the log task or we won't be able to kill ffmpeg when the user stops playback
  319. process.StandardOutput.BaseStream.CopyToAsync(memoryStream);
  320. #pragma warning restore 4014
  321. // MUST read both stdout and stderr asynchronously or a deadlock may occurr
  322. process.BeginErrorReadLine();
  323. var ranToCompletion = process.WaitForExit(10000);
  324. if (!ranToCompletion)
  325. {
  326. try
  327. {
  328. _logger.Info("Killing ffmpeg process");
  329. process.StandardInput.WriteLine("q");
  330. process.WaitForExit(1000);
  331. }
  332. catch (Exception ex)
  333. {
  334. _logger.ErrorException("Error killing process", ex);
  335. }
  336. }
  337. resourcePool.Release();
  338. var exitCode = ranToCompletion ? process.ExitCode : -1;
  339. process.Dispose();
  340. if (exitCode == -1 || memoryStream.Length == 0)
  341. {
  342. memoryStream.Dispose();
  343. var msg = string.Format("ffmpeg image extraction failed for {0}", inputPath);
  344. _logger.Error(msg);
  345. throw new ApplicationException(msg);
  346. }
  347. memoryStream.Position = 0;
  348. return memoryStream;
  349. }
  350. public Task<Stream> EncodeImage(ImageEncodingOptions options, CancellationToken cancellationToken)
  351. {
  352. throw new NotImplementedException();
  353. }
  354. /// <summary>
  355. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  356. /// </summary>
  357. public void Dispose()
  358. {
  359. Dispose(true);
  360. }
  361. /// <summary>
  362. /// Releases unmanaged and - optionally - managed resources.
  363. /// </summary>
  364. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  365. protected virtual void Dispose(bool dispose)
  366. {
  367. if (dispose)
  368. {
  369. _videoImageResourcePool.Dispose();
  370. }
  371. }
  372. public string GetTimeParameter(long ticks)
  373. {
  374. var time = TimeSpan.FromTicks(ticks);
  375. return GetTimeParameter(time);
  376. }
  377. public string GetTimeParameter(TimeSpan time)
  378. {
  379. return time.ToString(@"hh\:mm\:ss\.fff", UsCulture);
  380. }
  381. public async Task ExtractVideoImagesOnInterval(string[] inputFiles,
  382. MediaProtocol protocol,
  383. Video3DFormat? threedFormat,
  384. TimeSpan interval,
  385. string targetDirectory,
  386. string filenamePrefix,
  387. int? maxWidth,
  388. CancellationToken cancellationToken)
  389. {
  390. var resourcePool = _thumbnailResourcePool;
  391. var inputArgument = GetInputArgument(inputFiles, protocol);
  392. var vf = "fps=fps=1/" + interval.TotalSeconds.ToString(UsCulture);
  393. if (maxWidth.HasValue)
  394. {
  395. var maxWidthParam = maxWidth.Value.ToString(UsCulture);
  396. vf += string.Format(",scale=min(iw\\,{0}):trunc(ow/dar/2)*2", maxWidthParam);
  397. }
  398. Directory.CreateDirectory(targetDirectory);
  399. var outputPath = Path.Combine(targetDirectory, filenamePrefix + "%05d.jpg");
  400. var args = string.Format("-i {0} -threads 1 -v quiet -vf \"{2}\" -f image2 \"{1}\"", inputArgument, outputPath, vf);
  401. var probeSize = GetProbeSizeArgument(new[] { inputArgument }, protocol);
  402. if (!string.IsNullOrEmpty(probeSize))
  403. {
  404. args = probeSize + " " + args;
  405. }
  406. var process = new Process
  407. {
  408. StartInfo = new ProcessStartInfo
  409. {
  410. CreateNoWindow = true,
  411. UseShellExecute = false,
  412. FileName = FFMpegPath,
  413. Arguments = args,
  414. WindowStyle = ProcessWindowStyle.Hidden,
  415. ErrorDialog = false,
  416. RedirectStandardInput = true
  417. }
  418. };
  419. _logger.Info(process.StartInfo.FileName + " " + process.StartInfo.Arguments);
  420. await resourcePool.WaitAsync(cancellationToken).ConfigureAwait(false);
  421. bool ranToCompletion;
  422. try
  423. {
  424. process.Start();
  425. // Need to give ffmpeg enough time to make all the thumbnails, which could be a while,
  426. // but we still need to detect if the process hangs.
  427. // Making the assumption that as long as new jpegs are showing up, everything is good.
  428. bool isResponsive = true;
  429. int lastCount = 0;
  430. while (isResponsive && !process.WaitForExit(30000))
  431. {
  432. cancellationToken.ThrowIfCancellationRequested();
  433. int jpegCount = Directory.GetFiles(targetDirectory)
  434. .Count(i => string.Equals(Path.GetExtension(i), ".jpg", StringComparison.OrdinalIgnoreCase));
  435. isResponsive = (jpegCount > lastCount);
  436. lastCount = jpegCount;
  437. }
  438. ranToCompletion = process.HasExited;
  439. if (!ranToCompletion)
  440. {
  441. try
  442. {
  443. _logger.Info("Killing ffmpeg process");
  444. process.StandardInput.WriteLine("q");
  445. process.WaitForExit(1000);
  446. }
  447. catch (Exception ex)
  448. {
  449. _logger.ErrorException("Error killing process", ex);
  450. }
  451. }
  452. }
  453. finally
  454. {
  455. resourcePool.Release();
  456. }
  457. var exitCode = ranToCompletion ? process.ExitCode : -1;
  458. process.Dispose();
  459. if (exitCode == -1)
  460. {
  461. var msg = string.Format("ffmpeg image extraction failed for {0}", inputArgument);
  462. _logger.Error(msg);
  463. throw new ApplicationException(msg);
  464. }
  465. }
  466. public async Task<string> EncodeAudio(EncodingJobOptions options,
  467. IProgress<double> progress,
  468. CancellationToken cancellationToken)
  469. {
  470. var job = await new AudioEncoder(this,
  471. _logger,
  472. ConfigurationManager,
  473. FileSystem,
  474. LiveTvManager,
  475. IsoManager,
  476. LibraryManager,
  477. ChannelManager,
  478. SessionManager,
  479. SubtitleEncoder())
  480. .Start(options, progress, cancellationToken).ConfigureAwait(false);
  481. await job.TaskCompletionSource.Task.ConfigureAwait(false);
  482. return job.OutputFilePath;
  483. }
  484. public async Task<string> EncodeVideo(EncodingJobOptions options,
  485. IProgress<double> progress,
  486. CancellationToken cancellationToken)
  487. {
  488. var job = await new VideoEncoder(this,
  489. _logger,
  490. ConfigurationManager,
  491. FileSystem,
  492. LiveTvManager,
  493. IsoManager,
  494. LibraryManager,
  495. ChannelManager,
  496. SessionManager,
  497. SubtitleEncoder())
  498. .Start(options, progress, cancellationToken).ConfigureAwait(false);
  499. await job.TaskCompletionSource.Task.ConfigureAwait(false);
  500. return job.OutputFilePath;
  501. }
  502. }
  503. }