BaseEncoder.cs 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132
  1. using MediaBrowser.Common.Configuration;
  2. using MediaBrowser.Controller.Configuration;
  3. using MediaBrowser.Controller.Library;
  4. using MediaBrowser.Controller.MediaEncoding;
  5. using MediaBrowser.Controller.Session;
  6. using MediaBrowser.Model.Configuration;
  7. using MediaBrowser.Model.Dto;
  8. using MediaBrowser.Model.Entities;
  9. using MediaBrowser.Model.IO;
  10. using MediaBrowser.Model.Logging;
  11. using MediaBrowser.Model.MediaInfo;
  12. using System;
  13. using System.Collections.Generic;
  14. using System.Diagnostics;
  15. using System.Globalization;
  16. using System.IO;
  17. using System.Text;
  18. using System.Threading;
  19. using System.Threading.Tasks;
  20. using CommonIO;
  21. using MediaBrowser.Model.Dlna;
  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 = await GetCommandLineArguments(encodingJob).ConfigureAwait(false);
  67. var process = new Process
  68. {
  69. StartInfo = new ProcessStartInfo
  70. {
  71. CreateNoWindow = true,
  72. UseShellExecute = false,
  73. // Must consume both stdout and stderr or deadlocks may occur
  74. //RedirectStandardOutput = true,
  75. RedirectStandardError = true,
  76. RedirectStandardInput = true,
  77. FileName = MediaEncoder.EncoderPath,
  78. Arguments = commandLineArgs,
  79. WindowStyle = ProcessWindowStyle.Hidden,
  80. ErrorDialog = false
  81. },
  82. EnableRaisingEvents = true
  83. };
  84. var workingDirectory = GetWorkingDirectory(options);
  85. if (!string.IsNullOrWhiteSpace(workingDirectory))
  86. {
  87. process.StartInfo.WorkingDirectory = workingDirectory;
  88. }
  89. OnTranscodeBeginning(encodingJob);
  90. var commandLineLogMessage = process.StartInfo.FileName + " " + process.StartInfo.Arguments;
  91. Logger.Info(commandLineLogMessage);
  92. var logFilePath = Path.Combine(ConfigurationManager.CommonApplicationPaths.LogDirectoryPath, "transcode-" + Guid.NewGuid() + ".txt");
  93. FileSystem.CreateDirectory(Path.GetDirectoryName(logFilePath));
  94. // FFMpeg writes debug/error info to stderr. This is useful when debugging so let's put it in the log directory.
  95. encodingJob.LogFileStream = FileSystem.GetFileStream(logFilePath, FileMode.Create, FileAccess.Write, FileShare.Read, true);
  96. var commandLineLogMessageBytes = Encoding.UTF8.GetBytes(commandLineLogMessage + Environment.NewLine + Environment.NewLine);
  97. await encodingJob.LogFileStream.WriteAsync(commandLineLogMessageBytes, 0, commandLineLogMessageBytes.Length, cancellationToken).ConfigureAwait(false);
  98. process.Exited += (sender, args) => OnFfMpegProcessExited(process, encodingJob);
  99. try
  100. {
  101. process.Start();
  102. }
  103. catch (Exception ex)
  104. {
  105. Logger.ErrorException("Error starting ffmpeg", ex);
  106. OnTranscodeFailedToStart(encodingJob.OutputFilePath, encodingJob);
  107. throw;
  108. }
  109. cancellationToken.Register(() => Cancel(process, encodingJob));
  110. // MUST read both stdout and stderr asynchronously or a deadlock may occurr
  111. //process.BeginOutputReadLine();
  112. // Important - don't await the log task or we won't be able to kill ffmpeg when the user stops playback
  113. new JobLogger(Logger).StartStreamingLog(encodingJob, process.StandardError.BaseStream, encodingJob.LogFileStream);
  114. // Wait for the file to exist before proceeeding
  115. while (!FileSystem.FileExists(encodingJob.OutputFilePath) && !encodingJob.HasExited)
  116. {
  117. await Task.Delay(100, cancellationToken).ConfigureAwait(false);
  118. }
  119. return encodingJob;
  120. }
  121. private void Cancel(Process process, EncodingJob job)
  122. {
  123. Logger.Info("Killing ffmpeg process for {0}", job.OutputFilePath);
  124. //process.Kill();
  125. process.StandardInput.WriteLine("q");
  126. job.IsCancelled = true;
  127. }
  128. /// <summary>
  129. /// Processes the exited.
  130. /// </summary>
  131. /// <param name="process">The process.</param>
  132. /// <param name="job">The job.</param>
  133. private void OnFfMpegProcessExited(Process process, EncodingJob job)
  134. {
  135. job.HasExited = true;
  136. Logger.Debug("Disposing stream resources");
  137. job.Dispose();
  138. var isSuccesful = false;
  139. try
  140. {
  141. var exitCode = process.ExitCode;
  142. Logger.Info("FFMpeg exited with code {0}", exitCode);
  143. isSuccesful = exitCode == 0;
  144. }
  145. catch
  146. {
  147. Logger.Error("FFMpeg exited with an error.");
  148. }
  149. if (isSuccesful && !job.IsCancelled)
  150. {
  151. job.TaskCompletionSource.TrySetResult(true);
  152. }
  153. else if (job.IsCancelled)
  154. {
  155. try
  156. {
  157. DeleteFiles(job);
  158. }
  159. catch
  160. {
  161. }
  162. try
  163. {
  164. job.TaskCompletionSource.TrySetException(new OperationCanceledException());
  165. }
  166. catch
  167. {
  168. }
  169. }
  170. else
  171. {
  172. try
  173. {
  174. DeleteFiles(job);
  175. }
  176. catch
  177. {
  178. }
  179. try
  180. {
  181. job.TaskCompletionSource.TrySetException(new ApplicationException("Encoding failed"));
  182. }
  183. catch
  184. {
  185. }
  186. }
  187. // This causes on exited to be called twice:
  188. //try
  189. //{
  190. // // Dispose the process
  191. // process.Dispose();
  192. //}
  193. //catch (Exception ex)
  194. //{
  195. // Logger.ErrorException("Error disposing ffmpeg.", ex);
  196. //}
  197. }
  198. protected virtual void DeleteFiles(EncodingJob job)
  199. {
  200. FileSystem.DeleteFile(job.OutputFilePath);
  201. }
  202. private void OnTranscodeBeginning(EncodingJob job)
  203. {
  204. job.ReportTranscodingProgress(null, null, null, null);
  205. }
  206. private void OnTranscodeFailedToStart(string path, EncodingJob job)
  207. {
  208. if (!string.IsNullOrWhiteSpace(job.Options.DeviceId))
  209. {
  210. SessionManager.ClearTranscodingInfo(job.Options.DeviceId);
  211. }
  212. }
  213. protected abstract bool IsVideoEncoder { get; }
  214. protected virtual string GetWorkingDirectory(EncodingJobOptions options)
  215. {
  216. return null;
  217. }
  218. protected EncodingOptions GetEncodingOptions()
  219. {
  220. return ConfigurationManager.GetConfiguration<EncodingOptions>("encoding");
  221. }
  222. protected abstract Task<string> GetCommandLineArguments(EncodingJob job);
  223. private string GetOutputFilePath(EncodingJob state)
  224. {
  225. var folder = string.IsNullOrWhiteSpace(state.Options.OutputDirectory) ?
  226. ConfigurationManager.ApplicationPaths.TranscodingTempPath :
  227. state.Options.OutputDirectory;
  228. var outputFileExtension = GetOutputFileExtension(state);
  229. var filename = state.Id + (outputFileExtension ?? string.Empty).ToLower();
  230. return Path.Combine(folder, filename);
  231. }
  232. protected virtual string GetOutputFileExtension(EncodingJob state)
  233. {
  234. if (!string.IsNullOrWhiteSpace(state.Options.OutputContainer))
  235. {
  236. return "." + state.Options.OutputContainer;
  237. }
  238. return null;
  239. }
  240. /// <summary>
  241. /// Gets the number of threads.
  242. /// </summary>
  243. /// <returns>System.Int32.</returns>
  244. protected int GetNumberOfThreads(EncodingJob job, bool isWebm)
  245. {
  246. return job.Options.CpuCoreLimit ?? 0;
  247. }
  248. protected string GetInputModifier(EncodingJob state, bool genPts = true)
  249. {
  250. var inputModifier = string.Empty;
  251. var probeSize = GetProbeSizeArgument(state);
  252. inputModifier += " " + probeSize;
  253. inputModifier = inputModifier.Trim();
  254. var userAgentParam = GetUserAgentParam(state);
  255. if (!string.IsNullOrWhiteSpace(userAgentParam))
  256. {
  257. inputModifier += " " + userAgentParam;
  258. }
  259. inputModifier = inputModifier.Trim();
  260. inputModifier += " " + GetFastSeekCommandLineParameter(state.Options);
  261. inputModifier = inputModifier.Trim();
  262. if (state.IsVideoRequest && genPts)
  263. {
  264. inputModifier += " -fflags +genpts";
  265. }
  266. if (!string.IsNullOrEmpty(state.InputAudioSync))
  267. {
  268. inputModifier += " -async " + state.InputAudioSync;
  269. }
  270. if (!string.IsNullOrEmpty(state.InputVideoSync))
  271. {
  272. inputModifier += " -vsync " + state.InputVideoSync;
  273. }
  274. if (state.ReadInputAtNativeFramerate)
  275. {
  276. inputModifier += " -re";
  277. }
  278. var videoDecoder = GetVideoDecoder(state);
  279. if (!string.IsNullOrWhiteSpace(videoDecoder))
  280. {
  281. inputModifier += " " + videoDecoder;
  282. }
  283. //if (state.IsVideoRequest)
  284. //{
  285. // if (string.Equals(state.OutputContainer, "mkv", StringComparison.OrdinalIgnoreCase))
  286. // {
  287. // //inputModifier += " -noaccurate_seek";
  288. // }
  289. //}
  290. return inputModifier;
  291. }
  292. /// <summary>
  293. /// Gets the name of the output video codec
  294. /// </summary>
  295. /// <param name="state">The state.</param>
  296. /// <returns>System.String.</returns>
  297. protected string GetVideoDecoder(EncodingJob state)
  298. {
  299. if (string.Equals(state.OutputVideoCodec, "copy", StringComparison.OrdinalIgnoreCase))
  300. {
  301. return null;
  302. }
  303. // Only use alternative encoders for video files.
  304. // When using concat with folder rips, if the mfx session fails to initialize, ffmpeg will be stuck retrying and will not exit gracefully
  305. // Since transcoding of folder rips is expiremental anyway, it's not worth adding additional variables such as this.
  306. if (state.VideoType != VideoType.VideoFile)
  307. {
  308. return null;
  309. }
  310. if (state.VideoStream != null && !string.IsNullOrWhiteSpace(state.VideoStream.Codec))
  311. {
  312. if (string.Equals(GetEncodingOptions().HardwareAccelerationType, "qsv", StringComparison.OrdinalIgnoreCase))
  313. {
  314. switch (state.MediaSource.VideoStream.Codec.ToLower())
  315. {
  316. case "avc":
  317. case "h264":
  318. if (MediaEncoder.SupportsDecoder("h264_qsv"))
  319. {
  320. // Seeing stalls and failures with decoding. Not worth it compared to encoding.
  321. return "-c:v h264_qsv ";
  322. }
  323. break;
  324. case "mpeg2video":
  325. if (MediaEncoder.SupportsDecoder("mpeg2_qsv"))
  326. {
  327. return "-c:v mpeg2_qsv ";
  328. }
  329. break;
  330. case "vc1":
  331. if (MediaEncoder.SupportsDecoder("vc1_qsv"))
  332. {
  333. return "-c:v vc1_qsv ";
  334. }
  335. break;
  336. }
  337. }
  338. }
  339. // leave blank so ffmpeg will decide
  340. return null;
  341. }
  342. private string GetUserAgentParam(EncodingJob state)
  343. {
  344. string useragent = null;
  345. state.RemoteHttpHeaders.TryGetValue("User-Agent", out useragent);
  346. if (!string.IsNullOrWhiteSpace(useragent))
  347. {
  348. return "-user-agent \"" + useragent + "\"";
  349. }
  350. return string.Empty;
  351. }
  352. /// <summary>
  353. /// Gets the probe size argument.
  354. /// </summary>
  355. /// <param name="state">The state.</param>
  356. /// <returns>System.String.</returns>
  357. private string GetProbeSizeArgument(EncodingJob state)
  358. {
  359. if (state.PlayableStreamFileNames.Count > 0)
  360. {
  361. return MediaEncoder.GetProbeSizeArgument(state.PlayableStreamFileNames.ToArray(), state.InputProtocol);
  362. }
  363. return MediaEncoder.GetProbeSizeArgument(new[] { state.MediaPath }, state.InputProtocol);
  364. }
  365. /// <summary>
  366. /// Gets the fast seek command line parameter.
  367. /// </summary>
  368. /// <param name="request">The request.</param>
  369. /// <returns>System.String.</returns>
  370. /// <value>The fast seek command line parameter.</value>
  371. protected string GetFastSeekCommandLineParameter(EncodingJobOptions request)
  372. {
  373. var time = request.StartTimeTicks ?? 0;
  374. if (time > 0)
  375. {
  376. return string.Format("-ss {0}", MediaEncoder.GetTimeParameter(time));
  377. }
  378. return string.Empty;
  379. }
  380. /// <summary>
  381. /// Gets the input argument.
  382. /// </summary>
  383. /// <param name="state">The state.</param>
  384. /// <returns>System.String.</returns>
  385. protected string GetInputArgument(EncodingJob state)
  386. {
  387. var arg = string.Format("-i {0}", GetInputPathArgument(state));
  388. if (state.SubtitleStream != null && state.Options.SubtitleMethod == SubtitleDeliveryMethod.Encode)
  389. {
  390. if (state.SubtitleStream.IsExternal && !state.SubtitleStream.IsTextSubtitleStream)
  391. {
  392. if (state.VideoStream != null && state.VideoStream.Width.HasValue)
  393. {
  394. // This is hacky but not sure how to get the exact subtitle resolution
  395. double height = state.VideoStream.Width.Value;
  396. height /= 16;
  397. height *= 9;
  398. arg += string.Format(" -canvas_size {0}:{1}", state.VideoStream.Width.Value.ToString(CultureInfo.InvariantCulture), Convert.ToInt32(height).ToString(CultureInfo.InvariantCulture));
  399. }
  400. arg += " -i \"" + state.SubtitleStream.Path + "\"";
  401. }
  402. }
  403. if (state.IsVideoRequest)
  404. {
  405. var encodingOptions = GetEncodingOptions();
  406. var videoEncoder = EncodingJobFactory.GetVideoEncoder(MediaEncoder, state, encodingOptions);
  407. if (videoEncoder.IndexOf("vaapi", StringComparison.OrdinalIgnoreCase) != -1)
  408. {
  409. arg = "-hwaccel vaapi -hwaccel_output_format yuv420p -vaapi_device " + encodingOptions.VaapiDevice + " " + arg;
  410. }
  411. }
  412. return arg.Trim();
  413. }
  414. private string GetInputPathArgument(EncodingJob state)
  415. {
  416. var protocol = state.InputProtocol;
  417. var mediaPath = state.MediaPath ?? string.Empty;
  418. var inputPath = new[] { mediaPath };
  419. if (state.IsInputVideo)
  420. {
  421. if (!(state.VideoType == VideoType.Iso && state.IsoMount == null))
  422. {
  423. inputPath = MediaEncoderHelpers.GetInputArgument(FileSystem, mediaPath, state.InputProtocol, state.IsoMount, state.PlayableStreamFileNames);
  424. }
  425. }
  426. return MediaEncoder.GetInputArgument(inputPath, protocol);
  427. }
  428. private async Task AcquireResources(EncodingJob state, CancellationToken cancellationToken)
  429. {
  430. if (state.VideoType == VideoType.Iso && state.IsoType.HasValue && IsoManager.CanMount(state.MediaPath))
  431. {
  432. state.IsoMount = await IsoManager.Mount(state.MediaPath, cancellationToken).ConfigureAwait(false);
  433. }
  434. if (state.MediaSource.RequiresOpening && string.IsNullOrWhiteSpace(state.LiveStreamId))
  435. {
  436. var liveStreamResponse = await MediaSourceManager.OpenLiveStream(new LiveStreamRequest
  437. {
  438. OpenToken = state.MediaSource.OpenToken
  439. }, false, cancellationToken).ConfigureAwait(false);
  440. AttachMediaSourceInfo(state, liveStreamResponse.MediaSource, state.Options);
  441. if (state.IsVideoRequest)
  442. {
  443. EncodingJobFactory.TryStreamCopy(state, state.Options);
  444. }
  445. }
  446. if (state.MediaSource.BufferMs.HasValue)
  447. {
  448. await Task.Delay(state.MediaSource.BufferMs.Value, cancellationToken).ConfigureAwait(false);
  449. }
  450. }
  451. private void AttachMediaSourceInfo(EncodingJob state,
  452. MediaSourceInfo mediaSource,
  453. EncodingJobOptions videoRequest)
  454. {
  455. EncodingJobFactory.AttachMediaSourceInfo(state, mediaSource, videoRequest);
  456. }
  457. /// <summary>
  458. /// Gets the internal graphical subtitle param.
  459. /// </summary>
  460. /// <param name="state">The state.</param>
  461. /// <param name="outputVideoCodec">The output video codec.</param>
  462. /// <returns>System.String.</returns>
  463. protected async Task<string> GetGraphicalSubtitleParam(EncodingJob state, string outputVideoCodec)
  464. {
  465. var outputSizeParam = string.Empty;
  466. var request = state.Options;
  467. // Add resolution params, if specified
  468. if (request.Width.HasValue || request.Height.HasValue || request.MaxHeight.HasValue || request.MaxWidth.HasValue)
  469. {
  470. outputSizeParam = await GetOutputSizeParam(state, outputVideoCodec).ConfigureAwait(false);
  471. outputSizeParam = outputSizeParam.TrimEnd('"');
  472. if (string.Equals(outputVideoCodec, "h264_vaapi", StringComparison.OrdinalIgnoreCase))
  473. {
  474. outputSizeParam = "," + outputSizeParam.Substring(outputSizeParam.IndexOf("format", StringComparison.OrdinalIgnoreCase));
  475. }
  476. else
  477. {
  478. outputSizeParam = "," + outputSizeParam.Substring(outputSizeParam.IndexOf("scale", StringComparison.OrdinalIgnoreCase));
  479. }
  480. }
  481. if (string.Equals(outputVideoCodec, "h264_vaapi", StringComparison.OrdinalIgnoreCase) && outputSizeParam.Length == 0)
  482. {
  483. outputSizeParam = ",format=nv12|vaapi,hwupload";
  484. }
  485. var videoSizeParam = string.Empty;
  486. if (state.VideoStream != null && state.VideoStream.Width.HasValue && state.VideoStream.Height.HasValue)
  487. {
  488. videoSizeParam = string.Format(",scale={0}:{1}", state.VideoStream.Width.Value.ToString(UsCulture), state.VideoStream.Height.Value.ToString(UsCulture));
  489. }
  490. var mapPrefix = state.SubtitleStream.IsExternal ?
  491. 1 :
  492. 0;
  493. var subtitleStreamIndex = state.SubtitleStream.IsExternal
  494. ? 0
  495. : state.SubtitleStream.Index;
  496. return string.Format(" -filter_complex \"[{0}:{1}]format=yuva444p{4},lut=u=128:v=128:y=gammaval(.3)[sub] ; [0:{2}] [sub] overlay{3}\"",
  497. mapPrefix.ToString(UsCulture),
  498. subtitleStreamIndex.ToString(UsCulture),
  499. state.VideoStream.Index.ToString(UsCulture),
  500. outputSizeParam,
  501. videoSizeParam);
  502. }
  503. /// <summary>
  504. /// Gets the video bitrate to specify on the command line
  505. /// </summary>
  506. /// <param name="state">The state.</param>
  507. /// <param name="videoEncoder">The video codec.</param>
  508. /// <returns>System.String.</returns>
  509. protected string GetVideoQualityParam(EncodingJob state, string videoEncoder)
  510. {
  511. var param = string.Empty;
  512. var isVc1 = state.VideoStream != null &&
  513. string.Equals(state.VideoStream.Codec, "vc1", StringComparison.OrdinalIgnoreCase);
  514. if (string.Equals(videoEncoder, "libx264", StringComparison.OrdinalIgnoreCase))
  515. {
  516. param = "-preset superfast";
  517. param += " -crf 23";
  518. }
  519. else if (string.Equals(videoEncoder, "libx265", StringComparison.OrdinalIgnoreCase))
  520. {
  521. param = "-preset fast";
  522. param += " -crf 28";
  523. }
  524. // h264 (h264_qsv)
  525. else if (string.Equals(videoEncoder, "h264_qsv", StringComparison.OrdinalIgnoreCase))
  526. {
  527. param = "-preset 7 -look_ahead 0";
  528. }
  529. // h264 (h264_nvenc)
  530. else if (string.Equals(videoEncoder, "h264_nvenc", StringComparison.OrdinalIgnoreCase))
  531. {
  532. param = "-preset llhq";
  533. }
  534. // webm
  535. else if (string.Equals(videoEncoder, "libvpx", StringComparison.OrdinalIgnoreCase))
  536. {
  537. // Values 0-3, 0 being highest quality but slower
  538. var profileScore = 0;
  539. string crf;
  540. var qmin = "0";
  541. var qmax = "50";
  542. crf = "10";
  543. if (isVc1)
  544. {
  545. profileScore++;
  546. }
  547. // Max of 2
  548. profileScore = Math.Min(profileScore, 2);
  549. // http://www.webmproject.org/docs/encoder-parameters/
  550. param = string.Format("-speed 16 -quality good -profile:v {0} -slices 8 -crf {1} -qmin {2} -qmax {3}",
  551. profileScore.ToString(UsCulture),
  552. crf,
  553. qmin,
  554. qmax);
  555. }
  556. else if (string.Equals(videoEncoder, "mpeg4", StringComparison.OrdinalIgnoreCase))
  557. {
  558. param = "-mbd rd -flags +mv4+aic -trellis 2 -cmp 2 -subcmp 2 -bf 2";
  559. }
  560. // asf/wmv
  561. else if (string.Equals(videoEncoder, "wmv2", StringComparison.OrdinalIgnoreCase))
  562. {
  563. param = "-qmin 2";
  564. }
  565. else if (string.Equals(videoEncoder, "msmpeg4", StringComparison.OrdinalIgnoreCase))
  566. {
  567. param = "-mbd 2";
  568. }
  569. param += GetVideoBitrateParam(state, videoEncoder);
  570. var framerate = GetFramerateParam(state);
  571. if (framerate.HasValue)
  572. {
  573. param += string.Format(" -r {0}", framerate.Value.ToString(UsCulture));
  574. }
  575. if (!string.IsNullOrEmpty(state.OutputVideoSync))
  576. {
  577. param += " -vsync " + state.OutputVideoSync;
  578. }
  579. if (!string.IsNullOrEmpty(state.Options.Profile))
  580. {
  581. if (!string.Equals(videoEncoder, "h264_omx", StringComparison.OrdinalIgnoreCase) &&
  582. !string.Equals(videoEncoder, "h264_vaapi", StringComparison.OrdinalIgnoreCase))
  583. {
  584. // not supported by h264_omx
  585. param += " -profile:v " + state.Options.Profile;
  586. }
  587. }
  588. var levelString = state.Options.Level.HasValue ? state.Options.Level.Value.ToString(CultureInfo.InvariantCulture) : null;
  589. if (!string.IsNullOrEmpty(levelString))
  590. {
  591. levelString = NormalizeTranscodingLevel(state.OutputVideoCodec, levelString);
  592. // h264_qsv and h264_nvenc expect levels to be expressed as a decimal. libx264 supports decimal and non-decimal format
  593. if (string.Equals(videoEncoder, "h264_qsv", StringComparison.OrdinalIgnoreCase) ||
  594. string.Equals(videoEncoder, "h264_nvenc", StringComparison.OrdinalIgnoreCase))
  595. {
  596. switch (levelString)
  597. {
  598. case "30":
  599. param += " -level 3";
  600. break;
  601. case "31":
  602. param += " -level 3.1";
  603. break;
  604. case "32":
  605. param += " -level 3.2";
  606. break;
  607. case "40":
  608. param += " -level 4";
  609. break;
  610. case "41":
  611. param += " -level 4.1";
  612. break;
  613. case "42":
  614. param += " -level 4.2";
  615. break;
  616. case "50":
  617. param += " -level 5";
  618. break;
  619. case "51":
  620. param += " -level 5.1";
  621. break;
  622. case "52":
  623. param += " -level 5.2";
  624. break;
  625. default:
  626. param += " -level " + levelString;
  627. break;
  628. }
  629. }
  630. else if (!string.Equals(videoEncoder, "h264_omx", StringComparison.OrdinalIgnoreCase))
  631. {
  632. param += " -level " + levelString;
  633. }
  634. }
  635. if (!string.Equals(videoEncoder, "h264_omx", StringComparison.OrdinalIgnoreCase) &&
  636. !string.Equals(videoEncoder, "h264_qsv", StringComparison.OrdinalIgnoreCase) &&
  637. !string.Equals(videoEncoder, "h264_nvenc", StringComparison.OrdinalIgnoreCase) &&
  638. !string.Equals(videoEncoder, "h264_vaapi", StringComparison.OrdinalIgnoreCase))
  639. {
  640. param = "-pix_fmt yuv420p " + param;
  641. }
  642. return param;
  643. }
  644. private string NormalizeTranscodingLevel(string videoCodec, string level)
  645. {
  646. double requestLevel;
  647. // Clients may direct play higher than level 41, but there's no reason to transcode higher
  648. if (double.TryParse(level, NumberStyles.Any, UsCulture, out requestLevel))
  649. {
  650. if (string.Equals(videoCodec, "h264", StringComparison.OrdinalIgnoreCase))
  651. {
  652. if (requestLevel > 41)
  653. {
  654. return "41";
  655. }
  656. }
  657. }
  658. return level;
  659. }
  660. protected string GetVideoBitrateParam(EncodingJob state, string videoCodec)
  661. {
  662. var bitrate = state.OutputVideoBitrate;
  663. if (bitrate.HasValue)
  664. {
  665. if (string.Equals(videoCodec, "libvpx", StringComparison.OrdinalIgnoreCase))
  666. {
  667. // With vpx when crf is used, b:v becomes a max rate
  668. // 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.
  669. return string.Format(" -maxrate:v {0} -bufsize:v ({0}*2) -b:v {0}", bitrate.Value.ToString(UsCulture));
  670. }
  671. if (string.Equals(videoCodec, "msmpeg4", StringComparison.OrdinalIgnoreCase))
  672. {
  673. return string.Format(" -b:v {0}", bitrate.Value.ToString(UsCulture));
  674. }
  675. // h264
  676. return string.Format(" -b:v {0} -maxrate {0} -bufsize {1}",
  677. bitrate.Value.ToString(UsCulture),
  678. (bitrate.Value * 2).ToString(UsCulture));
  679. }
  680. return string.Empty;
  681. }
  682. protected double? GetFramerateParam(EncodingJob state)
  683. {
  684. if (state.Options != null)
  685. {
  686. if (state.Options.Framerate.HasValue)
  687. {
  688. return state.Options.Framerate.Value;
  689. }
  690. var maxrate = state.Options.MaxFramerate;
  691. if (maxrate.HasValue && state.VideoStream != null)
  692. {
  693. var contentRate = state.VideoStream.AverageFrameRate ?? state.VideoStream.RealFrameRate;
  694. if (contentRate.HasValue && contentRate.Value > maxrate.Value)
  695. {
  696. return maxrate;
  697. }
  698. }
  699. }
  700. return null;
  701. }
  702. /// <summary>
  703. /// Gets the map args.
  704. /// </summary>
  705. /// <param name="state">The state.</param>
  706. /// <returns>System.String.</returns>
  707. protected virtual string GetMapArgs(EncodingJob state)
  708. {
  709. // If we don't have known media info
  710. // If input is video, use -sn to drop subtitles
  711. // Otherwise just return empty
  712. if (state.VideoStream == null && state.AudioStream == null)
  713. {
  714. return state.IsInputVideo ? "-sn" : string.Empty;
  715. }
  716. // We have media info, but we don't know the stream indexes
  717. if (state.VideoStream != null && state.VideoStream.Index == -1)
  718. {
  719. return "-sn";
  720. }
  721. // We have media info, but we don't know the stream indexes
  722. if (state.AudioStream != null && state.AudioStream.Index == -1)
  723. {
  724. return state.IsInputVideo ? "-sn" : string.Empty;
  725. }
  726. var args = string.Empty;
  727. if (state.VideoStream != null)
  728. {
  729. args += string.Format("-map 0:{0}", state.VideoStream.Index);
  730. }
  731. else
  732. {
  733. args += "-map -0:v";
  734. }
  735. if (state.AudioStream != null)
  736. {
  737. args += string.Format(" -map 0:{0}", state.AudioStream.Index);
  738. }
  739. else
  740. {
  741. args += " -map -0:a";
  742. }
  743. if (state.SubtitleStream == null || state.Options.SubtitleMethod == SubtitleDeliveryMethod.Hls)
  744. {
  745. args += " -map -0:s";
  746. }
  747. else if (state.SubtitleStream.IsExternal && !state.SubtitleStream.IsTextSubtitleStream)
  748. {
  749. args += " -map 1:0 -sn";
  750. }
  751. return args;
  752. }
  753. /// <summary>
  754. /// Determines whether the specified stream is H264.
  755. /// </summary>
  756. /// <param name="stream">The stream.</param>
  757. /// <returns><c>true</c> if the specified stream is H264; otherwise, <c>false</c>.</returns>
  758. protected bool IsH264(MediaStream stream)
  759. {
  760. var codec = stream.Codec ?? string.Empty;
  761. return codec.IndexOf("264", StringComparison.OrdinalIgnoreCase) != -1 ||
  762. codec.IndexOf("avc", StringComparison.OrdinalIgnoreCase) != -1;
  763. }
  764. /// <summary>
  765. /// If we're going to put a fixed size on the command line, this will calculate it
  766. /// </summary>
  767. /// <param name="state">The state.</param>
  768. /// <param name="outputVideoCodec">The output video codec.</param>
  769. /// <param name="allowTimeStampCopy">if set to <c>true</c> [allow time stamp copy].</param>
  770. /// <returns>System.String.</returns>
  771. protected async Task<string> GetOutputSizeParam(EncodingJob state,
  772. string outputVideoCodec,
  773. bool allowTimeStampCopy = true)
  774. {
  775. // http://sonnati.wordpress.com/2012/10/19/ffmpeg-the-swiss-army-knife-of-internet-streaming-part-vi/
  776. var request = state.Options;
  777. var filters = new List<string>();
  778. if (string.Equals(outputVideoCodec, "h264_vaapi", StringComparison.OrdinalIgnoreCase))
  779. {
  780. filters.Add("format=nv12|vaapi");
  781. filters.Add("hwupload");
  782. }
  783. else if (state.DeInterlace && !string.Equals(outputVideoCodec, "h264_vaapi", StringComparison.OrdinalIgnoreCase))
  784. {
  785. filters.Add("yadif=0:-1:0");
  786. }
  787. if (string.Equals(outputVideoCodec, "h264_vaapi", StringComparison.OrdinalIgnoreCase))
  788. {
  789. // Work around vaapi's reduced scaling features
  790. var scaler = "scale_vaapi";
  791. // Given the input dimensions (inputWidth, inputHeight), determine the output dimensions
  792. // (outputWidth, outputHeight). The user may request precise output dimensions or maximum
  793. // output dimensions. Output dimensions are guaranteed to be even.
  794. decimal inputWidth = Convert.ToDecimal(state.VideoStream.Width);
  795. decimal inputHeight = Convert.ToDecimal(state.VideoStream.Height);
  796. decimal outputWidth = request.Width.HasValue ? Convert.ToDecimal(request.Width.Value) : inputWidth;
  797. decimal outputHeight = request.Height.HasValue ? Convert.ToDecimal(request.Height.Value) : inputHeight;
  798. decimal maximumWidth = request.MaxWidth.HasValue ? Convert.ToDecimal(request.MaxWidth.Value) : outputWidth;
  799. decimal maximumHeight = request.MaxHeight.HasValue ? Convert.ToDecimal(request.MaxHeight.Value) : outputHeight;
  800. if (outputWidth > maximumWidth || outputHeight > maximumHeight)
  801. {
  802. var scale = Math.Min(maximumWidth / outputWidth, maximumHeight / outputHeight);
  803. outputWidth = Math.Min(maximumWidth, Math.Truncate(outputWidth * scale));
  804. outputHeight = Math.Min(maximumHeight, Math.Truncate(outputHeight * scale));
  805. }
  806. outputWidth = 2 * Math.Truncate(outputWidth / 2);
  807. outputHeight = 2 * Math.Truncate(outputHeight / 2);
  808. if (outputWidth != inputWidth || outputHeight != inputHeight)
  809. {
  810. filters.Add(string.Format("{0}=w={1}:h={2}", scaler, outputWidth.ToString(UsCulture), outputHeight.ToString(UsCulture)));
  811. }
  812. }
  813. else
  814. {
  815. // If fixed dimensions were supplied
  816. if (request.Width.HasValue && request.Height.HasValue)
  817. {
  818. var widthParam = request.Width.Value.ToString(UsCulture);
  819. var heightParam = request.Height.Value.ToString(UsCulture);
  820. filters.Add(string.Format("scale=trunc({0}/2)*2:trunc({1}/2)*2", widthParam, heightParam));
  821. }
  822. // 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
  823. else if (request.MaxWidth.HasValue && request.MaxHeight.HasValue)
  824. {
  825. var maxWidthParam = request.MaxWidth.Value.ToString(UsCulture);
  826. var maxHeightParam = request.MaxHeight.Value.ToString(UsCulture);
  827. 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));
  828. }
  829. // If a fixed width was requested
  830. else if (request.Width.HasValue)
  831. {
  832. var widthParam = request.Width.Value.ToString(UsCulture);
  833. filters.Add(string.Format("scale={0}:trunc(ow/a/2)*2", widthParam));
  834. }
  835. // If a fixed height was requested
  836. else if (request.Height.HasValue)
  837. {
  838. var heightParam = request.Height.Value.ToString(UsCulture);
  839. filters.Add(string.Format("scale=trunc(oh*a/2)*2:{0}", heightParam));
  840. }
  841. // If a max width was requested
  842. else if (request.MaxWidth.HasValue)
  843. {
  844. var maxWidthParam = request.MaxWidth.Value.ToString(UsCulture);
  845. filters.Add(string.Format("scale=trunc(min(max(iw\\,ih*dar)\\,{0})/2)*2:trunc(ow/dar/2)*2", maxWidthParam));
  846. }
  847. // If a max height was requested
  848. else if (request.MaxHeight.HasValue)
  849. {
  850. var maxHeightParam = request.MaxHeight.Value.ToString(UsCulture);
  851. filters.Add(string.Format("scale=trunc(oh*a/2)*2:min(max(iw/dar\\,ih)\\,{0})", maxHeightParam));
  852. }
  853. }
  854. var output = string.Empty;
  855. if (state.SubtitleStream != null && state.SubtitleStream.IsTextSubtitleStream && state.Options.SubtitleMethod == SubtitleDeliveryMethod.Encode)
  856. {
  857. var subParam = await GetTextSubtitleParam(state).ConfigureAwait(false);
  858. filters.Add(subParam);
  859. if (allowTimeStampCopy)
  860. {
  861. output += " -copyts";
  862. }
  863. }
  864. if (filters.Count > 0)
  865. {
  866. output += string.Format(" -vf \"{0}\"", string.Join(",", filters.ToArray()));
  867. }
  868. return output;
  869. }
  870. /// <summary>
  871. /// Gets the text subtitle param.
  872. /// </summary>
  873. /// <param name="state">The state.</param>
  874. /// <returns>System.String.</returns>
  875. protected async Task<string> GetTextSubtitleParam(EncodingJob state)
  876. {
  877. var seconds = Math.Round(TimeSpan.FromTicks(state.Options.StartTimeTicks ?? 0).TotalSeconds);
  878. if (state.SubtitleStream.IsExternal)
  879. {
  880. var subtitlePath = state.SubtitleStream.Path;
  881. var charsetParam = string.Empty;
  882. if (!string.IsNullOrEmpty(state.SubtitleStream.Language))
  883. {
  884. var charenc = await SubtitleEncoder.GetSubtitleFileCharacterSet(subtitlePath, state.SubtitleStream.Language, state.MediaSource.Protocol, CancellationToken.None).ConfigureAwait(false);
  885. if (!string.IsNullOrEmpty(charenc))
  886. {
  887. charsetParam = ":charenc=" + charenc;
  888. }
  889. }
  890. // TODO: Perhaps also use original_size=1920x800 ??
  891. return string.Format("subtitles=filename='{0}'{1},setpts=PTS -{2}/TB",
  892. MediaEncoder.EscapeSubtitleFilterPath(subtitlePath),
  893. charsetParam,
  894. seconds.ToString(UsCulture));
  895. }
  896. var mediaPath = state.MediaPath ?? string.Empty;
  897. return string.Format("subtitles='{0}:si={1}',setpts=PTS -{2}/TB",
  898. MediaEncoder.EscapeSubtitleFilterPath(mediaPath),
  899. state.InternalSubtitleStreamOffset.ToString(UsCulture),
  900. seconds.ToString(UsCulture));
  901. }
  902. protected string GetAudioFilterParam(EncodingJob state, bool isHls)
  903. {
  904. var volParam = string.Empty;
  905. var audioSampleRate = string.Empty;
  906. var channels = state.OutputAudioChannels;
  907. // Boost volume to 200% when downsampling from 6ch to 2ch
  908. if (channels.HasValue && channels.Value <= 2)
  909. {
  910. if (state.AudioStream != null && state.AudioStream.Channels.HasValue && state.AudioStream.Channels.Value > 5 && !GetEncodingOptions().DownMixAudioBoost.Equals(1))
  911. {
  912. volParam = ",volume=" + GetEncodingOptions().DownMixAudioBoost.ToString(UsCulture);
  913. }
  914. }
  915. if (state.OutputAudioSampleRate.HasValue)
  916. {
  917. audioSampleRate = state.OutputAudioSampleRate.Value + ":";
  918. }
  919. var adelay = isHls ? "adelay=1," : string.Empty;
  920. var pts = string.Empty;
  921. if (state.SubtitleStream != null && state.SubtitleStream.IsTextSubtitleStream && state.Options.SubtitleMethod == SubtitleDeliveryMethod.Encode && !state.Options.CopyTimestamps)
  922. {
  923. var seconds = TimeSpan.FromTicks(state.Options.StartTimeTicks ?? 0).TotalSeconds;
  924. pts = string.Format(",asetpts=PTS-{0}/TB", Math.Round(seconds).ToString(UsCulture));
  925. }
  926. return string.Format("-af \"{0}aresample={1}async={4}{2}{3}\"",
  927. adelay,
  928. audioSampleRate,
  929. volParam,
  930. pts,
  931. state.OutputAudioSync);
  932. }
  933. }
  934. }