BaseEncoder.cs 43 KB

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