EncodingHelper.cs 63 KB

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