BaseEncoder.cs 34 KB

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