BaseEncoder.cs 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957
  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. Directory.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. Directory.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 (!File.Exists(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. return inputModifier;
  283. }
  284. private string GetUserAgentParam(EncodingJob job)
  285. {
  286. string useragent = null;
  287. job.RemoteHttpHeaders.TryGetValue("User-Agent", out useragent);
  288. if (!string.IsNullOrWhiteSpace(useragent))
  289. {
  290. return "-user-agent \"" + useragent + "\"";
  291. }
  292. return string.Empty;
  293. }
  294. /// <summary>
  295. /// Gets the probe size argument.
  296. /// </summary>
  297. /// <param name="job">The job.</param>
  298. /// <returns>System.String.</returns>
  299. private string GetProbeSizeArgument(EncodingJob job)
  300. {
  301. if (job.PlayableStreamFileNames.Count > 0)
  302. {
  303. return MediaEncoder.GetProbeSizeArgument(job.PlayableStreamFileNames.ToArray(), job.InputProtocol);
  304. }
  305. return MediaEncoder.GetProbeSizeArgument(new[] { job.MediaPath }, job.InputProtocol);
  306. }
  307. /// <summary>
  308. /// Gets the fast seek command line parameter.
  309. /// </summary>
  310. /// <param name="options">The options.</param>
  311. /// <returns>System.String.</returns>
  312. /// <value>The fast seek command line parameter.</value>
  313. protected string GetFastSeekCommandLineParameter(EncodingJobOptions options)
  314. {
  315. var time = options.StartTimeTicks;
  316. if (time.HasValue && time.Value > 0)
  317. {
  318. return string.Format("-ss {0}", MediaEncoder.GetTimeParameter(time.Value));
  319. }
  320. return string.Empty;
  321. }
  322. /// <summary>
  323. /// Gets the input argument.
  324. /// </summary>
  325. /// <param name="job">The job.</param>
  326. /// <returns>System.String.</returns>
  327. protected string GetInputArgument(EncodingJob job)
  328. {
  329. var arg = "-i " + GetInputPathArgument(job);
  330. if (job.SubtitleStream != null)
  331. {
  332. if (job.SubtitleStream.IsExternal && !job.SubtitleStream.IsTextSubtitleStream)
  333. {
  334. arg += " -i \"" + job.SubtitleStream.Path + "\"";
  335. }
  336. }
  337. return arg;
  338. }
  339. private string GetInputPathArgument(EncodingJob job)
  340. {
  341. var protocol = job.InputProtocol;
  342. var inputPath = new[] { job.MediaPath };
  343. if (job.IsInputVideo)
  344. {
  345. if (!(job.VideoType == VideoType.Iso && job.IsoMount == null))
  346. {
  347. inputPath = MediaEncoderHelpers.GetInputArgument(job.MediaPath, job.InputProtocol, job.IsoMount, job.PlayableStreamFileNames);
  348. }
  349. }
  350. return MediaEncoder.GetInputArgument(inputPath, protocol);
  351. }
  352. private async Task AcquireResources(EncodingJob state, CancellationToken cancellationToken)
  353. {
  354. if (state.VideoType == VideoType.Iso && state.IsoType.HasValue && IsoManager.CanMount(state.MediaPath))
  355. {
  356. state.IsoMount = await IsoManager.Mount(state.MediaPath, cancellationToken).ConfigureAwait(false);
  357. }
  358. if (state.MediaSource.RequiresOpening ?? false)
  359. {
  360. var liveStreamResponse = await MediaSourceManager.OpenLiveStream(new LiveStreamRequest
  361. {
  362. OpenToken = state.MediaSource.OpenToken
  363. }, false, cancellationToken).ConfigureAwait(false);
  364. AttachMediaStreamInfo(state, liveStreamResponse.MediaSource, state.Options);
  365. if (state.IsVideoRequest)
  366. {
  367. EncodingJobFactory.TryStreamCopy(state, state.Options);
  368. }
  369. }
  370. if (state.MediaSource.BufferMs.HasValue)
  371. {
  372. await Task.Delay(state.MediaSource.BufferMs.Value, cancellationToken).ConfigureAwait(false);
  373. }
  374. }
  375. private void AttachMediaStreamInfo(EncodingJob state,
  376. MediaSourceInfo mediaSource,
  377. EncodingJobOptions videoRequest)
  378. {
  379. EncodingJobFactory.AttachMediaStreamInfo(state, mediaSource, videoRequest);
  380. }
  381. /// <summary>
  382. /// Gets the internal graphical subtitle param.
  383. /// </summary>
  384. /// <param name="state">The state.</param>
  385. /// <param name="outputVideoCodec">The output video codec.</param>
  386. /// <returns>System.String.</returns>
  387. protected string GetGraphicalSubtitleParam(EncodingJob state, string outputVideoCodec)
  388. {
  389. var outputSizeParam = string.Empty;
  390. var request = state.Options;
  391. // Add resolution params, if specified
  392. if (request.Width.HasValue || request.Height.HasValue || request.MaxHeight.HasValue || request.MaxWidth.HasValue)
  393. {
  394. outputSizeParam = GetOutputSizeParam(state, outputVideoCodec).TrimEnd('"');
  395. outputSizeParam = "," + outputSizeParam.Substring(outputSizeParam.IndexOf("scale", StringComparison.OrdinalIgnoreCase));
  396. }
  397. var videoSizeParam = string.Empty;
  398. if (state.VideoStream != null && state.VideoStream.Width.HasValue && state.VideoStream.Height.HasValue)
  399. {
  400. videoSizeParam = string.Format(",scale={0}:{1}", state.VideoStream.Width.Value.ToString(UsCulture), state.VideoStream.Height.Value.ToString(UsCulture));
  401. }
  402. var mapPrefix = state.SubtitleStream.IsExternal ?
  403. 1 :
  404. 0;
  405. var subtitleStreamIndex = state.SubtitleStream.IsExternal
  406. ? 0
  407. : state.SubtitleStream.Index;
  408. return string.Format(" -filter_complex \"[{0}:{1}]format=yuva444p{4},lut=u=128:v=128:y=gammaval(.3)[sub] ; [0:{2}] [sub] overlay{3}\"",
  409. mapPrefix.ToString(UsCulture),
  410. subtitleStreamIndex.ToString(UsCulture),
  411. state.VideoStream.Index.ToString(UsCulture),
  412. outputSizeParam,
  413. videoSizeParam);
  414. }
  415. /// <summary>
  416. /// Gets the video bitrate to specify on the command line
  417. /// </summary>
  418. /// <param name="state">The state.</param>
  419. /// <param name="videoCodec">The video codec.</param>
  420. /// <param name="isHls">if set to <c>true</c> [is HLS].</param>
  421. /// <returns>System.String.</returns>
  422. protected string GetVideoQualityParam(EncodingJob state, string videoCodec, bool isHls)
  423. {
  424. var param = string.Empty;
  425. var isVc1 = state.VideoStream != null &&
  426. string.Equals(state.VideoStream.Codec, "vc1", StringComparison.OrdinalIgnoreCase);
  427. var qualitySetting = state.Quality;
  428. if (string.Equals(videoCodec, "libx264", StringComparison.OrdinalIgnoreCase))
  429. {
  430. param = "-preset superfast";
  431. switch (qualitySetting)
  432. {
  433. case EncodingQuality.HighSpeed:
  434. param += " -crf 28";
  435. break;
  436. case EncodingQuality.HighQuality:
  437. param += " -crf 25";
  438. break;
  439. case EncodingQuality.MaxQuality:
  440. param += " -crf 21";
  441. break;
  442. }
  443. }
  444. else if (string.Equals(videoCodec, "libx265", StringComparison.OrdinalIgnoreCase))
  445. {
  446. param = "-preset fast";
  447. switch (qualitySetting)
  448. {
  449. case EncodingQuality.HighSpeed:
  450. param += " -crf 28";
  451. break;
  452. case EncodingQuality.HighQuality:
  453. param += " -crf 25";
  454. break;
  455. case EncodingQuality.MaxQuality:
  456. param += " -crf 21";
  457. break;
  458. }
  459. }
  460. // webm
  461. else if (string.Equals(videoCodec, "libvpx", StringComparison.OrdinalIgnoreCase))
  462. {
  463. // Values 0-3, 0 being highest quality but slower
  464. var profileScore = 0;
  465. string crf;
  466. var qmin = "0";
  467. var qmax = "50";
  468. switch (qualitySetting)
  469. {
  470. case EncodingQuality.HighSpeed:
  471. crf = "10";
  472. break;
  473. case EncodingQuality.HighQuality:
  474. crf = "6";
  475. break;
  476. case EncodingQuality.MaxQuality:
  477. crf = "4";
  478. break;
  479. default:
  480. throw new ArgumentException("Unrecognized quality setting");
  481. }
  482. if (isVc1)
  483. {
  484. profileScore++;
  485. }
  486. // Max of 2
  487. profileScore = Math.Min(profileScore, 2);
  488. // http://www.webmproject.org/docs/encoder-parameters/
  489. param = string.Format("-speed 16 -quality good -profile:v {0} -slices 8 -crf {1} -qmin {2} -qmax {3}",
  490. profileScore.ToString(UsCulture),
  491. crf,
  492. qmin,
  493. qmax);
  494. }
  495. else if (string.Equals(videoCodec, "mpeg4", StringComparison.OrdinalIgnoreCase))
  496. {
  497. param = "-mbd rd -flags +mv4+aic -trellis 2 -cmp 2 -subcmp 2 -bf 2";
  498. }
  499. // asf/wmv
  500. else if (string.Equals(videoCodec, "wmv2", StringComparison.OrdinalIgnoreCase))
  501. {
  502. param = "-qmin 2";
  503. }
  504. else if (string.Equals(videoCodec, "msmpeg4", StringComparison.OrdinalIgnoreCase))
  505. {
  506. param = "-mbd 2";
  507. }
  508. param += GetVideoBitrateParam(state, videoCodec, isHls);
  509. var framerate = GetFramerateParam(state);
  510. if (framerate.HasValue)
  511. {
  512. param += string.Format(" -r {0}", framerate.Value.ToString(UsCulture));
  513. }
  514. if (!string.IsNullOrEmpty(state.OutputVideoSync))
  515. {
  516. param += " -vsync " + state.OutputVideoSync;
  517. }
  518. if (!string.IsNullOrEmpty(state.Options.Profile))
  519. {
  520. param += " -profile:v " + state.Options.Profile;
  521. }
  522. if (state.Options.Level.HasValue)
  523. {
  524. param += " -level " + state.Options.Level.Value.ToString(UsCulture);
  525. }
  526. return "-pix_fmt yuv420p " + param;
  527. }
  528. protected string GetVideoBitrateParam(EncodingJob state, string videoCodec, bool isHls)
  529. {
  530. var bitrate = state.OutputVideoBitrate;
  531. if (bitrate.HasValue)
  532. {
  533. var hasFixedResolution = state.Options.HasFixedResolution;
  534. if (string.Equals(videoCodec, "libvpx", StringComparison.OrdinalIgnoreCase))
  535. {
  536. if (hasFixedResolution)
  537. {
  538. return string.Format(" -minrate:v ({0}*.90) -maxrate:v ({0}*1.10) -bufsize:v {0} -b:v {0}", bitrate.Value.ToString(UsCulture));
  539. }
  540. // With vpx when crf is used, b:v becomes a max rate
  541. // 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.
  542. return string.Format(" -maxrate:v {0} -bufsize:v ({0}*2) -b:v {0}", bitrate.Value.ToString(UsCulture));
  543. }
  544. if (string.Equals(videoCodec, "msmpeg4", StringComparison.OrdinalIgnoreCase))
  545. {
  546. return string.Format(" -b:v {0}", bitrate.Value.ToString(UsCulture));
  547. }
  548. // H264
  549. if (hasFixedResolution)
  550. {
  551. if (isHls)
  552. {
  553. return string.Format(" -b:v {0} -maxrate ({0}*.80) -bufsize {0}", bitrate.Value.ToString(UsCulture));
  554. }
  555. return string.Format(" -b:v {0}", bitrate.Value.ToString(UsCulture));
  556. }
  557. return string.Format(" -maxrate {0} -bufsize {1}",
  558. bitrate.Value.ToString(UsCulture),
  559. (bitrate.Value * 2).ToString(UsCulture));
  560. }
  561. return string.Empty;
  562. }
  563. protected double? GetFramerateParam(EncodingJob state)
  564. {
  565. if (state.Options.Framerate.HasValue)
  566. {
  567. return state.Options.Framerate.Value;
  568. }
  569. var maxrate = state.Options.MaxFramerate;
  570. if (maxrate.HasValue && state.VideoStream != null)
  571. {
  572. var contentRate = state.VideoStream.AverageFrameRate ?? state.VideoStream.RealFrameRate;
  573. if (contentRate.HasValue && contentRate.Value > maxrate.Value)
  574. {
  575. return maxrate;
  576. }
  577. }
  578. return null;
  579. }
  580. /// <summary>
  581. /// Gets the map args.
  582. /// </summary>
  583. /// <param name="state">The state.</param>
  584. /// <returns>System.String.</returns>
  585. protected virtual string GetMapArgs(EncodingJob state)
  586. {
  587. // If we don't have known media info
  588. // If input is video, use -sn to drop subtitles
  589. // Otherwise just return empty
  590. if (state.VideoStream == null && state.AudioStream == null)
  591. {
  592. return state.IsInputVideo ? "-sn" : string.Empty;
  593. }
  594. // We have media info, but we don't know the stream indexes
  595. if (state.VideoStream != null && state.VideoStream.Index == -1)
  596. {
  597. return "-sn";
  598. }
  599. // We have media info, but we don't know the stream indexes
  600. if (state.AudioStream != null && state.AudioStream.Index == -1)
  601. {
  602. return state.IsInputVideo ? "-sn" : string.Empty;
  603. }
  604. var args = string.Empty;
  605. if (state.VideoStream != null)
  606. {
  607. args += string.Format("-map 0:{0}", state.VideoStream.Index);
  608. }
  609. else
  610. {
  611. args += "-map -0:v";
  612. }
  613. if (state.AudioStream != null)
  614. {
  615. args += string.Format(" -map 0:{0}", state.AudioStream.Index);
  616. }
  617. else
  618. {
  619. args += " -map -0:a";
  620. }
  621. if (state.SubtitleStream == null)
  622. {
  623. args += " -map -0:s";
  624. }
  625. else if (state.SubtitleStream.IsExternal && !state.SubtitleStream.IsTextSubtitleStream)
  626. {
  627. args += " -map 1:0 -sn";
  628. }
  629. return args;
  630. }
  631. /// <summary>
  632. /// Determines whether the specified stream is H264.
  633. /// </summary>
  634. /// <param name="stream">The stream.</param>
  635. /// <returns><c>true</c> if the specified stream is H264; otherwise, <c>false</c>.</returns>
  636. protected bool IsH264(MediaStream stream)
  637. {
  638. var codec = stream.Codec ?? string.Empty;
  639. return codec.IndexOf("264", StringComparison.OrdinalIgnoreCase) != -1 ||
  640. codec.IndexOf("avc", StringComparison.OrdinalIgnoreCase) != -1;
  641. }
  642. /// <summary>
  643. /// If we're going to put a fixed size on the command line, this will calculate it
  644. /// </summary>
  645. /// <param name="state">The state.</param>
  646. /// <param name="outputVideoCodec">The output video codec.</param>
  647. /// <param name="allowTimeStampCopy">if set to <c>true</c> [allow time stamp copy].</param>
  648. /// <returns>System.String.</returns>
  649. protected string GetOutputSizeParam(EncodingJob state,
  650. string outputVideoCodec,
  651. bool allowTimeStampCopy = true)
  652. {
  653. // http://sonnati.wordpress.com/2012/10/19/ffmpeg-the-swiss-army-knife-of-internet-streaming-part-vi/
  654. var request = state.Options;
  655. var filters = new List<string>();
  656. if (state.DeInterlace)
  657. {
  658. filters.Add("yadif=0:-1:0");
  659. }
  660. // If fixed dimensions were supplied
  661. if (request.Width.HasValue && request.Height.HasValue)
  662. {
  663. var widthParam = request.Width.Value.ToString(UsCulture);
  664. var heightParam = request.Height.Value.ToString(UsCulture);
  665. filters.Add(string.Format("scale=trunc({0}/2)*2:trunc({1}/2)*2", widthParam, heightParam));
  666. }
  667. // 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
  668. else if (request.MaxWidth.HasValue && request.MaxHeight.HasValue)
  669. {
  670. var maxWidthParam = request.MaxWidth.Value.ToString(UsCulture);
  671. var maxHeightParam = request.MaxHeight.Value.ToString(UsCulture);
  672. 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));
  673. }
  674. // If a fixed width was requested
  675. else if (request.Width.HasValue)
  676. {
  677. var widthParam = request.Width.Value.ToString(UsCulture);
  678. filters.Add(string.Format("scale={0}:trunc(ow/a/2)*2", widthParam));
  679. }
  680. // If a fixed height was requested
  681. else if (request.Height.HasValue)
  682. {
  683. var heightParam = request.Height.Value.ToString(UsCulture);
  684. filters.Add(string.Format("scale=trunc(oh*a/2)*2:{0}", heightParam));
  685. }
  686. // If a max width was requested
  687. else if (request.MaxWidth.HasValue)
  688. {
  689. var maxWidthParam = request.MaxWidth.Value.ToString(UsCulture);
  690. filters.Add(string.Format("scale=min(iw\\,{0}):trunc(ow/dar/2)*2", maxWidthParam));
  691. }
  692. // If a max height was requested
  693. else if (request.MaxHeight.HasValue)
  694. {
  695. var maxHeightParam = request.MaxHeight.Value.ToString(UsCulture);
  696. filters.Add(string.Format("scale=trunc(oh*a/2)*2:min(ih\\,{0})", maxHeightParam));
  697. }
  698. var output = string.Empty;
  699. if (state.SubtitleStream != null && state.SubtitleStream.IsTextSubtitleStream)
  700. {
  701. var subParam = GetTextSubtitleParam(state);
  702. filters.Add(subParam);
  703. if (allowTimeStampCopy)
  704. {
  705. output += " -copyts";
  706. }
  707. }
  708. if (filters.Count > 0)
  709. {
  710. output += string.Format(" -vf \"{0}\"", string.Join(",", filters.ToArray()));
  711. }
  712. return output;
  713. }
  714. /// <summary>
  715. /// Gets the text subtitle param.
  716. /// </summary>
  717. /// <param name="state">The state.</param>
  718. /// <returns>System.String.</returns>
  719. protected string GetTextSubtitleParam(EncodingJob state)
  720. {
  721. var seconds = Math.Round(TimeSpan.FromTicks(state.Options.StartTimeTicks ?? 0).TotalSeconds);
  722. if (state.SubtitleStream.IsExternal)
  723. {
  724. var subtitlePath = state.SubtitleStream.Path;
  725. var charsetParam = string.Empty;
  726. if (!string.IsNullOrEmpty(state.SubtitleStream.Language))
  727. {
  728. var charenc = SubtitleEncoder.GetSubtitleFileCharacterSet(subtitlePath, state.MediaSource.Protocol, CancellationToken.None).Result;
  729. if (!string.IsNullOrEmpty(charenc))
  730. {
  731. charsetParam = ":charenc=" + charenc;
  732. }
  733. }
  734. // TODO: Perhaps also use original_size=1920x800 ??
  735. return string.Format("subtitles=filename='{0}'{1},setpts=PTS -{2}/TB",
  736. subtitlePath.Replace('\\', '/').Replace(":/", "\\:/"),
  737. charsetParam,
  738. seconds.ToString(UsCulture));
  739. }
  740. return string.Format("subtitles='{0}:si={1}',setpts=PTS -{2}/TB",
  741. state.MediaPath.Replace('\\', '/').Replace(":/", "\\:/"),
  742. state.InternalSubtitleStreamOffset.ToString(UsCulture),
  743. seconds.ToString(UsCulture));
  744. }
  745. protected string GetAudioFilterParam(EncodingJob state, bool isHls)
  746. {
  747. var volParam = string.Empty;
  748. var audioSampleRate = string.Empty;
  749. var channels = state.OutputAudioChannels;
  750. // Boost volume to 200% when downsampling from 6ch to 2ch
  751. if (channels.HasValue && channels.Value <= 2)
  752. {
  753. if (state.AudioStream != null && state.AudioStream.Channels.HasValue && state.AudioStream.Channels.Value > 5)
  754. {
  755. volParam = ",volume=" + GetEncodingOptions().DownMixAudioBoost.ToString(UsCulture);
  756. }
  757. }
  758. if (state.OutputAudioSampleRate.HasValue)
  759. {
  760. audioSampleRate = state.OutputAudioSampleRate.Value + ":";
  761. }
  762. var adelay = isHls ? "adelay=1," : string.Empty;
  763. var pts = string.Empty;
  764. if (state.SubtitleStream != null && state.SubtitleStream.IsTextSubtitleStream)
  765. {
  766. var seconds = TimeSpan.FromTicks(state.Options.StartTimeTicks ?? 0).TotalSeconds;
  767. pts = string.Format(",asetpts=PTS-{0}/TB", Math.Round(seconds).ToString(UsCulture));
  768. }
  769. return string.Format("-af \"{0}aresample={1}async={4}{2}{3}\"",
  770. adelay,
  771. audioSampleRate,
  772. volParam,
  773. pts,
  774. state.OutputAudioSync);
  775. }
  776. }
  777. }