EncodingHelper.cs 62 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Globalization;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Threading;
  7. using MediaBrowser.Controller.Configuration;
  8. using MediaBrowser.Model.Configuration;
  9. using MediaBrowser.Model.Dlna;
  10. using MediaBrowser.Model.Dto;
  11. using MediaBrowser.Model.Entities;
  12. using MediaBrowser.Model.IO;
  13. using MediaBrowser.Model.MediaInfo;
  14. namespace MediaBrowser.Controller.MediaEncoding
  15. {
  16. public class EncodingHelper
  17. {
  18. private readonly CultureInfo _usCulture = new CultureInfo("en-US");
  19. private readonly IMediaEncoder _mediaEncoder;
  20. private readonly IServerConfigurationManager _config;
  21. private readonly IFileSystem _fileSystem;
  22. private readonly ISubtitleEncoder _subtitleEncoder;
  23. public EncodingHelper(IMediaEncoder mediaEncoder, IServerConfigurationManager config, IFileSystem fileSystem, ISubtitleEncoder subtitleEncoder)
  24. {
  25. _mediaEncoder = mediaEncoder;
  26. _config = config;
  27. _fileSystem = fileSystem;
  28. _subtitleEncoder = subtitleEncoder;
  29. }
  30. public string GetH264Encoder(EncodingJobInfo state, EncodingOptions encodingOptions)
  31. {
  32. var defaultEncoder = "libx264";
  33. // Only use alternative encoders for video files.
  34. // When using concat with folder rips, if the mfx session fails to initialize, ffmpeg will be stuck retrying and will not exit gracefully
  35. // Since transcoding of folder rips is expiremental anyway, it's not worth adding additional variables such as this.
  36. if (state.VideoType == VideoType.VideoFile)
  37. {
  38. var hwType = encodingOptions.HardwareAccelerationType;
  39. if (string.Equals(hwType, "qsv", StringComparison.OrdinalIgnoreCase) ||
  40. string.Equals(hwType, "h264_qsv", StringComparison.OrdinalIgnoreCase))
  41. {
  42. return GetAvailableEncoder("h264_qsv", defaultEncoder);
  43. }
  44. if (string.Equals(hwType, "nvenc", StringComparison.OrdinalIgnoreCase))
  45. {
  46. return GetAvailableEncoder("h264_nvenc", defaultEncoder);
  47. }
  48. if (string.Equals(hwType, "h264_omx", StringComparison.OrdinalIgnoreCase))
  49. {
  50. return GetAvailableEncoder("h264_omx", defaultEncoder);
  51. }
  52. if (string.Equals(hwType, "vaapi", StringComparison.OrdinalIgnoreCase) && !string.IsNullOrWhiteSpace(encodingOptions.VaapiDevice))
  53. {
  54. if (IsVaapiSupported(state))
  55. {
  56. return GetAvailableEncoder("h264_vaapi", defaultEncoder);
  57. }
  58. }
  59. }
  60. return defaultEncoder;
  61. }
  62. private string GetAvailableEncoder(string preferredEncoder, string defaultEncoder)
  63. {
  64. if (_mediaEncoder.SupportsEncoder(preferredEncoder))
  65. {
  66. return preferredEncoder;
  67. }
  68. return defaultEncoder;
  69. }
  70. private bool IsVaapiSupported(EncodingJobInfo state)
  71. {
  72. var videoStream = state.VideoStream;
  73. if (videoStream != null)
  74. {
  75. // vaapi will throw an error with this input
  76. // [vaapi @ 0x7faed8000960] No VAAPI support for codec mpeg4 profile -99.
  77. if (string.Equals(videoStream.Codec, "mpeg4", StringComparison.OrdinalIgnoreCase))
  78. {
  79. if (videoStream.Level == -99 || videoStream.Level == 15)
  80. {
  81. return false;
  82. }
  83. }
  84. }
  85. return true;
  86. }
  87. /// <summary>
  88. /// Gets the name of the output video codec
  89. /// </summary>
  90. public string GetVideoEncoder(EncodingJobInfo state, EncodingOptions encodingOptions)
  91. {
  92. var codec = state.OutputVideoCodec;
  93. if (!string.IsNullOrEmpty(codec))
  94. {
  95. if (string.Equals(codec, "h264", StringComparison.OrdinalIgnoreCase))
  96. {
  97. return GetH264Encoder(state, encodingOptions);
  98. }
  99. if (string.Equals(codec, "vpx", StringComparison.OrdinalIgnoreCase))
  100. {
  101. return "libvpx";
  102. }
  103. if (string.Equals(codec, "wmv", StringComparison.OrdinalIgnoreCase))
  104. {
  105. return "wmv2";
  106. }
  107. if (string.Equals(codec, "theora", StringComparison.OrdinalIgnoreCase))
  108. {
  109. return "libtheora";
  110. }
  111. return codec.ToLower();
  112. }
  113. return "copy";
  114. }
  115. /// <summary>
  116. /// Gets the user agent param.
  117. /// </summary>
  118. /// <param name="state">The state.</param>
  119. /// <returns>System.String.</returns>
  120. public string GetUserAgentParam(EncodingJobInfo state)
  121. {
  122. string useragent = null;
  123. state.RemoteHttpHeaders.TryGetValue("User-Agent", out useragent);
  124. if (!string.IsNullOrWhiteSpace(useragent))
  125. {
  126. return "-user-agent \"" + useragent + "\"";
  127. }
  128. return string.Empty;
  129. }
  130. public string GetInputFormat(string container)
  131. {
  132. if (string.Equals(container, "mkv", StringComparison.OrdinalIgnoreCase))
  133. {
  134. return "matroska";
  135. }
  136. if (string.Equals(container, "ts", StringComparison.OrdinalIgnoreCase))
  137. {
  138. return "mpegts";
  139. }
  140. return container;
  141. }
  142. public string GetDecoderFromCodec(string codec)
  143. {
  144. if (string.Equals(codec, "mp2", StringComparison.OrdinalIgnoreCase))
  145. {
  146. return null;
  147. }
  148. if (string.Equals(codec, "aac_latm", StringComparison.OrdinalIgnoreCase))
  149. {
  150. return null;
  151. }
  152. return codec;
  153. }
  154. /// <summary>
  155. /// Infers the audio codec based on the url
  156. /// </summary>
  157. /// <param name="url">The URL.</param>
  158. /// <returns>System.Nullable{AudioCodecs}.</returns>
  159. public string InferAudioCodec(string url)
  160. {
  161. var ext = Path.GetExtension(url);
  162. if (string.Equals(ext, ".mp3", StringComparison.OrdinalIgnoreCase))
  163. {
  164. return "mp3";
  165. }
  166. if (string.Equals(ext, ".aac", StringComparison.OrdinalIgnoreCase))
  167. {
  168. return "aac";
  169. }
  170. if (string.Equals(ext, ".wma", StringComparison.OrdinalIgnoreCase))
  171. {
  172. return "wma";
  173. }
  174. if (string.Equals(ext, ".ogg", StringComparison.OrdinalIgnoreCase))
  175. {
  176. return "vorbis";
  177. }
  178. if (string.Equals(ext, ".oga", StringComparison.OrdinalIgnoreCase))
  179. {
  180. return "vorbis";
  181. }
  182. if (string.Equals(ext, ".ogv", StringComparison.OrdinalIgnoreCase))
  183. {
  184. return "vorbis";
  185. }
  186. if (string.Equals(ext, ".webm", StringComparison.OrdinalIgnoreCase))
  187. {
  188. return "vorbis";
  189. }
  190. if (string.Equals(ext, ".webma", StringComparison.OrdinalIgnoreCase))
  191. {
  192. return "vorbis";
  193. }
  194. return "copy";
  195. }
  196. /// <summary>
  197. /// Infers the video codec.
  198. /// </summary>
  199. /// <param name="url">The URL.</param>
  200. /// <returns>System.Nullable{VideoCodecs}.</returns>
  201. public string InferVideoCodec(string url)
  202. {
  203. var ext = Path.GetExtension(url);
  204. if (string.Equals(ext, ".asf", StringComparison.OrdinalIgnoreCase))
  205. {
  206. return "wmv";
  207. }
  208. if (string.Equals(ext, ".webm", StringComparison.OrdinalIgnoreCase))
  209. {
  210. return "vpx";
  211. }
  212. if (string.Equals(ext, ".ogg", StringComparison.OrdinalIgnoreCase) || string.Equals(ext, ".ogv", StringComparison.OrdinalIgnoreCase))
  213. {
  214. return "theora";
  215. }
  216. if (string.Equals(ext, ".m3u8", StringComparison.OrdinalIgnoreCase) || string.Equals(ext, ".ts", StringComparison.OrdinalIgnoreCase))
  217. {
  218. return "h264";
  219. }
  220. return "copy";
  221. }
  222. public int GetVideoProfileScore(string profile)
  223. {
  224. var list = new List<string>
  225. {
  226. "Constrained Baseline",
  227. "Baseline",
  228. "Extended",
  229. "Main",
  230. "High",
  231. "Progressive High",
  232. "Constrained High"
  233. };
  234. return Array.FindIndex(list.ToArray(), t => string.Equals(t, profile, StringComparison.OrdinalIgnoreCase));
  235. }
  236. public string GetInputPathArgument(EncodingJobInfo state)
  237. {
  238. var protocol = state.InputProtocol;
  239. var mediaPath = state.MediaPath ?? string.Empty;
  240. var inputPath = new[] { mediaPath };
  241. if (state.IsInputVideo)
  242. {
  243. if (!(state.VideoType == VideoType.Iso && state.IsoMount == null))
  244. {
  245. inputPath = MediaEncoderHelpers.GetInputArgument(_fileSystem, mediaPath, state.InputProtocol, state.IsoMount, state.PlayableStreamFileNames);
  246. }
  247. }
  248. return _mediaEncoder.GetInputArgument(inputPath, protocol);
  249. }
  250. /// <summary>
  251. /// Gets the audio encoder.
  252. /// </summary>
  253. /// <param name="state">The state.</param>
  254. /// <returns>System.String.</returns>
  255. public string GetAudioEncoder(EncodingJobInfo state)
  256. {
  257. var codec = state.OutputAudioCodec;
  258. if (string.Equals(codec, "aac", StringComparison.OrdinalIgnoreCase))
  259. {
  260. return "aac -strict experimental";
  261. }
  262. if (string.Equals(codec, "mp3", StringComparison.OrdinalIgnoreCase))
  263. {
  264. return "libmp3lame";
  265. }
  266. if (string.Equals(codec, "vorbis", StringComparison.OrdinalIgnoreCase))
  267. {
  268. return "libvorbis";
  269. }
  270. if (string.Equals(codec, "wma", StringComparison.OrdinalIgnoreCase))
  271. {
  272. return "wmav2";
  273. }
  274. return codec.ToLower();
  275. }
  276. /// <summary>
  277. /// Gets the input argument.
  278. /// </summary>
  279. public string GetInputArgument(EncodingJobInfo state, EncodingOptions encodingOptions)
  280. {
  281. var request = state.BaseRequest;
  282. var arg = string.Format("-i {0}", GetInputPathArgument(state));
  283. if (state.SubtitleStream != null && request.SubtitleMethod == SubtitleDeliveryMethod.Encode)
  284. {
  285. if (state.SubtitleStream.IsExternal && !state.SubtitleStream.IsTextSubtitleStream)
  286. {
  287. if (state.VideoStream != null && state.VideoStream.Width.HasValue)
  288. {
  289. // This is hacky but not sure how to get the exact subtitle resolution
  290. double height = state.VideoStream.Width.Value;
  291. height /= 16;
  292. height *= 9;
  293. arg += string.Format(" -canvas_size {0}:{1}", state.VideoStream.Width.Value.ToString(CultureInfo.InvariantCulture), Convert.ToInt32(height).ToString(CultureInfo.InvariantCulture));
  294. }
  295. var subtitlePath = state.SubtitleStream.Path;
  296. if (string.Equals(Path.GetExtension(subtitlePath), ".sub", StringComparison.OrdinalIgnoreCase))
  297. {
  298. var idxFile = Path.ChangeExtension(subtitlePath, ".idx");
  299. if (_fileSystem.FileExists(idxFile))
  300. {
  301. subtitlePath = idxFile;
  302. }
  303. }
  304. arg += " -i \"" + subtitlePath + "\"";
  305. }
  306. }
  307. if (state.IsVideoRequest)
  308. {
  309. if (GetVideoEncoder(state, encodingOptions).IndexOf("vaapi", StringComparison.OrdinalIgnoreCase) != -1)
  310. {
  311. var hasGraphicalSubs = state.SubtitleStream != null && !state.SubtitleStream.IsTextSubtitleStream && request.SubtitleMethod == SubtitleDeliveryMethod.Encode;
  312. var hwOutputFormat = "vaapi";
  313. if (hasGraphicalSubs)
  314. {
  315. hwOutputFormat = "yuv420p";
  316. }
  317. arg = "-hwaccel vaapi -hwaccel_output_format " + hwOutputFormat + " -vaapi_device " + encodingOptions.VaapiDevice + " " + arg;
  318. }
  319. }
  320. return arg.Trim();
  321. }
  322. /// <summary>
  323. /// Determines whether the specified stream is H264.
  324. /// </summary>
  325. /// <param name="stream">The stream.</param>
  326. /// <returns><c>true</c> if the specified stream is H264; otherwise, <c>false</c>.</returns>
  327. public bool IsH264(MediaStream stream)
  328. {
  329. var codec = stream.Codec ?? string.Empty;
  330. return codec.IndexOf("264", StringComparison.OrdinalIgnoreCase) != -1 ||
  331. codec.IndexOf("avc", StringComparison.OrdinalIgnoreCase) != -1;
  332. }
  333. public string GetVideoBitrateParam(EncodingJobInfo state, string videoCodec)
  334. {
  335. var bitrate = state.OutputVideoBitrate;
  336. if (bitrate.HasValue)
  337. {
  338. if (string.Equals(videoCodec, "libvpx", StringComparison.OrdinalIgnoreCase))
  339. {
  340. // With vpx when crf is used, b:v becomes a max rate
  341. // 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.
  342. return string.Format(" -maxrate:v {0} -bufsize:v ({0}*2) -b:v {0}", bitrate.Value.ToString(_usCulture));
  343. }
  344. if (string.Equals(videoCodec, "msmpeg4", StringComparison.OrdinalIgnoreCase))
  345. {
  346. return string.Format(" -b:v {0}", bitrate.Value.ToString(_usCulture));
  347. }
  348. if (string.Equals(videoCodec, "libx264", StringComparison.OrdinalIgnoreCase))
  349. {
  350. // h264
  351. return string.Format(" -maxrate {0} -bufsize {1}",
  352. bitrate.Value.ToString(_usCulture),
  353. (bitrate.Value * 2).ToString(_usCulture));
  354. }
  355. // h264
  356. return string.Format(" -b:v {0} -maxrate {0} -bufsize {1}",
  357. bitrate.Value.ToString(_usCulture),
  358. (bitrate.Value * 2).ToString(_usCulture));
  359. }
  360. return string.Empty;
  361. }
  362. public string NormalizeTranscodingLevel(string videoCodec, string level)
  363. {
  364. double requestLevel;
  365. // Clients may direct play higher than level 41, but there's no reason to transcode higher
  366. if (double.TryParse(level, NumberStyles.Any, _usCulture, out requestLevel))
  367. {
  368. if (string.Equals(videoCodec, "h264", StringComparison.OrdinalIgnoreCase))
  369. {
  370. if (requestLevel > 41)
  371. {
  372. return "41";
  373. }
  374. }
  375. }
  376. return level;
  377. }
  378. /// <summary>
  379. /// Gets the probe size argument.
  380. /// </summary>
  381. /// <param name="state">The state.</param>
  382. /// <returns>System.String.</returns>
  383. public string GetProbeSizeArgument(EncodingJobInfo state)
  384. {
  385. if (state.PlayableStreamFileNames.Count > 0)
  386. {
  387. return _mediaEncoder.GetProbeSizeAndAnalyzeDurationArgument(state.PlayableStreamFileNames.ToArray(), state.InputProtocol);
  388. }
  389. return _mediaEncoder.GetProbeSizeAndAnalyzeDurationArgument(new[] { state.MediaPath }, state.InputProtocol);
  390. }
  391. /// <summary>
  392. /// Gets the text subtitle param.
  393. /// </summary>
  394. /// <param name="state">The state.</param>
  395. /// <returns>System.String.</returns>
  396. public string GetTextSubtitleParam(EncodingJobInfo state)
  397. {
  398. var seconds = Math.Round(TimeSpan.FromTicks(state.StartTimeTicks ?? 0).TotalSeconds);
  399. var setPtsParam = state.CopyTimestamps
  400. ? string.Empty
  401. : string.Format(",setpts=PTS -{0}/TB", seconds.ToString(_usCulture));
  402. if (state.SubtitleStream.IsExternal)
  403. {
  404. var subtitlePath = state.SubtitleStream.Path;
  405. var charsetParam = string.Empty;
  406. if (!string.IsNullOrEmpty(state.SubtitleStream.Language))
  407. {
  408. var charenc = _subtitleEncoder.GetSubtitleFileCharacterSet(subtitlePath, state.SubtitleStream.Language, state.MediaSource.Protocol, CancellationToken.None).Result;
  409. if (!string.IsNullOrEmpty(charenc))
  410. {
  411. charsetParam = ":charenc=" + charenc;
  412. }
  413. }
  414. // TODO: Perhaps also use original_size=1920x800 ??
  415. return string.Format("subtitles=filename='{0}'{1}{2}",
  416. _mediaEncoder.EscapeSubtitleFilterPath(subtitlePath),
  417. charsetParam,
  418. setPtsParam);
  419. }
  420. var mediaPath = state.MediaPath ?? string.Empty;
  421. return string.Format("subtitles='{0}:si={1}'{2}",
  422. _mediaEncoder.EscapeSubtitleFilterPath(mediaPath),
  423. state.InternalSubtitleStreamOffset.ToString(_usCulture),
  424. setPtsParam);
  425. }
  426. public double? GetFramerateParam(EncodingJobInfo state)
  427. {
  428. var request = state.BaseRequest;
  429. if (request.Framerate.HasValue)
  430. {
  431. return request.Framerate.Value;
  432. }
  433. var maxrate = request.MaxFramerate;
  434. if (maxrate.HasValue && state.VideoStream != null)
  435. {
  436. var contentRate = state.VideoStream.AverageFrameRate ?? state.VideoStream.RealFrameRate;
  437. if (contentRate.HasValue && contentRate.Value > maxrate.Value)
  438. {
  439. return maxrate;
  440. }
  441. }
  442. return null;
  443. }
  444. /// <summary>
  445. /// Gets the video bitrate to specify on the command line
  446. /// </summary>
  447. public string GetVideoQualityParam(EncodingJobInfo state, string videoEncoder, EncodingOptions encodingOptions, string defaultH264Preset)
  448. {
  449. var param = string.Empty;
  450. var isVc1 = state.VideoStream != null &&
  451. string.Equals(state.VideoStream.Codec, "vc1", StringComparison.OrdinalIgnoreCase);
  452. if (string.Equals(videoEncoder, "libx264", StringComparison.OrdinalIgnoreCase))
  453. {
  454. if (!string.IsNullOrWhiteSpace(encodingOptions.H264Preset))
  455. {
  456. param += "-preset " + encodingOptions.H264Preset;
  457. }
  458. else
  459. {
  460. param += "-preset " + defaultH264Preset;
  461. }
  462. if (encodingOptions.H264Crf >= 0 && encodingOptions.H264Crf <= 51)
  463. {
  464. param += " -crf " + encodingOptions.H264Crf.ToString(CultureInfo.InvariantCulture);
  465. }
  466. else
  467. {
  468. param += " -crf 23";
  469. }
  470. }
  471. else if (string.Equals(videoEncoder, "libx265", StringComparison.OrdinalIgnoreCase))
  472. {
  473. param += "-preset fast";
  474. param += " -crf 28";
  475. }
  476. // h264 (h264_qsv)
  477. else if (string.Equals(videoEncoder, "h264_qsv", StringComparison.OrdinalIgnoreCase))
  478. {
  479. param += "-preset 7 -look_ahead 0";
  480. }
  481. // h264 (h264_nvenc)
  482. else if (string.Equals(videoEncoder, "h264_nvenc", StringComparison.OrdinalIgnoreCase))
  483. {
  484. param += "-preset default";
  485. }
  486. // webm
  487. else if (string.Equals(videoEncoder, "libvpx", StringComparison.OrdinalIgnoreCase))
  488. {
  489. // Values 0-3, 0 being highest quality but slower
  490. var profileScore = 0;
  491. string crf;
  492. var qmin = "0";
  493. var qmax = "50";
  494. crf = "10";
  495. if (isVc1)
  496. {
  497. profileScore++;
  498. }
  499. // Max of 2
  500. profileScore = Math.Min(profileScore, 2);
  501. // http://www.webmproject.org/docs/encoder-parameters/
  502. param += string.Format("-speed 16 -quality good -profile:v {0} -slices 8 -crf {1} -qmin {2} -qmax {3}",
  503. profileScore.ToString(_usCulture),
  504. crf,
  505. qmin,
  506. qmax);
  507. }
  508. else if (string.Equals(videoEncoder, "mpeg4", StringComparison.OrdinalIgnoreCase))
  509. {
  510. param += "-mbd rd -flags +mv4+aic -trellis 2 -cmp 2 -subcmp 2 -bf 2";
  511. }
  512. // asf/wmv
  513. else if (string.Equals(videoEncoder, "wmv2", StringComparison.OrdinalIgnoreCase))
  514. {
  515. param += "-qmin 2";
  516. }
  517. else if (string.Equals(videoEncoder, "msmpeg4", StringComparison.OrdinalIgnoreCase))
  518. {
  519. param += "-mbd 2";
  520. }
  521. param += GetVideoBitrateParam(state, videoEncoder);
  522. var framerate = GetFramerateParam(state);
  523. if (framerate.HasValue)
  524. {
  525. param += string.Format(" -r {0}", framerate.Value.ToString(_usCulture));
  526. }
  527. if (!string.IsNullOrEmpty(state.OutputVideoSync))
  528. {
  529. param += " -vsync " + state.OutputVideoSync;
  530. }
  531. var request = state.BaseRequest;
  532. if (!string.IsNullOrEmpty(request.Profile))
  533. {
  534. if (!string.Equals(videoEncoder, "h264_omx", StringComparison.OrdinalIgnoreCase) &&
  535. !string.Equals(videoEncoder, "h264_vaapi", StringComparison.OrdinalIgnoreCase))
  536. {
  537. // not supported by h264_omx
  538. param += " -profile:v " + request.Profile;
  539. }
  540. }
  541. if (!string.IsNullOrEmpty(request.Level))
  542. {
  543. var level = NormalizeTranscodingLevel(state.OutputVideoCodec, request.Level);
  544. // h264_qsv and h264_nvenc expect levels to be expressed as a decimal. libx264 supports decimal and non-decimal format
  545. // also needed for libx264 due to https://trac.ffmpeg.org/ticket/3307
  546. if (string.Equals(videoEncoder, "h264_qsv", StringComparison.OrdinalIgnoreCase) ||
  547. string.Equals(videoEncoder, "h264_nvenc", StringComparison.OrdinalIgnoreCase) ||
  548. string.Equals(videoEncoder, "libx264", StringComparison.OrdinalIgnoreCase))
  549. {
  550. switch (level)
  551. {
  552. case "30":
  553. param += " -level 3.0";
  554. break;
  555. case "31":
  556. param += " -level 3.1";
  557. break;
  558. case "32":
  559. param += " -level 3.2";
  560. break;
  561. case "40":
  562. param += " -level 4.0";
  563. break;
  564. case "41":
  565. param += " -level 4.1";
  566. break;
  567. case "42":
  568. param += " -level 4.2";
  569. break;
  570. case "50":
  571. param += " -level 5.0";
  572. break;
  573. case "51":
  574. param += " -level 5.1";
  575. break;
  576. case "52":
  577. param += " -level 5.2";
  578. break;
  579. default:
  580. param += " -level " + level;
  581. break;
  582. }
  583. }
  584. else if (!string.Equals(videoEncoder, "h264_omx", StringComparison.OrdinalIgnoreCase))
  585. {
  586. param += " -level " + level;
  587. }
  588. }
  589. if (string.Equals(videoEncoder, "libx264", StringComparison.OrdinalIgnoreCase))
  590. {
  591. param += " -x264opts:0 subme=0:rc_lookahead=10:me_range=4:me=dia:no_chroma_me:8x8dct=0:partitions=none";
  592. }
  593. if (!string.Equals(videoEncoder, "h264_omx", StringComparison.OrdinalIgnoreCase) &&
  594. !string.Equals(videoEncoder, "h264_qsv", StringComparison.OrdinalIgnoreCase) &&
  595. !string.Equals(videoEncoder, "h264_vaapi", StringComparison.OrdinalIgnoreCase))
  596. {
  597. param = "-pix_fmt yuv420p " + param;
  598. }
  599. return param;
  600. }
  601. public bool CanStreamCopyVideo(EncodingJobInfo state, MediaStream videoStream)
  602. {
  603. var request = state.BaseRequest;
  604. if (videoStream.IsInterlaced)
  605. {
  606. return false;
  607. }
  608. if (videoStream.IsAnamorphic ?? false)
  609. {
  610. return false;
  611. }
  612. // Can't stream copy if we're burning in subtitles
  613. if (request.SubtitleStreamIndex.HasValue)
  614. {
  615. if (request.SubtitleMethod == SubtitleDeliveryMethod.Encode)
  616. {
  617. return false;
  618. }
  619. }
  620. if (string.Equals("h264", videoStream.Codec, StringComparison.OrdinalIgnoreCase))
  621. {
  622. if (videoStream.IsAVC.HasValue && !videoStream.IsAVC.Value && request.RequireAvc)
  623. {
  624. return false;
  625. }
  626. }
  627. // Source and target codecs must match
  628. if (string.IsNullOrEmpty(videoStream.Codec) || !state.SupportedVideoCodecs.Contains(videoStream.Codec, StringComparer.OrdinalIgnoreCase))
  629. {
  630. return false;
  631. }
  632. // If client is requesting a specific video profile, it must match the source
  633. if (!string.IsNullOrEmpty(request.Profile))
  634. {
  635. if (string.IsNullOrEmpty(videoStream.Profile))
  636. {
  637. //return false;
  638. }
  639. if (!string.IsNullOrEmpty(videoStream.Profile) && !string.Equals(request.Profile, videoStream.Profile, StringComparison.OrdinalIgnoreCase))
  640. {
  641. var currentScore = GetVideoProfileScore(videoStream.Profile);
  642. var requestedScore = GetVideoProfileScore(request.Profile);
  643. if (currentScore == -1 || currentScore > requestedScore)
  644. {
  645. return false;
  646. }
  647. }
  648. }
  649. // Video width must fall within requested value
  650. if (request.MaxWidth.HasValue)
  651. {
  652. if (!videoStream.Width.HasValue || videoStream.Width.Value > request.MaxWidth.Value)
  653. {
  654. return false;
  655. }
  656. }
  657. // Video height must fall within requested value
  658. if (request.MaxHeight.HasValue)
  659. {
  660. if (!videoStream.Height.HasValue || videoStream.Height.Value > request.MaxHeight.Value)
  661. {
  662. return false;
  663. }
  664. }
  665. // Video framerate must fall within requested value
  666. var requestedFramerate = request.MaxFramerate ?? request.Framerate;
  667. if (requestedFramerate.HasValue)
  668. {
  669. var videoFrameRate = videoStream.AverageFrameRate ?? videoStream.RealFrameRate;
  670. if (!videoFrameRate.HasValue || videoFrameRate.Value > requestedFramerate.Value)
  671. {
  672. return false;
  673. }
  674. }
  675. // Video bitrate must fall within requested value
  676. if (request.VideoBitRate.HasValue)
  677. {
  678. if (!videoStream.BitRate.HasValue || videoStream.BitRate.Value > request.VideoBitRate.Value)
  679. {
  680. return false;
  681. }
  682. }
  683. if (request.MaxVideoBitDepth.HasValue)
  684. {
  685. if (videoStream.BitDepth.HasValue && videoStream.BitDepth.Value > request.MaxVideoBitDepth.Value)
  686. {
  687. return false;
  688. }
  689. }
  690. if (request.MaxRefFrames.HasValue)
  691. {
  692. if (videoStream.RefFrames.HasValue && videoStream.RefFrames.Value > request.MaxRefFrames.Value)
  693. {
  694. return false;
  695. }
  696. }
  697. // If a specific level was requested, the source must match or be less than
  698. if (!string.IsNullOrEmpty(request.Level))
  699. {
  700. double requestLevel;
  701. if (double.TryParse(request.Level, NumberStyles.Any, _usCulture, out requestLevel))
  702. {
  703. if (!videoStream.Level.HasValue)
  704. {
  705. //return false;
  706. }
  707. if (videoStream.Level.HasValue && videoStream.Level.Value > requestLevel)
  708. {
  709. return false;
  710. }
  711. }
  712. }
  713. return request.EnableAutoStreamCopy;
  714. }
  715. public bool CanStreamCopyAudio(EncodingJobInfo state, MediaStream audioStream, List<string> supportedAudioCodecs)
  716. {
  717. var request = state.BaseRequest;
  718. // Source and target codecs must match
  719. if (string.IsNullOrEmpty(audioStream.Codec) || !supportedAudioCodecs.Contains(audioStream.Codec, StringComparer.OrdinalIgnoreCase))
  720. {
  721. return false;
  722. }
  723. // Video bitrate must fall within requested value
  724. if (request.AudioBitRate.HasValue)
  725. {
  726. if (!audioStream.BitRate.HasValue || audioStream.BitRate.Value <= 0)
  727. {
  728. return false;
  729. }
  730. if (audioStream.BitRate.Value > request.AudioBitRate.Value)
  731. {
  732. return false;
  733. }
  734. }
  735. // Channels must fall within requested value
  736. var channels = request.AudioChannels ?? request.MaxAudioChannels;
  737. if (channels.HasValue)
  738. {
  739. if (!audioStream.Channels.HasValue || audioStream.Channels.Value <= 0)
  740. {
  741. return false;
  742. }
  743. if (audioStream.Channels.Value > channels.Value)
  744. {
  745. return false;
  746. }
  747. }
  748. // Sample rate must fall within requested value
  749. if (request.AudioSampleRate.HasValue)
  750. {
  751. if (!audioStream.SampleRate.HasValue || audioStream.SampleRate.Value <= 0)
  752. {
  753. return false;
  754. }
  755. if (audioStream.SampleRate.Value > request.AudioSampleRate.Value)
  756. {
  757. return false;
  758. }
  759. }
  760. return request.EnableAutoStreamCopy;
  761. }
  762. public int? GetVideoBitrateParamValue(BaseEncodingJobOptions request, MediaStream videoStream, string outputVideoCodec)
  763. {
  764. var bitrate = request.VideoBitRate;
  765. if (videoStream != null)
  766. {
  767. var isUpscaling = request.Height.HasValue && videoStream.Height.HasValue &&
  768. request.Height.Value > videoStream.Height.Value;
  769. if (request.Width.HasValue && videoStream.Width.HasValue &&
  770. request.Width.Value > videoStream.Width.Value)
  771. {
  772. isUpscaling = true;
  773. }
  774. // Don't allow bitrate increases unless upscaling
  775. if (!isUpscaling)
  776. {
  777. if (bitrate.HasValue && videoStream.BitRate.HasValue)
  778. {
  779. bitrate = Math.Min(bitrate.Value, videoStream.BitRate.Value);
  780. }
  781. }
  782. }
  783. if (bitrate.HasValue)
  784. {
  785. var inputVideoCodec = videoStream == null ? null : videoStream.Codec;
  786. bitrate = ResolutionNormalizer.ScaleBitrate(bitrate.Value, inputVideoCodec, outputVideoCodec);
  787. // If a max bitrate was requested, don't let the scaled bitrate exceed it
  788. if (request.VideoBitRate.HasValue)
  789. {
  790. bitrate = Math.Min(bitrate.Value, request.VideoBitRate.Value);
  791. }
  792. }
  793. return bitrate;
  794. }
  795. public int? GetAudioBitrateParam(BaseEncodingJobOptions request, MediaStream audioStream)
  796. {
  797. if (request.AudioBitRate.HasValue)
  798. {
  799. // Make sure we don't request a bitrate higher than the source
  800. var currentBitrate = audioStream == null ? request.AudioBitRate.Value : audioStream.BitRate ?? request.AudioBitRate.Value;
  801. // Don't encode any higher than this
  802. return Math.Min(384000, request.AudioBitRate.Value);
  803. //return Math.Min(currentBitrate, request.AudioBitRate.Value);
  804. }
  805. return null;
  806. }
  807. public string GetAudioFilterParam(EncodingJobInfo state, EncodingOptions encodingOptions, bool isHls)
  808. {
  809. var volParam = string.Empty;
  810. var audioSampleRate = string.Empty;
  811. var channels = state.OutputAudioChannels;
  812. // Boost volume to 200% when downsampling from 6ch to 2ch
  813. if (channels.HasValue && channels.Value <= 2)
  814. {
  815. if (state.AudioStream != null && state.AudioStream.Channels.HasValue && state.AudioStream.Channels.Value > 5 && !encodingOptions.DownMixAudioBoost.Equals(1))
  816. {
  817. volParam = ",volume=" + encodingOptions.DownMixAudioBoost.ToString(_usCulture);
  818. }
  819. }
  820. if (state.OutputAudioSampleRate.HasValue)
  821. {
  822. audioSampleRate = state.OutputAudioSampleRate.Value + ":";
  823. }
  824. var adelay = isHls ? "adelay=1," : string.Empty;
  825. var pts = string.Empty;
  826. if (state.SubtitleStream != null && state.SubtitleStream.IsTextSubtitleStream && state.BaseRequest.SubtitleMethod == SubtitleDeliveryMethod.Encode && !state.CopyTimestamps)
  827. {
  828. var seconds = TimeSpan.FromTicks(state.StartTimeTicks ?? 0).TotalSeconds;
  829. pts = string.Format(",asetpts=PTS-{0}/TB", Math.Round(seconds).ToString(_usCulture));
  830. }
  831. return string.Format("-af \"{0}aresample={1}async={4}{2}{3}\"",
  832. adelay,
  833. audioSampleRate,
  834. volParam,
  835. pts,
  836. state.OutputAudioSync);
  837. }
  838. /// <summary>
  839. /// Gets the number of audio channels to specify on the command line
  840. /// </summary>
  841. /// <param name="request">The request.</param>
  842. /// <param name="audioStream">The audio stream.</param>
  843. /// <param name="outputAudioCodec">The output audio codec.</param>
  844. /// <returns>System.Nullable{System.Int32}.</returns>
  845. public int? GetNumAudioChannelsParam(BaseEncodingJobOptions request, MediaStream audioStream, string outputAudioCodec)
  846. {
  847. var inputChannels = audioStream == null
  848. ? null
  849. : audioStream.Channels;
  850. if (inputChannels <= 0)
  851. {
  852. inputChannels = null;
  853. }
  854. int? transcoderChannelLimit = null;
  855. var codec = outputAudioCodec ?? string.Empty;
  856. if (codec.IndexOf("wma", StringComparison.OrdinalIgnoreCase) != -1)
  857. {
  858. // wmav2 currently only supports two channel output
  859. transcoderChannelLimit = 2;
  860. }
  861. else if (codec.IndexOf("mp3", StringComparison.OrdinalIgnoreCase) != -1)
  862. {
  863. // libmp3lame currently only supports two channel output
  864. transcoderChannelLimit = 2;
  865. }
  866. else
  867. {
  868. // If we don't have any media info then limit it to 6 to prevent encoding errors due to asking for too many channels
  869. transcoderChannelLimit = 6;
  870. }
  871. var isTranscodingAudio = !string.Equals(codec, "copy", StringComparison.OrdinalIgnoreCase);
  872. int? resultChannels = null;
  873. if (isTranscodingAudio)
  874. {
  875. resultChannels = request.TranscodingMaxAudioChannels;
  876. }
  877. resultChannels = resultChannels ?? request.MaxAudioChannels ?? request.AudioChannels;
  878. if (inputChannels.HasValue)
  879. {
  880. resultChannels = resultChannels.HasValue
  881. ? Math.Min(resultChannels.Value, inputChannels.Value)
  882. : inputChannels.Value;
  883. }
  884. if (isTranscodingAudio && transcoderChannelLimit.HasValue)
  885. {
  886. resultChannels = resultChannels.HasValue
  887. ? Math.Min(resultChannels.Value, transcoderChannelLimit.Value)
  888. : transcoderChannelLimit.Value;
  889. }
  890. return resultChannels ?? request.AudioChannels;
  891. }
  892. /// <summary>
  893. /// Enforces the resolution limit.
  894. /// </summary>
  895. /// <param name="state">The state.</param>
  896. public void EnforceResolutionLimit(EncodingJobInfo state)
  897. {
  898. var videoRequest = state.BaseRequest;
  899. // Switch the incoming params to be ceilings rather than fixed values
  900. videoRequest.MaxWidth = videoRequest.MaxWidth ?? videoRequest.Width;
  901. videoRequest.MaxHeight = videoRequest.MaxHeight ?? videoRequest.Height;
  902. videoRequest.Width = null;
  903. videoRequest.Height = null;
  904. }
  905. /// <summary>
  906. /// Gets the fast seek command line parameter.
  907. /// </summary>
  908. /// <param name="request">The request.</param>
  909. /// <returns>System.String.</returns>
  910. /// <value>The fast seek command line parameter.</value>
  911. public string GetFastSeekCommandLineParameter(BaseEncodingJobOptions request)
  912. {
  913. var time = request.StartTimeTicks ?? 0;
  914. if (time > 0)
  915. {
  916. return string.Format("-ss {0}", _mediaEncoder.GetTimeParameter(time));
  917. }
  918. return string.Empty;
  919. }
  920. /// <summary>
  921. /// Gets the map args.
  922. /// </summary>
  923. /// <param name="state">The state.</param>
  924. /// <returns>System.String.</returns>
  925. public string GetMapArgs(EncodingJobInfo state)
  926. {
  927. // If we don't have known media info
  928. // If input is video, use -sn to drop subtitles
  929. // Otherwise just return empty
  930. if (state.VideoStream == null && state.AudioStream == null)
  931. {
  932. return state.IsInputVideo ? "-sn" : string.Empty;
  933. }
  934. // We have media info, but we don't know the stream indexes
  935. if (state.VideoStream != null && state.VideoStream.Index == -1)
  936. {
  937. return "-sn";
  938. }
  939. // We have media info, but we don't know the stream indexes
  940. if (state.AudioStream != null && state.AudioStream.Index == -1)
  941. {
  942. return state.IsInputVideo ? "-sn" : string.Empty;
  943. }
  944. var args = string.Empty;
  945. if (state.VideoStream != null)
  946. {
  947. args += string.Format("-map 0:{0}", state.VideoStream.Index);
  948. }
  949. else
  950. {
  951. // No known video stream
  952. args += "-vn";
  953. }
  954. if (state.AudioStream != null)
  955. {
  956. args += string.Format(" -map 0:{0}", state.AudioStream.Index);
  957. }
  958. else
  959. {
  960. args += " -map -0:a";
  961. }
  962. var subtitleMethod = state.BaseRequest.SubtitleMethod;
  963. if (state.SubtitleStream == null || subtitleMethod == SubtitleDeliveryMethod.Hls)
  964. {
  965. args += " -map -0:s";
  966. }
  967. else if (subtitleMethod == SubtitleDeliveryMethod.Embed)
  968. {
  969. args += string.Format(" -map 0:{0}", state.SubtitleStream.Index);
  970. }
  971. else if (state.SubtitleStream.IsExternal && !state.SubtitleStream.IsTextSubtitleStream)
  972. {
  973. args += " -map 1:0 -sn";
  974. }
  975. return args;
  976. }
  977. /// <summary>
  978. /// Determines which stream will be used for playback
  979. /// </summary>
  980. /// <param name="allStream">All stream.</param>
  981. /// <param name="desiredIndex">Index of the desired.</param>
  982. /// <param name="type">The type.</param>
  983. /// <param name="returnFirstIfNoIndex">if set to <c>true</c> [return first if no index].</param>
  984. /// <returns>MediaStream.</returns>
  985. public MediaStream GetMediaStream(IEnumerable<MediaStream> allStream, int? desiredIndex, MediaStreamType type, bool returnFirstIfNoIndex = true)
  986. {
  987. var streams = allStream.Where(s => s.Type == type).OrderBy(i => i.Index).ToList();
  988. if (desiredIndex.HasValue)
  989. {
  990. var stream = streams.FirstOrDefault(s => s.Index == desiredIndex.Value);
  991. if (stream != null)
  992. {
  993. return stream;
  994. }
  995. }
  996. if (type == MediaStreamType.Video)
  997. {
  998. streams = streams.Where(i => !string.Equals(i.Codec, "mjpeg", StringComparison.OrdinalIgnoreCase)).ToList();
  999. }
  1000. if (returnFirstIfNoIndex && type == MediaStreamType.Audio)
  1001. {
  1002. return streams.FirstOrDefault(i => i.Channels.HasValue && i.Channels.Value > 0) ??
  1003. streams.FirstOrDefault();
  1004. }
  1005. // Just return the first one
  1006. return returnFirstIfNoIndex ? streams.FirstOrDefault() : null;
  1007. }
  1008. /// <summary>
  1009. /// Gets the internal graphical subtitle param.
  1010. /// </summary>
  1011. /// <param name="state">The state.</param>
  1012. /// <param name="outputVideoCodec">The output video codec.</param>
  1013. /// <returns>System.String.</returns>
  1014. public string GetGraphicalSubtitleParam(EncodingJobInfo state, string outputVideoCodec)
  1015. {
  1016. var outputSizeParam = string.Empty;
  1017. var request = state.BaseRequest;
  1018. // Add resolution params, if specified
  1019. if (request.Width.HasValue || request.Height.HasValue || request.MaxHeight.HasValue || request.MaxWidth.HasValue)
  1020. {
  1021. outputSizeParam = GetOutputSizeParam(state, outputVideoCodec).TrimEnd('"');
  1022. if (string.Equals(outputVideoCodec, "h264_vaapi", StringComparison.OrdinalIgnoreCase))
  1023. {
  1024. outputSizeParam = "," + outputSizeParam.Substring(outputSizeParam.IndexOf("format", StringComparison.OrdinalIgnoreCase));
  1025. }
  1026. else
  1027. {
  1028. outputSizeParam = "," + outputSizeParam.Substring(outputSizeParam.IndexOf("scale", StringComparison.OrdinalIgnoreCase));
  1029. }
  1030. }
  1031. if (string.Equals(outputVideoCodec, "h264_vaapi", StringComparison.OrdinalIgnoreCase) && outputSizeParam.Length == 0)
  1032. {
  1033. outputSizeParam = ",format=nv12|vaapi,hwupload";
  1034. }
  1035. var videoSizeParam = string.Empty;
  1036. if (state.VideoStream != null && state.VideoStream.Width.HasValue && state.VideoStream.Height.HasValue)
  1037. {
  1038. videoSizeParam = string.Format("scale={0}:{1}", state.VideoStream.Width.Value.ToString(_usCulture), state.VideoStream.Height.Value.ToString(_usCulture));
  1039. }
  1040. var mapPrefix = state.SubtitleStream.IsExternal ?
  1041. 1 :
  1042. 0;
  1043. var subtitleStreamIndex = state.SubtitleStream.IsExternal
  1044. ? 0
  1045. : state.SubtitleStream.Index;
  1046. return string.Format(" -filter_complex \"[{0}:{1}]{4}[sub] ; [0:{2}] [sub] overlay{3}\"",
  1047. mapPrefix.ToString(_usCulture),
  1048. subtitleStreamIndex.ToString(_usCulture),
  1049. state.VideoStream.Index.ToString(_usCulture),
  1050. outputSizeParam,
  1051. videoSizeParam);
  1052. }
  1053. /// <summary>
  1054. /// If we're going to put a fixed size on the command line, this will calculate it
  1055. /// </summary>
  1056. /// <param name="state">The state.</param>
  1057. /// <param name="outputVideoCodec">The output video codec.</param>
  1058. /// <param name="allowTimeStampCopy">if set to <c>true</c> [allow time stamp copy].</param>
  1059. /// <returns>System.String.</returns>
  1060. public string GetOutputSizeParam(EncodingJobInfo state,
  1061. string outputVideoCodec,
  1062. bool allowTimeStampCopy = true)
  1063. {
  1064. // http://sonnati.wordpress.com/2012/10/19/ffmpeg-the-swiss-army-knife-of-internet-streaming-part-vi/
  1065. var request = state.BaseRequest;
  1066. var filters = new List<string>();
  1067. if (string.Equals(outputVideoCodec, "h264_vaapi", StringComparison.OrdinalIgnoreCase))
  1068. {
  1069. filters.Add("format=nv12|vaapi");
  1070. filters.Add("hwupload");
  1071. }
  1072. else if (state.DeInterlace && !string.Equals(outputVideoCodec, "h264_vaapi", StringComparison.OrdinalIgnoreCase))
  1073. {
  1074. filters.Add("yadif=0:-1:0");
  1075. }
  1076. if (string.Equals(outputVideoCodec, "h264_vaapi", StringComparison.OrdinalIgnoreCase))
  1077. {
  1078. // Work around vaapi's reduced scaling features
  1079. var scaler = "scale_vaapi";
  1080. // Given the input dimensions (inputWidth, inputHeight), determine the output dimensions
  1081. // (outputWidth, outputHeight). The user may request precise output dimensions or maximum
  1082. // output dimensions. Output dimensions are guaranteed to be even.
  1083. decimal inputWidth = Convert.ToDecimal(state.VideoStream.Width);
  1084. decimal inputHeight = Convert.ToDecimal(state.VideoStream.Height);
  1085. decimal outputWidth = request.Width.HasValue ? Convert.ToDecimal(request.Width.Value) : inputWidth;
  1086. decimal outputHeight = request.Height.HasValue ? Convert.ToDecimal(request.Height.Value) : inputHeight;
  1087. decimal maximumWidth = request.MaxWidth.HasValue ? Convert.ToDecimal(request.MaxWidth.Value) : outputWidth;
  1088. decimal maximumHeight = request.MaxHeight.HasValue ? Convert.ToDecimal(request.MaxHeight.Value) : outputHeight;
  1089. if (outputWidth > maximumWidth || outputHeight > maximumHeight)
  1090. {
  1091. var scale = Math.Min(maximumWidth / outputWidth, maximumHeight / outputHeight);
  1092. outputWidth = Math.Min(maximumWidth, Math.Truncate(outputWidth * scale));
  1093. outputHeight = Math.Min(maximumHeight, Math.Truncate(outputHeight * scale));
  1094. }
  1095. outputWidth = 2 * Math.Truncate(outputWidth / 2);
  1096. outputHeight = 2 * Math.Truncate(outputHeight / 2);
  1097. if (outputWidth != inputWidth || outputHeight != inputHeight)
  1098. {
  1099. filters.Add(string.Format("{0}=w={1}:h={2}", scaler, outputWidth.ToString(_usCulture), outputHeight.ToString(_usCulture)));
  1100. }
  1101. }
  1102. else
  1103. {
  1104. // If fixed dimensions were supplied
  1105. if (request.Width.HasValue && request.Height.HasValue)
  1106. {
  1107. var widthParam = request.Width.Value.ToString(_usCulture);
  1108. var heightParam = request.Height.Value.ToString(_usCulture);
  1109. filters.Add(string.Format("scale=trunc({0}/2)*2:trunc({1}/2)*2", widthParam, heightParam));
  1110. }
  1111. // 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
  1112. else if (request.MaxWidth.HasValue && request.MaxHeight.HasValue)
  1113. {
  1114. var maxWidthParam = request.MaxWidth.Value.ToString(_usCulture);
  1115. var maxHeightParam = request.MaxHeight.Value.ToString(_usCulture);
  1116. 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));
  1117. }
  1118. // If a fixed width was requested
  1119. else if (request.Width.HasValue)
  1120. {
  1121. var widthParam = request.Width.Value.ToString(_usCulture);
  1122. filters.Add(string.Format("scale={0}:trunc(ow/a/2)*2", widthParam));
  1123. }
  1124. // If a fixed height was requested
  1125. else if (request.Height.HasValue)
  1126. {
  1127. var heightParam = request.Height.Value.ToString(_usCulture);
  1128. filters.Add(string.Format("scale=trunc(oh*a/2)*2:{0}", heightParam));
  1129. }
  1130. // If a max width was requested
  1131. else if (request.MaxWidth.HasValue)
  1132. {
  1133. var maxWidthParam = request.MaxWidth.Value.ToString(_usCulture);
  1134. filters.Add(string.Format("scale=trunc(min(max(iw\\,ih*dar)\\,{0})/2)*2:trunc(ow/dar/2)*2", maxWidthParam));
  1135. }
  1136. // If a max height was requested
  1137. else if (request.MaxHeight.HasValue)
  1138. {
  1139. var maxHeightParam = request.MaxHeight.Value.ToString(_usCulture);
  1140. filters.Add(string.Format("scale=trunc(oh*a/2)*2:min(max(iw/dar\\,ih)\\,{0})", maxHeightParam));
  1141. }
  1142. }
  1143. var output = string.Empty;
  1144. if (state.SubtitleStream != null && state.SubtitleStream.IsTextSubtitleStream && request.SubtitleMethod == SubtitleDeliveryMethod.Encode)
  1145. {
  1146. var subParam = GetTextSubtitleParam(state);
  1147. filters.Add(subParam);
  1148. if (allowTimeStampCopy)
  1149. {
  1150. output += " -copyts";
  1151. }
  1152. }
  1153. if (filters.Count > 0)
  1154. {
  1155. output += string.Format(" -vf \"{0}\"", string.Join(",", filters.ToArray()));
  1156. }
  1157. return output;
  1158. }
  1159. /// <summary>
  1160. /// Gets the number of threads.
  1161. /// </summary>
  1162. /// <returns>System.Int32.</returns>
  1163. public int GetNumberOfThreads(EncodingJobInfo state, EncodingOptions encodingOptions, bool isWebm)
  1164. {
  1165. var threads = GetNumberOfThreadsInternal(state, encodingOptions, isWebm);
  1166. if (state.BaseRequest.CpuCoreLimit.HasValue && state.BaseRequest.CpuCoreLimit.Value > 0)
  1167. {
  1168. threads = Math.Min(threads, state.BaseRequest.CpuCoreLimit.Value);
  1169. }
  1170. return threads;
  1171. }
  1172. public void TryStreamCopy(EncodingJobInfo state)
  1173. {
  1174. if (state.VideoStream != null && CanStreamCopyVideo(state, state.VideoStream))
  1175. {
  1176. state.OutputVideoCodec = "copy";
  1177. }
  1178. else
  1179. {
  1180. var user = state.User;
  1181. // If the user doesn't have access to transcoding, then force stream copy, regardless of whether it will be compatible or not
  1182. if (user != null && !user.Policy.EnableVideoPlaybackTranscoding)
  1183. {
  1184. state.OutputVideoCodec = "copy";
  1185. }
  1186. }
  1187. if (state.AudioStream != null && CanStreamCopyAudio(state, state.AudioStream, state.SupportedAudioCodecs))
  1188. {
  1189. state.OutputAudioCodec = "copy";
  1190. }
  1191. else
  1192. {
  1193. var user = state.User;
  1194. // If the user doesn't have access to transcoding, then force stream copy, regardless of whether it will be compatible or not
  1195. if (user != null && !user.Policy.EnableAudioPlaybackTranscoding)
  1196. {
  1197. state.OutputAudioCodec = "copy";
  1198. }
  1199. }
  1200. }
  1201. public string GetInputModifier(EncodingJobInfo state, EncodingOptions encodingOptions)
  1202. {
  1203. var inputModifier = string.Empty;
  1204. var probeSize = GetProbeSizeArgument(state);
  1205. inputModifier += " " + probeSize;
  1206. inputModifier = inputModifier.Trim();
  1207. var userAgentParam = GetUserAgentParam(state);
  1208. if (!string.IsNullOrWhiteSpace(userAgentParam))
  1209. {
  1210. inputModifier += " " + userAgentParam;
  1211. }
  1212. inputModifier = inputModifier.Trim();
  1213. inputModifier += " " + GetFastSeekCommandLineParameter(state.BaseRequest);
  1214. inputModifier = inputModifier.Trim();
  1215. //inputModifier += " -fflags +genpts+ignidx+igndts";
  1216. //if (state.IsVideoRequest && genPts)
  1217. //{
  1218. // inputModifier += " -fflags +genpts";
  1219. //}
  1220. if (!string.IsNullOrEmpty(state.InputAudioSync))
  1221. {
  1222. inputModifier += " -async " + state.InputAudioSync;
  1223. }
  1224. if (!string.IsNullOrEmpty(state.InputVideoSync))
  1225. {
  1226. inputModifier += " -vsync " + state.InputVideoSync;
  1227. }
  1228. if (state.ReadInputAtNativeFramerate)
  1229. {
  1230. inputModifier += " -re";
  1231. }
  1232. var videoDecoder = GetVideoDecoder(state, encodingOptions);
  1233. if (!string.IsNullOrWhiteSpace(videoDecoder))
  1234. {
  1235. inputModifier += " " + videoDecoder;
  1236. }
  1237. if (state.IsVideoRequest)
  1238. {
  1239. // Important: If this is ever re-enabled, make sure not to use it with wtv because it breaks seeking
  1240. if (string.Equals(state.OutputContainer, "mkv", StringComparison.OrdinalIgnoreCase) && state.CopyTimestamps)
  1241. {
  1242. //inputModifier += " -noaccurate_seek";
  1243. }
  1244. if (!string.IsNullOrWhiteSpace(state.InputContainer))
  1245. {
  1246. var inputFormat = GetInputFormat(state.InputContainer);
  1247. if (!string.IsNullOrWhiteSpace(inputFormat))
  1248. {
  1249. inputModifier += " -f " + inputFormat;
  1250. }
  1251. }
  1252. if (state.RunTimeTicks.HasValue)
  1253. {
  1254. foreach (var stream in state.MediaSource.MediaStreams)
  1255. {
  1256. if (!stream.IsExternal && stream.Type != MediaStreamType.Subtitle)
  1257. {
  1258. if (!string.IsNullOrWhiteSpace(stream.Codec) && stream.Index != -1)
  1259. {
  1260. var decoder = GetDecoderFromCodec(stream.Codec);
  1261. if (!string.IsNullOrWhiteSpace(decoder))
  1262. {
  1263. inputModifier += " -codec:" + stream.Index.ToString(_usCulture) + " " + decoder;
  1264. }
  1265. }
  1266. }
  1267. }
  1268. }
  1269. }
  1270. return inputModifier;
  1271. }
  1272. public void AttachMediaSourceInfo(EncodingJobInfo state,
  1273. MediaSourceInfo mediaSource,
  1274. string requestedUrl)
  1275. {
  1276. state.MediaPath = mediaSource.Path;
  1277. state.InputProtocol = mediaSource.Protocol;
  1278. state.InputContainer = mediaSource.Container;
  1279. state.RunTimeTicks = mediaSource.RunTimeTicks;
  1280. state.RemoteHttpHeaders = mediaSource.RequiredHttpHeaders;
  1281. if (mediaSource.VideoType.HasValue)
  1282. {
  1283. state.VideoType = mediaSource.VideoType.Value;
  1284. }
  1285. state.IsoType = mediaSource.IsoType;
  1286. state.PlayableStreamFileNames = mediaSource.PlayableStreamFileNames.ToList();
  1287. if (mediaSource.Timestamp.HasValue)
  1288. {
  1289. state.InputTimestamp = mediaSource.Timestamp.Value;
  1290. }
  1291. state.InputProtocol = mediaSource.Protocol;
  1292. state.MediaPath = mediaSource.Path;
  1293. state.RunTimeTicks = mediaSource.RunTimeTicks;
  1294. state.RemoteHttpHeaders = mediaSource.RequiredHttpHeaders;
  1295. state.ReadInputAtNativeFramerate = mediaSource.ReadAtNativeFramerate;
  1296. if (state.ReadInputAtNativeFramerate ||
  1297. mediaSource.Protocol == MediaProtocol.File && string.Equals(mediaSource.Container, "wtv", StringComparison.OrdinalIgnoreCase))
  1298. {
  1299. state.OutputAudioSync = "1000";
  1300. state.InputVideoSync = "-1";
  1301. state.InputAudioSync = "1";
  1302. }
  1303. if (string.Equals(mediaSource.Container, "wma", StringComparison.OrdinalIgnoreCase))
  1304. {
  1305. // Seeing some stuttering when transcoding wma to audio-only HLS
  1306. state.InputAudioSync = "1";
  1307. }
  1308. var mediaStreams = mediaSource.MediaStreams;
  1309. if (state.IsVideoRequest)
  1310. {
  1311. var videoRequest = state.BaseRequest;
  1312. if (string.IsNullOrEmpty(videoRequest.VideoCodec))
  1313. {
  1314. if (string.IsNullOrWhiteSpace(requestedUrl))
  1315. {
  1316. requestedUrl = "test." + videoRequest.OutputContainer;
  1317. }
  1318. videoRequest.VideoCodec = InferVideoCodec(requestedUrl);
  1319. }
  1320. state.VideoStream = GetMediaStream(mediaStreams, videoRequest.VideoStreamIndex, MediaStreamType.Video);
  1321. state.SubtitleStream = GetMediaStream(mediaStreams, videoRequest.SubtitleStreamIndex, MediaStreamType.Subtitle, false);
  1322. state.SubtitleDeliveryMethod = videoRequest.SubtitleMethod;
  1323. state.AudioStream = GetMediaStream(mediaStreams, videoRequest.AudioStreamIndex, MediaStreamType.Audio);
  1324. if (state.SubtitleStream != null && !state.SubtitleStream.IsExternal)
  1325. {
  1326. state.InternalSubtitleStreamOffset = mediaStreams.Where(i => i.Type == MediaStreamType.Subtitle && !i.IsExternal).ToList().IndexOf(state.SubtitleStream);
  1327. }
  1328. if (state.VideoStream != null && state.VideoStream.IsInterlaced)
  1329. {
  1330. state.DeInterlace = true;
  1331. }
  1332. EnforceResolutionLimit(state);
  1333. }
  1334. else
  1335. {
  1336. state.AudioStream = GetMediaStream(mediaStreams, null, MediaStreamType.Audio, true);
  1337. }
  1338. state.MediaSource = mediaSource;
  1339. }
  1340. /// <summary>
  1341. /// Gets the name of the output video codec
  1342. /// </summary>
  1343. protected string GetVideoDecoder(EncodingJobInfo state, EncodingOptions encodingOptions)
  1344. {
  1345. if (string.Equals(state.OutputVideoCodec, "copy", StringComparison.OrdinalIgnoreCase))
  1346. {
  1347. return null;
  1348. }
  1349. // Only use alternative encoders for video files.
  1350. // When using concat with folder rips, if the mfx session fails to initialize, ffmpeg will be stuck retrying and will not exit gracefully
  1351. // Since transcoding of folder rips is expiremental anyway, it's not worth adding additional variables such as this.
  1352. if (state.VideoType != VideoType.VideoFile)
  1353. {
  1354. return null;
  1355. }
  1356. if (state.VideoStream != null && !string.IsNullOrWhiteSpace(state.VideoStream.Codec))
  1357. {
  1358. if (string.Equals(encodingOptions.HardwareAccelerationType, "qsv", StringComparison.OrdinalIgnoreCase))
  1359. {
  1360. switch (state.MediaSource.VideoStream.Codec.ToLower())
  1361. {
  1362. case "avc":
  1363. case "h264":
  1364. if (_mediaEncoder.SupportsDecoder("h264_qsv"))
  1365. {
  1366. return "-c:v h264_qsv ";
  1367. }
  1368. break;
  1369. case "mpeg2video":
  1370. if (_mediaEncoder.SupportsDecoder("mpeg2_qsv"))
  1371. {
  1372. return "-c:v mpeg2_qsv ";
  1373. }
  1374. break;
  1375. case "vc1":
  1376. if (_mediaEncoder.SupportsDecoder("vc1_qsv"))
  1377. {
  1378. return "-c:v vc1_qsv ";
  1379. }
  1380. break;
  1381. }
  1382. }
  1383. }
  1384. // leave blank so ffmpeg will decide
  1385. return null;
  1386. }
  1387. /// <summary>
  1388. /// Gets the number of threads.
  1389. /// </summary>
  1390. /// <returns>System.Int32.</returns>
  1391. private int GetNumberOfThreadsInternal(EncodingJobInfo state, EncodingOptions encodingOptions, bool isWebm)
  1392. {
  1393. var threads = encodingOptions.EncodingThreadCount;
  1394. if (isWebm)
  1395. {
  1396. // Recommended per docs
  1397. return Math.Max(Environment.ProcessorCount - 1, 2);
  1398. }
  1399. // Automatic
  1400. if (threads == -1)
  1401. {
  1402. return 0;
  1403. }
  1404. return threads;
  1405. }
  1406. }
  1407. }