BaseEncoder.cs 34 KB

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