BaseEncoder.cs 43 KB

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