BaseEncoder.cs 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062
  1. using MediaBrowser.Common.Configuration;
  2. using MediaBrowser.Common.IO;
  3. using MediaBrowser.Controller.Channels;
  4. using MediaBrowser.Controller.Configuration;
  5. using MediaBrowser.Controller.Library;
  6. using MediaBrowser.Controller.LiveTv;
  7. using MediaBrowser.Controller.MediaEncoding;
  8. using MediaBrowser.Controller.Session;
  9. using MediaBrowser.MediaEncoding.Subtitles;
  10. using MediaBrowser.Model.Configuration;
  11. using MediaBrowser.Model.Dlna;
  12. using MediaBrowser.Model.Drawing;
  13. using MediaBrowser.Model.Entities;
  14. using MediaBrowser.Model.IO;
  15. using MediaBrowser.Model.Logging;
  16. using System;
  17. using System.Collections.Generic;
  18. using System.Diagnostics;
  19. using System.Globalization;
  20. using System.IO;
  21. using System.Text;
  22. using System.Threading;
  23. using System.Threading.Tasks;
  24. namespace MediaBrowser.MediaEncoding.Encoder
  25. {
  26. public abstract class BaseEncoder
  27. {
  28. protected readonly MediaEncoder MediaEncoder;
  29. protected readonly ILogger Logger;
  30. protected readonly IServerConfigurationManager ConfigurationManager;
  31. protected readonly IFileSystem FileSystem;
  32. protected readonly ILiveTvManager LiveTvManager;
  33. protected readonly IIsoManager IsoManager;
  34. protected readonly ILibraryManager LibraryManager;
  35. protected readonly IChannelManager ChannelManager;
  36. protected readonly ISessionManager SessionManager;
  37. protected readonly ISubtitleEncoder SubtitleEncoder;
  38. protected readonly CultureInfo UsCulture = new CultureInfo("en-US");
  39. public BaseEncoder(MediaEncoder mediaEncoder,
  40. ILogger logger,
  41. IServerConfigurationManager configurationManager,
  42. IFileSystem fileSystem,
  43. ILiveTvManager liveTvManager,
  44. IIsoManager isoManager,
  45. ILibraryManager libraryManager,
  46. IChannelManager channelManager,
  47. ISessionManager sessionManager, ISubtitleEncoder subtitleEncoder)
  48. {
  49. MediaEncoder = mediaEncoder;
  50. Logger = logger;
  51. ConfigurationManager = configurationManager;
  52. FileSystem = fileSystem;
  53. LiveTvManager = liveTvManager;
  54. IsoManager = isoManager;
  55. LibraryManager = libraryManager;
  56. ChannelManager = channelManager;
  57. SessionManager = sessionManager;
  58. SubtitleEncoder = subtitleEncoder;
  59. }
  60. public async Task<EncodingJob> Start(EncodingJobOptions options,
  61. IProgress<double> progress,
  62. CancellationToken cancellationToken)
  63. {
  64. var encodingJob = await new EncodingJobFactory(Logger, LiveTvManager, LibraryManager, ChannelManager)
  65. .CreateJob(options, IsVideoEncoder, progress, cancellationToken).ConfigureAwait(false);
  66. encodingJob.OutputFilePath = GetOutputFilePath(encodingJob);
  67. Directory.CreateDirectory(Path.GetDirectoryName(encodingJob.OutputFilePath));
  68. if (options.Context == EncodingContext.Static && encodingJob.IsInputVideo)
  69. {
  70. encodingJob.ReadInputAtNativeFramerate = true;
  71. }
  72. await AcquireResources(encodingJob, cancellationToken).ConfigureAwait(false);
  73. var commandLineArgs = GetCommandLineArguments(encodingJob);
  74. if (GetEncodingOptions().EnableDebugLogging)
  75. {
  76. commandLineArgs = "-loglevel debug " + commandLineArgs;
  77. }
  78. var process = new Process
  79. {
  80. StartInfo = new ProcessStartInfo
  81. {
  82. CreateNoWindow = true,
  83. UseShellExecute = false,
  84. // Must consume both stdout and stderr or deadlocks may occur
  85. RedirectStandardOutput = true,
  86. RedirectStandardError = true,
  87. RedirectStandardInput = true,
  88. FileName = MediaEncoder.EncoderPath,
  89. Arguments = commandLineArgs,
  90. WindowStyle = ProcessWindowStyle.Hidden,
  91. ErrorDialog = false
  92. },
  93. EnableRaisingEvents = true
  94. };
  95. var workingDirectory = GetWorkingDirectory(options);
  96. if (!string.IsNullOrWhiteSpace(workingDirectory))
  97. {
  98. process.StartInfo.WorkingDirectory = workingDirectory;
  99. }
  100. OnTranscodeBeginning(encodingJob);
  101. var commandLineLogMessage = process.StartInfo.FileName + " " + process.StartInfo.Arguments;
  102. Logger.Info(commandLineLogMessage);
  103. var logFilePath = Path.Combine(ConfigurationManager.CommonApplicationPaths.LogDirectoryPath, "transcode-" + Guid.NewGuid() + ".txt");
  104. Directory.CreateDirectory(Path.GetDirectoryName(logFilePath));
  105. // FFMpeg writes debug/error info to stderr. This is useful when debugging so let's put it in the log directory.
  106. encodingJob.LogFileStream = FileSystem.GetFileStream(logFilePath, FileMode.Create, FileAccess.Write, FileShare.Read, true);
  107. var commandLineLogMessageBytes = Encoding.UTF8.GetBytes(commandLineLogMessage + Environment.NewLine + Environment.NewLine);
  108. await encodingJob.LogFileStream.WriteAsync(commandLineLogMessageBytes, 0, commandLineLogMessageBytes.Length, cancellationToken).ConfigureAwait(false);
  109. process.Exited += (sender, args) => OnFfMpegProcessExited(process, encodingJob);
  110. try
  111. {
  112. process.Start();
  113. }
  114. catch (Exception ex)
  115. {
  116. Logger.ErrorException("Error starting ffmpeg", ex);
  117. OnTranscodeFailedToStart(encodingJob.OutputFilePath, encodingJob);
  118. throw;
  119. }
  120. cancellationToken.Register(() => Cancel(process, encodingJob));
  121. // MUST read both stdout and stderr asynchronously or a deadlock may occurr
  122. process.BeginOutputReadLine();
  123. // Important - don't await the log task or we won't be able to kill ffmpeg when the user stops playback
  124. new JobLogger(Logger).StartStreamingLog(encodingJob, process.StandardError.BaseStream, encodingJob.LogFileStream);
  125. // Wait for the file to exist before proceeeding
  126. while (!File.Exists(encodingJob.OutputFilePath) && !encodingJob.HasExited)
  127. {
  128. await Task.Delay(100, cancellationToken).ConfigureAwait(false);
  129. }
  130. return encodingJob;
  131. }
  132. private void Cancel(Process process, EncodingJob job)
  133. {
  134. Logger.Info("Killing ffmpeg process for {0}", job.OutputFilePath);
  135. //process.Kill();
  136. process.StandardInput.WriteLine("q");
  137. job.IsCancelled = true;
  138. }
  139. /// <summary>
  140. /// Processes the exited.
  141. /// </summary>
  142. /// <param name="process">The process.</param>
  143. /// <param name="job">The job.</param>
  144. private void OnFfMpegProcessExited(Process process, EncodingJob job)
  145. {
  146. job.HasExited = true;
  147. Logger.Debug("Disposing stream resources");
  148. job.Dispose();
  149. var isSuccesful = false;
  150. try
  151. {
  152. var exitCode = process.ExitCode;
  153. Logger.Info("FFMpeg exited with code {0}", exitCode);
  154. isSuccesful = exitCode == 0;
  155. }
  156. catch
  157. {
  158. Logger.Error("FFMpeg exited with an error.");
  159. }
  160. if (isSuccesful && !job.IsCancelled)
  161. {
  162. job.TaskCompletionSource.TrySetResult(true);
  163. }
  164. else if (job.IsCancelled)
  165. {
  166. try
  167. {
  168. DeleteFiles(job);
  169. }
  170. catch
  171. {
  172. }
  173. try
  174. {
  175. job.TaskCompletionSource.TrySetException(new OperationCanceledException());
  176. }
  177. catch
  178. {
  179. }
  180. }
  181. else
  182. {
  183. try
  184. {
  185. DeleteFiles(job);
  186. }
  187. catch
  188. {
  189. }
  190. try
  191. {
  192. job.TaskCompletionSource.TrySetException(new ApplicationException("Encoding failed"));
  193. }
  194. catch
  195. {
  196. }
  197. }
  198. // This causes on exited to be called twice:
  199. //try
  200. //{
  201. // // Dispose the process
  202. // process.Dispose();
  203. //}
  204. //catch (Exception ex)
  205. //{
  206. // Logger.ErrorException("Error disposing ffmpeg.", ex);
  207. //}
  208. }
  209. protected virtual void DeleteFiles(EncodingJob job)
  210. {
  211. FileSystem.DeleteFile(job.OutputFilePath);
  212. }
  213. private void OnTranscodeBeginning(EncodingJob job)
  214. {
  215. job.ReportTranscodingProgress(null, null, null, null);
  216. }
  217. private void OnTranscodeFailedToStart(string path, EncodingJob job)
  218. {
  219. if (!string.IsNullOrWhiteSpace(job.Options.DeviceId))
  220. {
  221. SessionManager.ClearTranscodingInfo(job.Options.DeviceId);
  222. }
  223. }
  224. protected abstract bool IsVideoEncoder { get; }
  225. protected virtual string GetWorkingDirectory(EncodingJobOptions options)
  226. {
  227. return null;
  228. }
  229. protected EncodingOptions GetEncodingOptions()
  230. {
  231. return ConfigurationManager.GetConfiguration<EncodingOptions>("encoding");
  232. }
  233. protected abstract string GetCommandLineArguments(EncodingJob job);
  234. private string GetOutputFilePath(EncodingJob state)
  235. {
  236. var folder = string.IsNullOrWhiteSpace(state.Options.OutputDirectory) ?
  237. ConfigurationManager.ApplicationPaths.TranscodingTempPath :
  238. state.Options.OutputDirectory;
  239. var outputFileExtension = GetOutputFileExtension(state);
  240. var filename = state.Id + (outputFileExtension ?? string.Empty).ToLower();
  241. return Path.Combine(folder, filename);
  242. }
  243. protected virtual string GetOutputFileExtension(EncodingJob state)
  244. {
  245. if (!string.IsNullOrWhiteSpace(state.Options.OutputContainer))
  246. {
  247. return "." + state.Options.OutputContainer;
  248. }
  249. return null;
  250. }
  251. /// <summary>
  252. /// Gets the number of threads.
  253. /// </summary>
  254. /// <returns>System.Int32.</returns>
  255. protected int GetNumberOfThreads(EncodingJob job, bool isWebm)
  256. {
  257. // Only need one thread for sync
  258. if (job.Options.Context == EncodingContext.Static)
  259. {
  260. return 1;
  261. }
  262. if (isWebm)
  263. {
  264. // Recommended per docs
  265. return Math.Max(Environment.ProcessorCount - 1, 2);
  266. }
  267. return 0;
  268. }
  269. protected EncodingQuality GetQualitySetting()
  270. {
  271. var quality = GetEncodingOptions().EncodingQuality;
  272. if (quality == EncodingQuality.Auto)
  273. {
  274. var cpuCount = Environment.ProcessorCount;
  275. if (cpuCount >= 4)
  276. {
  277. //return EncodingQuality.HighQuality;
  278. }
  279. return EncodingQuality.HighSpeed;
  280. }
  281. return quality;
  282. }
  283. protected string GetInputModifier(EncodingJob job, bool genPts = true)
  284. {
  285. var inputModifier = string.Empty;
  286. var probeSize = GetProbeSizeArgument(job);
  287. inputModifier += " " + probeSize;
  288. inputModifier = inputModifier.Trim();
  289. var userAgentParam = GetUserAgentParam(job);
  290. if (!string.IsNullOrWhiteSpace(userAgentParam))
  291. {
  292. inputModifier += " " + userAgentParam;
  293. }
  294. inputModifier = inputModifier.Trim();
  295. inputModifier += " " + GetFastSeekCommandLineParameter(job.Options);
  296. inputModifier = inputModifier.Trim();
  297. if (job.IsVideoRequest && genPts)
  298. {
  299. inputModifier += " -fflags +genpts";
  300. }
  301. if (!string.IsNullOrEmpty(job.InputAudioSync))
  302. {
  303. inputModifier += " -async " + job.InputAudioSync;
  304. }
  305. if (!string.IsNullOrEmpty(job.InputVideoSync))
  306. {
  307. inputModifier += " -vsync " + job.InputVideoSync;
  308. }
  309. if (job.ReadInputAtNativeFramerate)
  310. {
  311. inputModifier += " -re";
  312. }
  313. return inputModifier;
  314. }
  315. private string GetUserAgentParam(EncodingJob job)
  316. {
  317. string useragent = null;
  318. job.RemoteHttpHeaders.TryGetValue("User-Agent", out useragent);
  319. if (!string.IsNullOrWhiteSpace(useragent))
  320. {
  321. return "-user-agent \"" + useragent + "\"";
  322. }
  323. return string.Empty;
  324. }
  325. /// <summary>
  326. /// Gets the probe size argument.
  327. /// </summary>
  328. /// <param name="job">The job.</param>
  329. /// <returns>System.String.</returns>
  330. private string GetProbeSizeArgument(EncodingJob job)
  331. {
  332. if (job.PlayableStreamFileNames.Count > 0)
  333. {
  334. return MediaEncoder.GetProbeSizeArgument(job.PlayableStreamFileNames.ToArray(), job.InputProtocol);
  335. }
  336. return MediaEncoder.GetProbeSizeArgument(new[] { job.MediaPath }, job.InputProtocol);
  337. }
  338. /// <summary>
  339. /// Gets the fast seek command line parameter.
  340. /// </summary>
  341. /// <param name="options">The options.</param>
  342. /// <returns>System.String.</returns>
  343. /// <value>The fast seek command line parameter.</value>
  344. protected string GetFastSeekCommandLineParameter(EncodingJobOptions options)
  345. {
  346. var time = options.StartTimeTicks;
  347. if (time.HasValue && time.Value > 0)
  348. {
  349. return string.Format("-ss {0}", MediaEncoder.GetTimeParameter(time.Value));
  350. }
  351. return string.Empty;
  352. }
  353. /// <summary>
  354. /// Gets the input argument.
  355. /// </summary>
  356. /// <param name="job">The job.</param>
  357. /// <returns>System.String.</returns>
  358. protected string GetInputArgument(EncodingJob job)
  359. {
  360. var arg = "-i " + GetInputPathArgument(job);
  361. if (job.SubtitleStream != null)
  362. {
  363. if (job.SubtitleStream.IsExternal && !job.SubtitleStream.IsTextSubtitleStream)
  364. {
  365. arg += " -i \"" + job.SubtitleStream.Path + "\"";
  366. }
  367. }
  368. return arg;
  369. }
  370. private string GetInputPathArgument(EncodingJob job)
  371. {
  372. var protocol = job.InputProtocol;
  373. var inputPath = new[] { job.MediaPath };
  374. if (job.IsInputVideo)
  375. {
  376. if (!(job.VideoType == VideoType.Iso && job.IsoMount == null))
  377. {
  378. inputPath = MediaEncoderHelpers.GetInputArgument(job.MediaPath, job.InputProtocol, job.IsoMount, job.PlayableStreamFileNames);
  379. }
  380. }
  381. return MediaEncoder.GetInputArgument(inputPath, protocol);
  382. }
  383. private async Task AcquireResources(EncodingJob state, CancellationToken cancellationToken)
  384. {
  385. if (state.VideoType == VideoType.Iso && state.IsoType.HasValue && IsoManager.CanMount(state.MediaPath))
  386. {
  387. state.IsoMount = await IsoManager.Mount(state.MediaPath, cancellationToken).ConfigureAwait(false);
  388. }
  389. if (string.IsNullOrEmpty(state.MediaPath))
  390. {
  391. var checkCodecs = false;
  392. if (string.Equals(state.ItemType, typeof(LiveTvChannel).Name))
  393. {
  394. var streamInfo = await LiveTvManager.GetChannelStream(state.Options.ItemId, cancellationToken).ConfigureAwait(false);
  395. state.LiveTvStreamId = streamInfo.Id;
  396. state.MediaPath = streamInfo.Path;
  397. state.InputProtocol = streamInfo.Protocol;
  398. await Task.Delay(1500, cancellationToken).ConfigureAwait(false);
  399. AttachMediaStreamInfo(state, streamInfo, state.Options);
  400. checkCodecs = true;
  401. }
  402. else if (string.Equals(state.ItemType, typeof(LiveTvVideoRecording).Name) ||
  403. string.Equals(state.ItemType, typeof(LiveTvAudioRecording).Name))
  404. {
  405. var streamInfo = await LiveTvManager.GetRecordingStream(state.Options.ItemId, cancellationToken).ConfigureAwait(false);
  406. state.LiveTvStreamId = streamInfo.Id;
  407. state.MediaPath = streamInfo.Path;
  408. state.InputProtocol = streamInfo.Protocol;
  409. await Task.Delay(1500, cancellationToken).ConfigureAwait(false);
  410. AttachMediaStreamInfo(state, streamInfo, state.Options);
  411. checkCodecs = true;
  412. }
  413. if (state.IsVideoRequest && checkCodecs)
  414. {
  415. if (state.VideoStream != null && EncodingJobFactory.CanStreamCopyVideo(state.Options, state.VideoStream))
  416. {
  417. state.OutputVideoCodec = "copy";
  418. }
  419. if (state.AudioStream != null && EncodingJobFactory.CanStreamCopyAudio(state.Options, state.AudioStream, state.SupportedAudioCodecs))
  420. {
  421. state.OutputAudioCodec = "copy";
  422. }
  423. }
  424. }
  425. }
  426. private void AttachMediaStreamInfo(EncodingJob state,
  427. ChannelMediaInfo mediaInfo,
  428. EncodingJobOptions videoRequest)
  429. {
  430. var mediaSource = mediaInfo.ToMediaSource();
  431. state.InputProtocol = mediaSource.Protocol;
  432. state.MediaPath = mediaSource.Path;
  433. state.RunTimeTicks = mediaSource.RunTimeTicks;
  434. state.RemoteHttpHeaders = mediaSource.RequiredHttpHeaders;
  435. state.InputBitrate = mediaSource.Bitrate;
  436. state.InputFileSize = mediaSource.Size;
  437. state.ReadInputAtNativeFramerate = mediaSource.ReadAtNativeFramerate;
  438. if (state.ReadInputAtNativeFramerate)
  439. {
  440. state.OutputAudioSync = "1000";
  441. state.InputVideoSync = "-1";
  442. state.InputAudioSync = "1";
  443. }
  444. EncodingJobFactory.AttachMediaStreamInfo(state, mediaSource.MediaStreams, videoRequest);
  445. }
  446. /// <summary>
  447. /// Gets the internal graphical subtitle param.
  448. /// </summary>
  449. /// <param name="state">The state.</param>
  450. /// <param name="outputVideoCodec">The output video codec.</param>
  451. /// <returns>System.String.</returns>
  452. protected string GetGraphicalSubtitleParam(EncodingJob state, string outputVideoCodec)
  453. {
  454. var outputSizeParam = string.Empty;
  455. var request = state.Options;
  456. // Add resolution params, if specified
  457. if (request.Width.HasValue || request.Height.HasValue || request.MaxHeight.HasValue || request.MaxWidth.HasValue)
  458. {
  459. outputSizeParam = GetOutputSizeParam(state, outputVideoCodec).TrimEnd('"');
  460. outputSizeParam = "," + outputSizeParam.Substring(outputSizeParam.IndexOf("scale", StringComparison.OrdinalIgnoreCase));
  461. }
  462. var videoSizeParam = string.Empty;
  463. if (state.VideoStream != null && state.VideoStream.Width.HasValue && state.VideoStream.Height.HasValue)
  464. {
  465. videoSizeParam = string.Format(",scale={0}:{1}", state.VideoStream.Width.Value.ToString(UsCulture), state.VideoStream.Height.Value.ToString(UsCulture));
  466. }
  467. var mapPrefix = state.SubtitleStream.IsExternal ?
  468. 1 :
  469. 0;
  470. var subtitleStreamIndex = state.SubtitleStream.IsExternal
  471. ? 0
  472. : state.SubtitleStream.Index;
  473. return string.Format(" -filter_complex \"[{0}:{1}]format=yuva444p{4},lut=u=128:v=128:y=gammaval(.3)[sub] ; [0:{2}] [sub] overlay{3}\"",
  474. mapPrefix.ToString(UsCulture),
  475. subtitleStreamIndex.ToString(UsCulture),
  476. state.VideoStream.Index.ToString(UsCulture),
  477. outputSizeParam,
  478. videoSizeParam);
  479. }
  480. /// <summary>
  481. /// Gets the video bitrate to specify on the command line
  482. /// </summary>
  483. /// <param name="state">The state.</param>
  484. /// <param name="videoCodec">The video codec.</param>
  485. /// <param name="isHls">if set to <c>true</c> [is HLS].</param>
  486. /// <returns>System.String.</returns>
  487. protected string GetVideoQualityParam(EncodingJob state, string videoCodec, bool isHls)
  488. {
  489. var param = string.Empty;
  490. var isVc1 = state.VideoStream != null &&
  491. string.Equals(state.VideoStream.Codec, "vc1", StringComparison.OrdinalIgnoreCase);
  492. var qualitySetting = GetQualitySetting();
  493. if (string.Equals(videoCodec, "libx264", StringComparison.OrdinalIgnoreCase))
  494. {
  495. param = "-preset superfast";
  496. switch (qualitySetting)
  497. {
  498. case EncodingQuality.HighSpeed:
  499. param += " -crf 28";
  500. break;
  501. case EncodingQuality.HighQuality:
  502. param += " -crf 25";
  503. break;
  504. case EncodingQuality.MaxQuality:
  505. param += " -crf 21";
  506. break;
  507. }
  508. }
  509. else if (string.Equals(videoCodec, "libx265", StringComparison.OrdinalIgnoreCase))
  510. {
  511. param = "-preset fast";
  512. switch (qualitySetting)
  513. {
  514. case EncodingQuality.HighSpeed:
  515. param += " -crf 28";
  516. break;
  517. case EncodingQuality.HighQuality:
  518. param += " -crf 25";
  519. break;
  520. case EncodingQuality.MaxQuality:
  521. param += " -crf 21";
  522. break;
  523. }
  524. }
  525. // webm
  526. else if (string.Equals(videoCodec, "libvpx", StringComparison.OrdinalIgnoreCase))
  527. {
  528. // Values 0-3, 0 being highest quality but slower
  529. var profileScore = 0;
  530. string crf;
  531. var qmin = "0";
  532. var qmax = "50";
  533. switch (qualitySetting)
  534. {
  535. case EncodingQuality.HighSpeed:
  536. crf = "10";
  537. break;
  538. case EncodingQuality.HighQuality:
  539. crf = "6";
  540. break;
  541. case EncodingQuality.MaxQuality:
  542. crf = "4";
  543. break;
  544. default:
  545. throw new ArgumentException("Unrecognized quality setting");
  546. }
  547. if (isVc1)
  548. {
  549. profileScore++;
  550. }
  551. // Max of 2
  552. profileScore = Math.Min(profileScore, 2);
  553. // http://www.webmproject.org/docs/encoder-parameters/
  554. param = string.Format("-speed 16 -quality good -profile:v {0} -slices 8 -crf {1} -qmin {2} -qmax {3}",
  555. profileScore.ToString(UsCulture),
  556. crf,
  557. qmin,
  558. qmax);
  559. }
  560. else if (string.Equals(videoCodec, "mpeg4", StringComparison.OrdinalIgnoreCase))
  561. {
  562. param = "-mbd rd -flags +mv4+aic -trellis 2 -cmp 2 -subcmp 2 -bf 2";
  563. }
  564. // asf/wmv
  565. else if (string.Equals(videoCodec, "wmv2", StringComparison.OrdinalIgnoreCase))
  566. {
  567. param = "-qmin 2";
  568. }
  569. else if (string.Equals(videoCodec, "msmpeg4", StringComparison.OrdinalIgnoreCase))
  570. {
  571. param = "-mbd 2";
  572. }
  573. param += GetVideoBitrateParam(state, videoCodec, isHls);
  574. var framerate = GetFramerateParam(state);
  575. if (framerate.HasValue)
  576. {
  577. param += string.Format(" -r {0}", framerate.Value.ToString(UsCulture));
  578. }
  579. if (!string.IsNullOrEmpty(state.OutputVideoSync))
  580. {
  581. param += " -vsync " + state.OutputVideoSync;
  582. }
  583. if (!string.IsNullOrEmpty(state.Options.Profile))
  584. {
  585. param += " -profile:v " + state.Options.Profile;
  586. }
  587. if (state.Options.Level.HasValue)
  588. {
  589. param += " -level " + state.Options.Level.Value.ToString(UsCulture);
  590. }
  591. return "-pix_fmt yuv420p " + param;
  592. }
  593. protected string GetVideoBitrateParam(EncodingJob state, string videoCodec, bool isHls)
  594. {
  595. var bitrate = state.OutputVideoBitrate;
  596. if (bitrate.HasValue)
  597. {
  598. var hasFixedResolution = state.Options.HasFixedResolution;
  599. if (string.Equals(videoCodec, "libvpx", StringComparison.OrdinalIgnoreCase))
  600. {
  601. if (hasFixedResolution)
  602. {
  603. return string.Format(" -minrate:v ({0}*.90) -maxrate:v ({0}*1.10) -bufsize:v {0} -b:v {0}", bitrate.Value.ToString(UsCulture));
  604. }
  605. // With vpx when crf is used, b:v becomes a max rate
  606. // https://trac.ffmpeg.org/wiki/vpxEncodingGuide. But higher bitrate source files -b:v causes judder so limite the bitrate but dont allow it to "saturate" the bitrate. So dont contrain it down just up.
  607. return string.Format(" -maxrate:v {0} -bufsize:v ({0}*2) -b:v {0}", bitrate.Value.ToString(UsCulture));
  608. }
  609. if (string.Equals(videoCodec, "msmpeg4", StringComparison.OrdinalIgnoreCase))
  610. {
  611. return string.Format(" -b:v {0}", bitrate.Value.ToString(UsCulture));
  612. }
  613. // H264
  614. if (hasFixedResolution)
  615. {
  616. if (isHls)
  617. {
  618. return string.Format(" -b:v {0} -maxrate ({0}*.80) -bufsize {0}", bitrate.Value.ToString(UsCulture));
  619. }
  620. return string.Format(" -b:v {0}", bitrate.Value.ToString(UsCulture));
  621. }
  622. return string.Format(" -maxrate {0} -bufsize {1}",
  623. bitrate.Value.ToString(UsCulture),
  624. (bitrate.Value * 2).ToString(UsCulture));
  625. }
  626. return string.Empty;
  627. }
  628. protected double? GetFramerateParam(EncodingJob state)
  629. {
  630. if (state.Options.Framerate.HasValue)
  631. {
  632. return state.Options.Framerate.Value;
  633. }
  634. var maxrate = state.Options.MaxFramerate;
  635. if (maxrate.HasValue && state.VideoStream != null)
  636. {
  637. var contentRate = state.VideoStream.AverageFrameRate ?? state.VideoStream.RealFrameRate;
  638. if (contentRate.HasValue && contentRate.Value > maxrate.Value)
  639. {
  640. return maxrate;
  641. }
  642. }
  643. return null;
  644. }
  645. /// <summary>
  646. /// Gets the map args.
  647. /// </summary>
  648. /// <param name="state">The state.</param>
  649. /// <returns>System.String.</returns>
  650. protected virtual string GetMapArgs(EncodingJob state)
  651. {
  652. // If we don't have known media info
  653. // If input is video, use -sn to drop subtitles
  654. // Otherwise just return empty
  655. if (state.VideoStream == null && state.AudioStream == null)
  656. {
  657. return state.IsInputVideo ? "-sn" : string.Empty;
  658. }
  659. // We have media info, but we don't know the stream indexes
  660. if (state.VideoStream != null && state.VideoStream.Index == -1)
  661. {
  662. return "-sn";
  663. }
  664. // We have media info, but we don't know the stream indexes
  665. if (state.AudioStream != null && state.AudioStream.Index == -1)
  666. {
  667. return state.IsInputVideo ? "-sn" : string.Empty;
  668. }
  669. var args = string.Empty;
  670. if (state.VideoStream != null)
  671. {
  672. args += string.Format("-map 0:{0}", state.VideoStream.Index);
  673. }
  674. else
  675. {
  676. args += "-map -0:v";
  677. }
  678. if (state.AudioStream != null)
  679. {
  680. args += string.Format(" -map 0:{0}", state.AudioStream.Index);
  681. }
  682. else
  683. {
  684. args += " -map -0:a";
  685. }
  686. if (state.SubtitleStream == null)
  687. {
  688. args += " -map -0:s";
  689. }
  690. else if (state.SubtitleStream.IsExternal && !state.SubtitleStream.IsTextSubtitleStream)
  691. {
  692. args += " -map 1:0 -sn";
  693. }
  694. return args;
  695. }
  696. /// <summary>
  697. /// Determines whether the specified stream is H264.
  698. /// </summary>
  699. /// <param name="stream">The stream.</param>
  700. /// <returns><c>true</c> if the specified stream is H264; otherwise, <c>false</c>.</returns>
  701. protected bool IsH264(MediaStream stream)
  702. {
  703. var codec = stream.Codec ?? string.Empty;
  704. return codec.IndexOf("264", StringComparison.OrdinalIgnoreCase) != -1 ||
  705. codec.IndexOf("avc", StringComparison.OrdinalIgnoreCase) != -1;
  706. }
  707. /// <summary>
  708. /// If we're going to put a fixed size on the command line, this will calculate it
  709. /// </summary>
  710. /// <param name="state">The state.</param>
  711. /// <param name="outputVideoCodec">The output video codec.</param>
  712. /// <param name="allowTimeStampCopy">if set to <c>true</c> [allow time stamp copy].</param>
  713. /// <returns>System.String.</returns>
  714. protected string GetOutputSizeParam(EncodingJob state,
  715. string outputVideoCodec,
  716. bool allowTimeStampCopy = true)
  717. {
  718. // http://sonnati.wordpress.com/2012/10/19/ffmpeg-the-swiss-army-knife-of-internet-streaming-part-vi/
  719. var request = state.Options;
  720. var filters = new List<string>();
  721. if (state.DeInterlace)
  722. {
  723. filters.Add("yadif=0:-1:0");
  724. }
  725. // If fixed dimensions were supplied
  726. if (request.Width.HasValue && request.Height.HasValue)
  727. {
  728. var widthParam = request.Width.Value.ToString(UsCulture);
  729. var heightParam = request.Height.Value.ToString(UsCulture);
  730. filters.Add(string.Format("scale=trunc({0}/2)*2:trunc({1}/2)*2", widthParam, heightParam));
  731. }
  732. // If Max dimensions were supplied, for width selects lowest even number between input width and width req size and selects lowest even number from in width*display aspect and requested size
  733. else if (request.MaxWidth.HasValue && request.MaxHeight.HasValue)
  734. {
  735. var maxWidthParam = request.MaxWidth.Value.ToString(UsCulture);
  736. var maxHeightParam = request.MaxHeight.Value.ToString(UsCulture);
  737. filters.Add(string.Format("scale=trunc(min(iw\\,{0})/2)*2:trunc(min((iw/dar)\\,{1})/2)*2", maxWidthParam, maxHeightParam));
  738. }
  739. // If a fixed width was requested
  740. else if (request.Width.HasValue)
  741. {
  742. var widthParam = request.Width.Value.ToString(UsCulture);
  743. filters.Add(string.Format("scale={0}:trunc(ow/a/2)*2", widthParam));
  744. }
  745. // If a fixed height was requested
  746. else if (request.Height.HasValue)
  747. {
  748. var heightParam = request.Height.Value.ToString(UsCulture);
  749. filters.Add(string.Format("scale=trunc(oh*a*2)/2:{0}", heightParam));
  750. }
  751. // If a max width was requested
  752. else if (request.MaxWidth.HasValue && (!request.MaxHeight.HasValue || state.VideoStream == null))
  753. {
  754. var maxWidthParam = request.MaxWidth.Value.ToString(UsCulture);
  755. filters.Add(string.Format("scale=min(iw\\,{0}):trunc(ow/dar/2)*2", maxWidthParam));
  756. }
  757. // If a max height was requested
  758. else if (request.MaxHeight.HasValue && (!request.MaxWidth.HasValue || state.VideoStream == null))
  759. {
  760. var maxHeightParam = request.MaxHeight.Value.ToString(UsCulture);
  761. filters.Add(string.Format("scale=trunc(oh*a*2)/2:min(ih\\,{0})", maxHeightParam));
  762. }
  763. else if (request.MaxWidth.HasValue ||
  764. request.MaxHeight.HasValue ||
  765. request.Width.HasValue ||
  766. request.Height.HasValue)
  767. {
  768. if (state.VideoStream != null)
  769. {
  770. // Need to perform calculations manually
  771. // Try to account for bad media info
  772. var currentHeight = state.VideoStream.Height ?? request.MaxHeight ?? request.Height ?? 0;
  773. var currentWidth = state.VideoStream.Width ?? request.MaxWidth ?? request.Width ?? 0;
  774. var outputSize = DrawingUtils.Resize(currentWidth, currentHeight, request.Width, request.Height, request.MaxWidth, request.MaxHeight);
  775. var manualWidthParam = outputSize.Width.ToString(UsCulture);
  776. var manualHeightParam = outputSize.Height.ToString(UsCulture);
  777. filters.Add(string.Format("scale=trunc({0}/2)*2:trunc({1}/2)*2", manualWidthParam, manualHeightParam));
  778. }
  779. }
  780. var output = string.Empty;
  781. if (state.SubtitleStream != null && state.SubtitleStream.IsTextSubtitleStream)
  782. {
  783. var subParam = GetTextSubtitleParam(state);
  784. filters.Add(subParam);
  785. if (allowTimeStampCopy)
  786. {
  787. output += " -copyts";
  788. }
  789. }
  790. if (filters.Count > 0)
  791. {
  792. output += string.Format(" -vf \"{0}\"", string.Join(",", filters.ToArray()));
  793. }
  794. return output;
  795. }
  796. /// <summary>
  797. /// Gets the text subtitle param.
  798. /// </summary>
  799. /// <param name="state">The state.</param>
  800. /// <returns>System.String.</returns>
  801. protected string GetTextSubtitleParam(EncodingJob state)
  802. {
  803. var seconds = Math.Round(TimeSpan.FromTicks(state.Options.StartTimeTicks ?? 0).TotalSeconds);
  804. if (state.SubtitleStream.IsExternal)
  805. {
  806. var subtitlePath = state.SubtitleStream.Path;
  807. var charsetParam = string.Empty;
  808. if (!string.IsNullOrEmpty(state.SubtitleStream.Language))
  809. {
  810. var charenc = SubtitleEncoder.GetSubtitleFileCharacterSet(subtitlePath);
  811. if (!string.IsNullOrEmpty(charenc))
  812. {
  813. charsetParam = ":charenc=" + charenc;
  814. }
  815. }
  816. // TODO: Perhaps also use original_size=1920x800 ??
  817. return string.Format("subtitles=filename='{0}'{1},setpts=PTS -{2}/TB",
  818. subtitlePath.Replace('\\', '/').Replace(":/", "\\:/"),
  819. charsetParam,
  820. seconds.ToString(UsCulture));
  821. }
  822. return string.Format("subtitles='{0}:si={1}',setpts=PTS -{2}/TB",
  823. state.MediaPath.Replace('\\', '/').Replace(":/", "\\:/"),
  824. state.InternalSubtitleStreamOffset.ToString(UsCulture),
  825. seconds.ToString(UsCulture));
  826. }
  827. protected string GetAudioFilterParam(EncodingJob state, bool isHls)
  828. {
  829. var volParam = string.Empty;
  830. var audioSampleRate = string.Empty;
  831. var channels = state.OutputAudioChannels;
  832. // Boost volume to 200% when downsampling from 6ch to 2ch
  833. if (channels.HasValue && channels.Value <= 2)
  834. {
  835. if (state.AudioStream != null && state.AudioStream.Channels.HasValue && state.AudioStream.Channels.Value > 5)
  836. {
  837. volParam = ",volume=" + GetEncodingOptions().DownMixAudioBoost.ToString(UsCulture);
  838. }
  839. }
  840. if (state.OutputAudioSampleRate.HasValue)
  841. {
  842. audioSampleRate = state.OutputAudioSampleRate.Value + ":";
  843. }
  844. var adelay = isHls ? "adelay=1," : string.Empty;
  845. var pts = string.Empty;
  846. if (state.SubtitleStream != null && state.SubtitleStream.IsTextSubtitleStream)
  847. {
  848. var seconds = TimeSpan.FromTicks(state.Options.StartTimeTicks ?? 0).TotalSeconds;
  849. pts = string.Format(",asetpts=PTS-{0}/TB", Math.Round(seconds).ToString(UsCulture));
  850. }
  851. return string.Format("-af \"{0}aresample={1}async={4}{2}{3}\"",
  852. adelay,
  853. audioSampleRate,
  854. volParam,
  855. pts,
  856. state.OutputAudioSync);
  857. }
  858. }
  859. }