MediaEncoder.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596
  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 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. public string FFMpegPath { get; private set; }
  49. public string FFProbePath { get; private set; }
  50. public string Version { get; private set; }
  51. protected readonly IServerConfigurationManager ConfigurationManager;
  52. protected readonly IFileSystem FileSystem;
  53. protected readonly ILiveTvManager LiveTvManager;
  54. protected readonly IIsoManager IsoManager;
  55. protected readonly ILibraryManager LibraryManager;
  56. protected readonly IChannelManager ChannelManager;
  57. protected readonly ISessionManager SessionManager;
  58. protected readonly Func<ISubtitleEncoder> SubtitleEncoder;
  59. 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)
  60. {
  61. _logger = logger;
  62. _jsonSerializer = jsonSerializer;
  63. Version = version;
  64. ConfigurationManager = configurationManager;
  65. FileSystem = fileSystem;
  66. LiveTvManager = liveTvManager;
  67. IsoManager = isoManager;
  68. LibraryManager = libraryManager;
  69. ChannelManager = channelManager;
  70. SessionManager = sessionManager;
  71. SubtitleEncoder = subtitleEncoder;
  72. FFProbePath = ffProbePath;
  73. FFMpegPath = ffMpegPath;
  74. }
  75. /// <summary>
  76. /// Gets the encoder path.
  77. /// </summary>
  78. /// <value>The encoder path.</value>
  79. public string EncoderPath
  80. {
  81. get { return FFMpegPath; }
  82. }
  83. /// <summary>
  84. /// Gets the media info.
  85. /// </summary>
  86. /// <param name="inputFiles">The input files.</param>
  87. /// <param name="protocol">The protocol.</param>
  88. /// <param name="isAudio">if set to <c>true</c> [is audio].</param>
  89. /// <param name="cancellationToken">The cancellation token.</param>
  90. /// <returns>Task.</returns>
  91. public Task<InternalMediaInfoResult> GetMediaInfo(string[] inputFiles, MediaProtocol protocol, bool isAudio,
  92. CancellationToken cancellationToken)
  93. {
  94. return GetMediaInfoInternal(GetInputArgument(inputFiles, protocol), !isAudio,
  95. GetProbeSizeArgument(inputFiles, protocol), cancellationToken);
  96. }
  97. /// <summary>
  98. /// Gets the input argument.
  99. /// </summary>
  100. /// <param name="inputFiles">The input files.</param>
  101. /// <param name="protocol">The protocol.</param>
  102. /// <returns>System.String.</returns>
  103. /// <exception cref="System.ArgumentException">Unrecognized InputType</exception>
  104. public string GetInputArgument(string[] inputFiles, MediaProtocol protocol)
  105. {
  106. return EncodingUtils.GetInputArgument(inputFiles.ToList(), protocol);
  107. }
  108. /// <summary>
  109. /// Gets the probe size argument.
  110. /// </summary>
  111. /// <param name="inputFiles">The input files.</param>
  112. /// <param name="protocol">The protocol.</param>
  113. /// <returns>System.String.</returns>
  114. public string GetProbeSizeArgument(string[] inputFiles, MediaProtocol protocol)
  115. {
  116. return EncodingUtils.GetProbeSizeArgument(inputFiles.Length > 1);
  117. }
  118. /// <summary>
  119. /// Gets the media info internal.
  120. /// </summary>
  121. /// <param name="inputPath">The input path.</param>
  122. /// <param name="extractChapters">if set to <c>true</c> [extract chapters].</param>
  123. /// <param name="probeSizeArgument">The probe size argument.</param>
  124. /// <param name="cancellationToken">The cancellation token.</param>
  125. /// <returns>Task{MediaInfoResult}.</returns>
  126. /// <exception cref="System.ApplicationException"></exception>
  127. private async Task<InternalMediaInfoResult> GetMediaInfoInternal(string inputPath, bool extractChapters,
  128. string probeSizeArgument,
  129. CancellationToken cancellationToken)
  130. {
  131. var args = extractChapters
  132. ? "{0} -i {1} -threads 0 -v info -print_format json -show_streams -show_chapters -show_format"
  133. : "{0} -i {1} -threads 0 -v info -print_format json -show_streams -show_format";
  134. var process = new Process
  135. {
  136. StartInfo = new ProcessStartInfo
  137. {
  138. CreateNoWindow = true,
  139. UseShellExecute = false,
  140. // Must consume both or ffmpeg may hang due to deadlocks. See comments below.
  141. RedirectStandardOutput = true,
  142. RedirectStandardError = true,
  143. FileName = FFProbePath,
  144. Arguments = string.Format(args,
  145. probeSizeArgument, inputPath).Trim(),
  146. WindowStyle = ProcessWindowStyle.Hidden,
  147. ErrorDialog = false
  148. },
  149. EnableRaisingEvents = true
  150. };
  151. _logger.Debug("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments);
  152. process.Exited += ProcessExited;
  153. await _ffProbeResourcePool.WaitAsync(cancellationToken).ConfigureAwait(false);
  154. InternalMediaInfoResult result;
  155. try
  156. {
  157. process.Start();
  158. }
  159. catch (Exception ex)
  160. {
  161. _ffProbeResourcePool.Release();
  162. _logger.ErrorException("Error starting ffprobe", ex);
  163. throw;
  164. }
  165. try
  166. {
  167. process.BeginErrorReadLine();
  168. result = _jsonSerializer.DeserializeFromStream<InternalMediaInfoResult>(process.StandardOutput.BaseStream);
  169. }
  170. catch
  171. {
  172. // Hate having to do this
  173. try
  174. {
  175. process.Kill();
  176. }
  177. catch (Exception ex1)
  178. {
  179. _logger.ErrorException("Error killing ffprobe", ex1);
  180. }
  181. throw;
  182. }
  183. finally
  184. {
  185. _ffProbeResourcePool.Release();
  186. }
  187. if (result == null)
  188. {
  189. throw new ApplicationException(string.Format("FFProbe failed for {0}", inputPath));
  190. }
  191. cancellationToken.ThrowIfCancellationRequested();
  192. if (result.streams != null)
  193. {
  194. // Normalize aspect ratio if invalid
  195. foreach (var stream in result.streams)
  196. {
  197. if (string.Equals(stream.display_aspect_ratio, "0:1", StringComparison.OrdinalIgnoreCase))
  198. {
  199. stream.display_aspect_ratio = string.Empty;
  200. }
  201. if (string.Equals(stream.sample_aspect_ratio, "0:1", StringComparison.OrdinalIgnoreCase))
  202. {
  203. stream.sample_aspect_ratio = string.Empty;
  204. }
  205. }
  206. }
  207. return result;
  208. }
  209. /// <summary>
  210. /// The us culture
  211. /// </summary>
  212. protected readonly CultureInfo UsCulture = new CultureInfo("en-US");
  213. /// <summary>
  214. /// Processes the exited.
  215. /// </summary>
  216. /// <param name="sender">The sender.</param>
  217. /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
  218. private void ProcessExited(object sender, EventArgs e)
  219. {
  220. ((Process)sender).Dispose();
  221. }
  222. public Task<Stream> ExtractAudioImage(string path, CancellationToken cancellationToken)
  223. {
  224. return ExtractImage(new[] { path }, MediaProtocol.File, true, null, null, cancellationToken);
  225. }
  226. public Task<Stream> ExtractVideoImage(string[] inputFiles, MediaProtocol protocol, Video3DFormat? threedFormat,
  227. TimeSpan? offset, CancellationToken cancellationToken)
  228. {
  229. return ExtractImage(inputFiles, protocol, false, threedFormat, offset, cancellationToken);
  230. }
  231. private async Task<Stream> ExtractImage(string[] inputFiles, MediaProtocol protocol, bool isAudio,
  232. Video3DFormat? threedFormat, TimeSpan? offset, CancellationToken cancellationToken)
  233. {
  234. var resourcePool = isAudio ? _audioImageResourcePool : _videoImageResourcePool;
  235. var inputArgument = GetInputArgument(inputFiles, protocol);
  236. if (!isAudio)
  237. {
  238. try
  239. {
  240. return await ExtractImageInternal(inputArgument, protocol, threedFormat, offset, true, resourcePool, cancellationToken).ConfigureAwait(false);
  241. }
  242. catch
  243. {
  244. _logger.Error("I-frame image extraction failed, will attempt standard way. Input: {0}", inputArgument);
  245. }
  246. }
  247. return await ExtractImageInternal(inputArgument, protocol, threedFormat, offset, false, resourcePool, cancellationToken).ConfigureAwait(false);
  248. }
  249. private async Task<Stream> ExtractImageInternal(string inputPath, MediaProtocol protocol, Video3DFormat? threedFormat, TimeSpan? offset, bool useIFrame, SemaphoreSlim resourcePool, CancellationToken cancellationToken)
  250. {
  251. if (string.IsNullOrEmpty(inputPath))
  252. {
  253. throw new ArgumentNullException("inputPath");
  254. }
  255. // 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.
  256. // This filter chain may have adverse effects on recorded tv thumbnails if ar changes during presentation ex. commercials @ diff ar
  257. var vf = "scale=600:trunc(600/dar/2)*2";
  258. if (threedFormat.HasValue)
  259. {
  260. switch (threedFormat.Value)
  261. {
  262. case Video3DFormat.HalfSideBySide:
  263. 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";
  264. // 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.
  265. break;
  266. case Video3DFormat.FullSideBySide:
  267. 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";
  268. //fsbs crop width in half,set the display aspect,crop out any black bars we may have made the scale width to 600.
  269. break;
  270. case Video3DFormat.HalfTopAndBottom:
  271. 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";
  272. //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
  273. break;
  274. case Video3DFormat.FullTopAndBottom:
  275. 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";
  276. // ftab crop heigt in half, set the display aspect,crop out any black bars we may have made the scale width to 600
  277. break;
  278. }
  279. }
  280. // TODO: Output in webp for smaller sizes
  281. // -f image2 -f webp
  282. // 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.
  283. var args = useIFrame ? string.Format("-i {0} -threads 0 -v quiet -vframes 1 -vf \"{2},thumbnail=30\" -f image2 \"{1}\"", inputPath, "-", vf) :
  284. string.Format("-i {0} -threads 0 -v quiet -vframes 1 -vf \"{2}\" -f image2 \"{1}\"", inputPath, "-", vf);
  285. var probeSize = GetProbeSizeArgument(new[] { inputPath }, protocol);
  286. if (!string.IsNullOrEmpty(probeSize))
  287. {
  288. args = probeSize + " " + args;
  289. }
  290. if (offset.HasValue)
  291. {
  292. args = string.Format("-ss {0} ", GetTimeParameter(offset.Value)) + args;
  293. }
  294. var process = new Process
  295. {
  296. StartInfo = new ProcessStartInfo
  297. {
  298. CreateNoWindow = true,
  299. UseShellExecute = false,
  300. FileName = FFMpegPath,
  301. Arguments = args,
  302. WindowStyle = ProcessWindowStyle.Hidden,
  303. ErrorDialog = false,
  304. RedirectStandardOutput = true,
  305. RedirectStandardError = true,
  306. RedirectStandardInput = true
  307. }
  308. };
  309. _logger.Debug("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments);
  310. await resourcePool.WaitAsync(cancellationToken).ConfigureAwait(false);
  311. process.Start();
  312. var memoryStream = new MemoryStream();
  313. #pragma warning disable 4014
  314. // Important - don't await the log task or we won't be able to kill ffmpeg when the user stops playback
  315. process.StandardOutput.BaseStream.CopyToAsync(memoryStream);
  316. #pragma warning restore 4014
  317. // MUST read both stdout and stderr asynchronously or a deadlock may occurr
  318. process.BeginErrorReadLine();
  319. var ranToCompletion = process.WaitForExit(10000);
  320. if (!ranToCompletion)
  321. {
  322. try
  323. {
  324. _logger.Info("Killing ffmpeg process");
  325. process.StandardInput.WriteLine("q");
  326. process.WaitForExit(1000);
  327. }
  328. catch (Exception ex)
  329. {
  330. _logger.ErrorException("Error killing process", ex);
  331. }
  332. }
  333. resourcePool.Release();
  334. var exitCode = ranToCompletion ? process.ExitCode : -1;
  335. process.Dispose();
  336. if (exitCode == -1 || memoryStream.Length == 0)
  337. {
  338. memoryStream.Dispose();
  339. var msg = string.Format("ffmpeg image extraction failed for {0}", inputPath);
  340. _logger.Error(msg);
  341. throw new ApplicationException(msg);
  342. }
  343. memoryStream.Position = 0;
  344. return memoryStream;
  345. }
  346. public Task<Stream> EncodeImage(ImageEncodingOptions options, CancellationToken cancellationToken)
  347. {
  348. throw new NotImplementedException();
  349. }
  350. /// <summary>
  351. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  352. /// </summary>
  353. public void Dispose()
  354. {
  355. Dispose(true);
  356. }
  357. /// <summary>
  358. /// Releases unmanaged and - optionally - managed resources.
  359. /// </summary>
  360. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  361. protected virtual void Dispose(bool dispose)
  362. {
  363. if (dispose)
  364. {
  365. _videoImageResourcePool.Dispose();
  366. }
  367. }
  368. public string GetTimeParameter(long ticks)
  369. {
  370. var time = TimeSpan.FromTicks(ticks);
  371. return GetTimeParameter(time);
  372. }
  373. public string GetTimeParameter(TimeSpan time)
  374. {
  375. return time.ToString(@"hh\:mm\:ss\.fff", UsCulture);
  376. }
  377. public async Task ExtractVideoImagesOnInterval(string[] inputFiles,
  378. MediaProtocol protocol,
  379. Video3DFormat? threedFormat,
  380. TimeSpan interval,
  381. string targetDirectory,
  382. string filenamePrefix,
  383. int? maxWidth,
  384. CancellationToken cancellationToken)
  385. {
  386. var resourcePool = _videoImageResourcePool;
  387. var inputArgument = GetInputArgument(inputFiles, protocol);
  388. var vf = "fps=fps=1/" + interval.TotalSeconds.ToString(UsCulture);
  389. if (maxWidth.HasValue)
  390. {
  391. var maxWidthParam = maxWidth.Value.ToString(UsCulture);
  392. vf += string.Format(",scale=min(iw\\,{0}):trunc(ow/dar/2)*2", maxWidthParam);
  393. }
  394. Directory.CreateDirectory(targetDirectory);
  395. var outputPath = Path.Combine(targetDirectory, filenamePrefix + "%05d.jpg");
  396. var args = string.Format("-i {0} -threads 0 -v quiet -vf \"{2}\" -f image2 \"{1}\"", inputArgument, outputPath, vf);
  397. var probeSize = GetProbeSizeArgument(new[] { inputArgument }, protocol);
  398. if (!string.IsNullOrEmpty(probeSize))
  399. {
  400. args = probeSize + " " + args;
  401. }
  402. var process = new Process
  403. {
  404. StartInfo = new ProcessStartInfo
  405. {
  406. CreateNoWindow = true,
  407. UseShellExecute = false,
  408. FileName = FFMpegPath,
  409. Arguments = args,
  410. WindowStyle = ProcessWindowStyle.Hidden,
  411. ErrorDialog = false,
  412. RedirectStandardInput = true
  413. }
  414. };
  415. _logger.Info(process.StartInfo.FileName + " " + process.StartInfo.Arguments);
  416. await resourcePool.WaitAsync(cancellationToken).ConfigureAwait(false);
  417. process.Start();
  418. // Need to give ffmpeg enough time to make all the thumbnails, which could be a while,
  419. // but we still need to detect if the process hangs.
  420. // Making the assumption that as long as new jpegs are showing up, everything is good.
  421. bool isResponsive = true;
  422. int lastCount = 0;
  423. while (isResponsive && !process.WaitForExit(120000))
  424. {
  425. int jpegCount = Directory.GetFiles(targetDirectory, "*.jpg").Count();
  426. isResponsive = (jpegCount > lastCount);
  427. lastCount = jpegCount;
  428. }
  429. bool ranToCompletion = process.HasExited;
  430. if (!ranToCompletion)
  431. {
  432. try
  433. {
  434. _logger.Info("Killing ffmpeg process");
  435. process.StandardInput.WriteLine("q");
  436. process.WaitForExit(1000);
  437. }
  438. catch (Exception ex)
  439. {
  440. _logger.ErrorException("Error killing process", ex);
  441. }
  442. }
  443. resourcePool.Release();
  444. var exitCode = ranToCompletion ? process.ExitCode : -1;
  445. process.Dispose();
  446. if (exitCode == -1)
  447. {
  448. var msg = string.Format("ffmpeg image extraction failed for {0}", inputArgument);
  449. _logger.Error(msg);
  450. throw new ApplicationException(msg);
  451. }
  452. }
  453. public async Task<string> EncodeAudio(EncodingJobOptions options,
  454. IProgress<double> progress,
  455. CancellationToken cancellationToken)
  456. {
  457. var job = await new AudioEncoder(this,
  458. _logger,
  459. ConfigurationManager,
  460. FileSystem,
  461. LiveTvManager,
  462. IsoManager,
  463. LibraryManager,
  464. ChannelManager,
  465. SessionManager,
  466. SubtitleEncoder())
  467. .Start(options, progress, cancellationToken).ConfigureAwait(false);
  468. await job.TaskCompletionSource.Task.ConfigureAwait(false);
  469. return job.OutputFilePath;
  470. }
  471. public async Task<string> EncodeVideo(EncodingJobOptions options,
  472. IProgress<double> progress,
  473. CancellationToken cancellationToken)
  474. {
  475. var job = await new VideoEncoder(this,
  476. _logger,
  477. ConfigurationManager,
  478. FileSystem,
  479. LiveTvManager,
  480. IsoManager,
  481. LibraryManager,
  482. ChannelManager,
  483. SessionManager,
  484. SubtitleEncoder())
  485. .Start(options, progress, cancellationToken).ConfigureAwait(false);
  486. await job.TaskCompletionSource.Task.ConfigureAwait(false);
  487. return job.OutputFilePath;
  488. }
  489. }
  490. }