2
0

BaseEncoder.cs 43 KB

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