BaseEncoder.cs 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088
  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. return arg.Trim();
  404. }
  405. private string GetInputPathArgument(EncodingJob state)
  406. {
  407. var protocol = state.InputProtocol;
  408. var mediaPath = state.MediaPath ?? string.Empty;
  409. var inputPath = new[] { mediaPath };
  410. if (state.IsInputVideo)
  411. {
  412. if (!(state.VideoType == VideoType.Iso && state.IsoMount == null))
  413. {
  414. inputPath = MediaEncoderHelpers.GetInputArgument(FileSystem, mediaPath, state.InputProtocol, state.IsoMount, state.PlayableStreamFileNames);
  415. }
  416. }
  417. return MediaEncoder.GetInputArgument(inputPath, protocol);
  418. }
  419. private async Task AcquireResources(EncodingJob state, CancellationToken cancellationToken)
  420. {
  421. if (state.VideoType == VideoType.Iso && state.IsoType.HasValue && IsoManager.CanMount(state.MediaPath))
  422. {
  423. state.IsoMount = await IsoManager.Mount(state.MediaPath, cancellationToken).ConfigureAwait(false);
  424. }
  425. if (state.MediaSource.RequiresOpening && string.IsNullOrWhiteSpace(state.LiveStreamId))
  426. {
  427. var liveStreamResponse = await MediaSourceManager.OpenLiveStream(new LiveStreamRequest
  428. {
  429. OpenToken = state.MediaSource.OpenToken
  430. }, false, cancellationToken).ConfigureAwait(false);
  431. AttachMediaSourceInfo(state, liveStreamResponse.MediaSource, state.Options);
  432. if (state.IsVideoRequest)
  433. {
  434. EncodingJobFactory.TryStreamCopy(state, state.Options);
  435. }
  436. }
  437. if (state.MediaSource.BufferMs.HasValue)
  438. {
  439. await Task.Delay(state.MediaSource.BufferMs.Value, cancellationToken).ConfigureAwait(false);
  440. }
  441. }
  442. private void AttachMediaSourceInfo(EncodingJob state,
  443. MediaSourceInfo mediaSource,
  444. EncodingJobOptions videoRequest)
  445. {
  446. EncodingJobFactory.AttachMediaSourceInfo(state, mediaSource, videoRequest);
  447. }
  448. /// <summary>
  449. /// Gets the internal graphical subtitle param.
  450. /// </summary>
  451. /// <param name="state">The state.</param>
  452. /// <param name="outputVideoCodec">The output video codec.</param>
  453. /// <returns>System.String.</returns>
  454. protected async Task<string> GetGraphicalSubtitleParam(EncodingJob state, string outputVideoCodec)
  455. {
  456. var outputSizeParam = string.Empty;
  457. var request = state.Options;
  458. // Add resolution params, if specified
  459. if (request.Width.HasValue || request.Height.HasValue || request.MaxHeight.HasValue || request.MaxWidth.HasValue)
  460. {
  461. outputSizeParam = await GetOutputSizeParam(state, outputVideoCodec).ConfigureAwait(false);
  462. outputSizeParam = outputSizeParam.TrimEnd('"');
  463. outputSizeParam = "," + outputSizeParam.Substring(outputSizeParam.IndexOf("scale", StringComparison.OrdinalIgnoreCase));
  464. }
  465. var videoSizeParam = string.Empty;
  466. if (state.VideoStream != null && state.VideoStream.Width.HasValue && state.VideoStream.Height.HasValue)
  467. {
  468. videoSizeParam = string.Format(",scale={0}:{1}", state.VideoStream.Width.Value.ToString(UsCulture), state.VideoStream.Height.Value.ToString(UsCulture));
  469. }
  470. var mapPrefix = state.SubtitleStream.IsExternal ?
  471. 1 :
  472. 0;
  473. var subtitleStreamIndex = state.SubtitleStream.IsExternal
  474. ? 0
  475. : state.SubtitleStream.Index;
  476. return string.Format(" -filter_complex \"[{0}:{1}]format=yuva444p{4},lut=u=128:v=128:y=gammaval(.3)[sub] ; [0:{2}] [sub] overlay{3}\"",
  477. mapPrefix.ToString(UsCulture),
  478. subtitleStreamIndex.ToString(UsCulture),
  479. state.VideoStream.Index.ToString(UsCulture),
  480. outputSizeParam,
  481. videoSizeParam);
  482. }
  483. /// <summary>
  484. /// Gets the video bitrate to specify on the command line
  485. /// </summary>
  486. /// <param name="state">The state.</param>
  487. /// <param name="videoCodec">The video codec.</param>
  488. /// <returns>System.String.</returns>
  489. protected string GetVideoQualityParam(EncodingJob state, string videoCodec)
  490. {
  491. var param = string.Empty;
  492. var isVc1 = state.VideoStream != null &&
  493. string.Equals(state.VideoStream.Codec, "vc1", StringComparison.OrdinalIgnoreCase);
  494. if (string.Equals(videoCodec, "libx264", StringComparison.OrdinalIgnoreCase))
  495. {
  496. param = "-preset superfast";
  497. param += " -crf 23";
  498. }
  499. else if (string.Equals(videoCodec, "libx265", StringComparison.OrdinalIgnoreCase))
  500. {
  501. param = "-preset fast";
  502. param += " -crf 28";
  503. }
  504. // h264 (h264_qsv)
  505. else if (string.Equals(videoCodec, "h264_qsv", StringComparison.OrdinalIgnoreCase))
  506. {
  507. param = "-preset 7 -look_ahead 0";
  508. }
  509. // h264 (h264_nvenc)
  510. else if (string.Equals(videoCodec, "h264_nvenc", StringComparison.OrdinalIgnoreCase))
  511. {
  512. param = "-preset llhq";
  513. }
  514. // webm
  515. else if (string.Equals(videoCodec, "libvpx", StringComparison.OrdinalIgnoreCase))
  516. {
  517. // Values 0-3, 0 being highest quality but slower
  518. var profileScore = 0;
  519. string crf;
  520. var qmin = "0";
  521. var qmax = "50";
  522. crf = "10";
  523. if (isVc1)
  524. {
  525. profileScore++;
  526. }
  527. // Max of 2
  528. profileScore = Math.Min(profileScore, 2);
  529. // http://www.webmproject.org/docs/encoder-parameters/
  530. param = string.Format("-speed 16 -quality good -profile:v {0} -slices 8 -crf {1} -qmin {2} -qmax {3}",
  531. profileScore.ToString(UsCulture),
  532. crf,
  533. qmin,
  534. qmax);
  535. }
  536. else if (string.Equals(videoCodec, "mpeg4", StringComparison.OrdinalIgnoreCase))
  537. {
  538. param = "-mbd rd -flags +mv4+aic -trellis 2 -cmp 2 -subcmp 2 -bf 2";
  539. }
  540. // asf/wmv
  541. else if (string.Equals(videoCodec, "wmv2", StringComparison.OrdinalIgnoreCase))
  542. {
  543. param = "-qmin 2";
  544. }
  545. else if (string.Equals(videoCodec, "msmpeg4", StringComparison.OrdinalIgnoreCase))
  546. {
  547. param = "-mbd 2";
  548. }
  549. param += GetVideoBitrateParam(state, videoCodec);
  550. var framerate = GetFramerateParam(state);
  551. if (framerate.HasValue)
  552. {
  553. param += string.Format(" -r {0}", framerate.Value.ToString(UsCulture));
  554. }
  555. if (!string.IsNullOrEmpty(state.OutputVideoSync))
  556. {
  557. param += " -vsync " + state.OutputVideoSync;
  558. }
  559. if (!string.IsNullOrEmpty(state.Options.Profile))
  560. {
  561. if (!string.Equals(videoCodec, "h264_omx", StringComparison.OrdinalIgnoreCase) &&
  562. !string.Equals(videoCodec, "h264_vaapi", StringComparison.OrdinalIgnoreCase))
  563. {
  564. // not supported by h264_omx
  565. param += " -profile:v " + state.Options.Profile;
  566. }
  567. }
  568. var levelString = state.Options.Level.HasValue ? state.Options.Level.Value.ToString(CultureInfo.InvariantCulture) : null;
  569. if (!string.IsNullOrEmpty(levelString))
  570. {
  571. // h264_qsv and h264_nvenc expect levels to be expressed as a decimal. libx264 supports decimal and non-decimal format
  572. if (string.Equals(videoCodec, "h264_qsv", StringComparison.OrdinalIgnoreCase) ||
  573. string.Equals(videoCodec, "h264_nvenc", StringComparison.OrdinalIgnoreCase))
  574. {
  575. switch (levelString)
  576. {
  577. case "30":
  578. param += " -level 3";
  579. break;
  580. case "31":
  581. param += " -level 3.1";
  582. break;
  583. case "32":
  584. param += " -level 3.2";
  585. break;
  586. case "40":
  587. param += " -level 4";
  588. break;
  589. case "41":
  590. param += " -level 4.1";
  591. break;
  592. case "42":
  593. param += " -level 4.2";
  594. break;
  595. case "50":
  596. param += " -level 5";
  597. break;
  598. case "51":
  599. param += " -level 5.1";
  600. break;
  601. case "52":
  602. param += " -level 5.2";
  603. break;
  604. default:
  605. param += " -level " + levelString;
  606. break;
  607. }
  608. }
  609. else if (!string.Equals(videoCodec, "h264_omx", StringComparison.OrdinalIgnoreCase))
  610. {
  611. param += " -level " + levelString;
  612. }
  613. }
  614. if (!string.Equals(videoCodec, "h264_omx", StringComparison.OrdinalIgnoreCase) &&
  615. !string.Equals(videoCodec, "h264_qsv", StringComparison.OrdinalIgnoreCase) &&
  616. !string.Equals(videoCodec, "h264_nvenc", StringComparison.OrdinalIgnoreCase) &&
  617. !string.Equals(videoCodec, "h264_vaapi", StringComparison.OrdinalIgnoreCase))
  618. {
  619. param = "-pix_fmt yuv420p " + param;
  620. }
  621. return param;
  622. }
  623. protected string GetVideoBitrateParam(EncodingJob state, string videoCodec)
  624. {
  625. var bitrate = state.OutputVideoBitrate;
  626. if (bitrate.HasValue)
  627. {
  628. if (string.Equals(videoCodec, "libvpx", StringComparison.OrdinalIgnoreCase))
  629. {
  630. // With vpx when crf is used, b:v becomes a max rate
  631. // 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.
  632. return string.Format(" -maxrate:v {0} -bufsize:v ({0}*2) -b:v {0}", bitrate.Value.ToString(UsCulture));
  633. }
  634. if (string.Equals(videoCodec, "msmpeg4", StringComparison.OrdinalIgnoreCase))
  635. {
  636. return string.Format(" -b:v {0}", bitrate.Value.ToString(UsCulture));
  637. }
  638. // h264
  639. return string.Format(" -b:v {0} -maxrate {0} -bufsize {1}",
  640. bitrate.Value.ToString(UsCulture),
  641. (bitrate.Value * 2).ToString(UsCulture));
  642. }
  643. return string.Empty;
  644. }
  645. protected double? GetFramerateParam(EncodingJob state)
  646. {
  647. if (state.Options != null)
  648. {
  649. if (state.Options.Framerate.HasValue)
  650. {
  651. return state.Options.Framerate.Value;
  652. }
  653. var maxrate = state.Options.MaxFramerate;
  654. if (maxrate.HasValue && state.VideoStream != null)
  655. {
  656. var contentRate = state.VideoStream.AverageFrameRate ?? state.VideoStream.RealFrameRate;
  657. if (contentRate.HasValue && contentRate.Value > maxrate.Value)
  658. {
  659. return maxrate;
  660. }
  661. }
  662. }
  663. return null;
  664. }
  665. /// <summary>
  666. /// Gets the map args.
  667. /// </summary>
  668. /// <param name="state">The state.</param>
  669. /// <returns>System.String.</returns>
  670. protected virtual string GetMapArgs(EncodingJob state)
  671. {
  672. // If we don't have known media info
  673. // If input is video, use -sn to drop subtitles
  674. // Otherwise just return empty
  675. if (state.VideoStream == null && state.AudioStream == null)
  676. {
  677. return state.IsInputVideo ? "-sn" : string.Empty;
  678. }
  679. // We have media info, but we don't know the stream indexes
  680. if (state.VideoStream != null && state.VideoStream.Index == -1)
  681. {
  682. return "-sn";
  683. }
  684. // We have media info, but we don't know the stream indexes
  685. if (state.AudioStream != null && state.AudioStream.Index == -1)
  686. {
  687. return state.IsInputVideo ? "-sn" : string.Empty;
  688. }
  689. var args = string.Empty;
  690. if (state.VideoStream != null)
  691. {
  692. args += string.Format("-map 0:{0}", state.VideoStream.Index);
  693. }
  694. else
  695. {
  696. args += "-map -0:v";
  697. }
  698. if (state.AudioStream != null)
  699. {
  700. args += string.Format(" -map 0:{0}", state.AudioStream.Index);
  701. }
  702. else
  703. {
  704. args += " -map -0:a";
  705. }
  706. if (state.SubtitleStream == null || state.Options.SubtitleMethod == SubtitleDeliveryMethod.Hls)
  707. {
  708. args += " -map -0:s";
  709. }
  710. else if (state.SubtitleStream.IsExternal && !state.SubtitleStream.IsTextSubtitleStream)
  711. {
  712. args += " -map 1:0 -sn";
  713. }
  714. return args;
  715. }
  716. /// <summary>
  717. /// Determines whether the specified stream is H264.
  718. /// </summary>
  719. /// <param name="stream">The stream.</param>
  720. /// <returns><c>true</c> if the specified stream is H264; otherwise, <c>false</c>.</returns>
  721. protected bool IsH264(MediaStream stream)
  722. {
  723. var codec = stream.Codec ?? string.Empty;
  724. return codec.IndexOf("264", StringComparison.OrdinalIgnoreCase) != -1 ||
  725. codec.IndexOf("avc", StringComparison.OrdinalIgnoreCase) != -1;
  726. }
  727. /// <summary>
  728. /// If we're going to put a fixed size on the command line, this will calculate it
  729. /// </summary>
  730. /// <param name="state">The state.</param>
  731. /// <param name="outputVideoCodec">The output video codec.</param>
  732. /// <param name="allowTimeStampCopy">if set to <c>true</c> [allow time stamp copy].</param>
  733. /// <returns>System.String.</returns>
  734. protected async Task<string> GetOutputSizeParam(EncodingJob state,
  735. string outputVideoCodec,
  736. bool allowTimeStampCopy = true)
  737. {
  738. // http://sonnati.wordpress.com/2012/10/19/ffmpeg-the-swiss-army-knife-of-internet-streaming-part-vi/
  739. var request = state.Options;
  740. var filters = new List<string>();
  741. if (string.Equals(outputVideoCodec, "h264_vaapi", StringComparison.OrdinalIgnoreCase))
  742. {
  743. filters.Add("format=nv12|vaapi");
  744. filters.Add("hwupload");
  745. }
  746. else if (state.DeInterlace && !string.Equals(outputVideoCodec, "h264_vaapi", StringComparison.OrdinalIgnoreCase))
  747. {
  748. filters.Add("yadif=0:-1:0");
  749. }
  750. if (string.Equals(outputVideoCodec, "h264_vaapi", StringComparison.OrdinalIgnoreCase))
  751. {
  752. // Work around vaapi's reduced scaling features
  753. var scaler = "scale_vaapi";
  754. // Given the input dimensions (inputWidth, inputHeight), determine the output dimensions
  755. // (outputWidth, outputHeight). The user may request precise output dimensions or maximum
  756. // output dimensions. Output dimensions are guaranteed to be even.
  757. decimal inputWidth = Convert.ToDecimal(state.VideoStream.Width);
  758. decimal inputHeight = Convert.ToDecimal(state.VideoStream.Height);
  759. decimal outputWidth = request.Width.HasValue ? Convert.ToDecimal(request.Width.Value) : inputWidth;
  760. decimal outputHeight = request.Height.HasValue ? Convert.ToDecimal(request.Height.Value) : inputHeight;
  761. decimal maximumWidth = request.MaxWidth.HasValue ? Convert.ToDecimal(request.MaxWidth.Value) : outputWidth;
  762. decimal maximumHeight = request.MaxHeight.HasValue ? Convert.ToDecimal(request.MaxHeight.Value) : outputHeight;
  763. if (outputWidth > maximumWidth || outputHeight > maximumHeight)
  764. {
  765. var scale = Math.Min(maximumWidth / outputWidth, maximumHeight / outputHeight);
  766. outputWidth = Math.Min(maximumWidth, Math.Truncate(outputWidth * scale));
  767. outputHeight = Math.Min(maximumHeight, Math.Truncate(outputHeight * scale));
  768. }
  769. outputWidth = 2 * Math.Truncate(outputWidth / 2);
  770. outputHeight = 2 * Math.Truncate(outputHeight / 2);
  771. if (outputWidth != inputWidth || outputHeight != inputHeight)
  772. {
  773. filters.Add(string.Format("{0}=w={1}:h={2}", scaler, outputWidth.ToString(UsCulture), outputHeight.ToString(UsCulture)));
  774. }
  775. }
  776. else
  777. {
  778. // If fixed dimensions were supplied
  779. if (request.Width.HasValue && request.Height.HasValue)
  780. {
  781. var widthParam = request.Width.Value.ToString(UsCulture);
  782. var heightParam = request.Height.Value.ToString(UsCulture);
  783. filters.Add(string.Format("scale=trunc({0}/2)*2:trunc({1}/2)*2", widthParam, heightParam));
  784. }
  785. // 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
  786. else if (request.MaxWidth.HasValue && request.MaxHeight.HasValue)
  787. {
  788. var maxWidthParam = request.MaxWidth.Value.ToString(UsCulture);
  789. var maxHeightParam = request.MaxHeight.Value.ToString(UsCulture);
  790. 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));
  791. }
  792. // If a fixed width was requested
  793. else if (request.Width.HasValue)
  794. {
  795. var widthParam = request.Width.Value.ToString(UsCulture);
  796. filters.Add(string.Format("scale={0}:trunc(ow/a/2)*2", widthParam));
  797. }
  798. // If a fixed height was requested
  799. else if (request.Height.HasValue)
  800. {
  801. var heightParam = request.Height.Value.ToString(UsCulture);
  802. filters.Add(string.Format("scale=trunc(oh*a/2)*2:{0}", heightParam));
  803. }
  804. // If a max width was requested
  805. else if (request.MaxWidth.HasValue)
  806. {
  807. var maxWidthParam = request.MaxWidth.Value.ToString(UsCulture);
  808. filters.Add(string.Format("scale=trunc(min(max(iw\\,ih*dar)\\,{0})/2)*2:trunc(ow/dar/2)*2", maxWidthParam));
  809. }
  810. // If a max height was requested
  811. else if (request.MaxHeight.HasValue)
  812. {
  813. var maxHeightParam = request.MaxHeight.Value.ToString(UsCulture);
  814. filters.Add(string.Format("scale=trunc(oh*a/2)*2:min(max(iw/dar\\,ih)\\,{0})", maxHeightParam));
  815. }
  816. }
  817. var output = string.Empty;
  818. if (state.SubtitleStream != null && state.SubtitleStream.IsTextSubtitleStream && state.Options.SubtitleMethod == SubtitleDeliveryMethod.Encode)
  819. {
  820. var subParam = await GetTextSubtitleParam(state).ConfigureAwait(false);
  821. filters.Add(subParam);
  822. if (allowTimeStampCopy)
  823. {
  824. output += " -copyts";
  825. }
  826. }
  827. if (filters.Count > 0)
  828. {
  829. output += string.Format(" -vf \"{0}\"", string.Join(",", filters.ToArray()));
  830. }
  831. return output;
  832. }
  833. /// <summary>
  834. /// Gets the text subtitle param.
  835. /// </summary>
  836. /// <param name="state">The state.</param>
  837. /// <returns>System.String.</returns>
  838. protected async Task<string> GetTextSubtitleParam(EncodingJob state)
  839. {
  840. var seconds = Math.Round(TimeSpan.FromTicks(state.Options.StartTimeTicks ?? 0).TotalSeconds);
  841. if (state.SubtitleStream.IsExternal)
  842. {
  843. var subtitlePath = state.SubtitleStream.Path;
  844. var charsetParam = string.Empty;
  845. if (!string.IsNullOrEmpty(state.SubtitleStream.Language))
  846. {
  847. var charenc = await SubtitleEncoder.GetSubtitleFileCharacterSet(subtitlePath, state.SubtitleStream.Language, state.MediaSource.Protocol, CancellationToken.None).ConfigureAwait(false);
  848. if (!string.IsNullOrEmpty(charenc))
  849. {
  850. charsetParam = ":charenc=" + charenc;
  851. }
  852. }
  853. // TODO: Perhaps also use original_size=1920x800 ??
  854. return string.Format("subtitles=filename='{0}'{1},setpts=PTS -{2}/TB",
  855. MediaEncoder.EscapeSubtitleFilterPath(subtitlePath),
  856. charsetParam,
  857. seconds.ToString(UsCulture));
  858. }
  859. var mediaPath = state.MediaPath ?? string.Empty;
  860. return string.Format("subtitles='{0}:si={1}',setpts=PTS -{2}/TB",
  861. MediaEncoder.EscapeSubtitleFilterPath(mediaPath),
  862. state.InternalSubtitleStreamOffset.ToString(UsCulture),
  863. seconds.ToString(UsCulture));
  864. }
  865. protected string GetAudioFilterParam(EncodingJob state, bool isHls)
  866. {
  867. var volParam = string.Empty;
  868. var audioSampleRate = string.Empty;
  869. var channels = state.OutputAudioChannels;
  870. // Boost volume to 200% when downsampling from 6ch to 2ch
  871. if (channels.HasValue && channels.Value <= 2)
  872. {
  873. if (state.AudioStream != null && state.AudioStream.Channels.HasValue && state.AudioStream.Channels.Value > 5 && !GetEncodingOptions().DownMixAudioBoost.Equals(1))
  874. {
  875. volParam = ",volume=" + GetEncodingOptions().DownMixAudioBoost.ToString(UsCulture);
  876. }
  877. }
  878. if (state.OutputAudioSampleRate.HasValue)
  879. {
  880. audioSampleRate = state.OutputAudioSampleRate.Value + ":";
  881. }
  882. var adelay = isHls ? "adelay=1," : string.Empty;
  883. var pts = string.Empty;
  884. if (state.SubtitleStream != null && state.SubtitleStream.IsTextSubtitleStream && state.Options.SubtitleMethod == SubtitleDeliveryMethod.Encode && !state.Options.CopyTimestamps)
  885. {
  886. var seconds = TimeSpan.FromTicks(state.Options.StartTimeTicks ?? 0).TotalSeconds;
  887. pts = string.Format(",asetpts=PTS-{0}/TB", Math.Round(seconds).ToString(UsCulture));
  888. }
  889. return string.Format("-af \"{0}aresample={1}async={4}{2}{3}\"",
  890. adelay,
  891. audioSampleRate,
  892. volParam,
  893. pts,
  894. state.OutputAudioSync);
  895. }
  896. }
  897. }