EncodingHelper.cs 130 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Globalization;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Runtime.InteropServices;
  7. using System.Text;
  8. using System.Threading;
  9. using Jellyfin.Data.Enums;
  10. using MediaBrowser.Controller.Entities;
  11. using MediaBrowser.Controller.Extensions;
  12. using MediaBrowser.Model.Configuration;
  13. using MediaBrowser.Model.Dlna;
  14. using MediaBrowser.Model.Dto;
  15. using MediaBrowser.Model.Entities;
  16. using MediaBrowser.Model.IO;
  17. using MediaBrowser.Model.MediaInfo;
  18. using Microsoft.Extensions.Configuration;
  19. namespace MediaBrowser.Controller.MediaEncoding
  20. {
  21. public class EncodingHelper
  22. {
  23. private readonly CultureInfo _usCulture = new CultureInfo("en-US");
  24. private readonly IMediaEncoder _mediaEncoder;
  25. private readonly IFileSystem _fileSystem;
  26. private readonly ISubtitleEncoder _subtitleEncoder;
  27. private readonly IConfiguration _configuration;
  28. private static readonly string[] _videoProfiles = new[]
  29. {
  30. "ConstrainedBaseline",
  31. "Baseline",
  32. "Extended",
  33. "Main",
  34. "High",
  35. "ProgressiveHigh",
  36. "ConstrainedHigh"
  37. };
  38. public EncodingHelper(
  39. IMediaEncoder mediaEncoder,
  40. IFileSystem fileSystem,
  41. ISubtitleEncoder subtitleEncoder,
  42. IConfiguration configuration)
  43. {
  44. _mediaEncoder = mediaEncoder;
  45. _fileSystem = fileSystem;
  46. _subtitleEncoder = subtitleEncoder;
  47. _configuration = configuration;
  48. }
  49. public string GetH264Encoder(EncodingJobInfo state, EncodingOptions encodingOptions)
  50. => GetH264OrH265Encoder("libx264", "h264", state, encodingOptions);
  51. public string GetH265Encoder(EncodingJobInfo state, EncodingOptions encodingOptions)
  52. => GetH264OrH265Encoder("libx265", "hevc", state, encodingOptions);
  53. private string GetH264OrH265Encoder(string defaultEncoder, string hwEncoder, EncodingJobInfo state, EncodingOptions encodingOptions)
  54. {
  55. // Only use alternative encoders for video files.
  56. // When using concat with folder rips, if the mfx session fails to initialize, ffmpeg will be stuck retrying and will not exit gracefully
  57. // Since transcoding of folder rips is expiremental anyway, it's not worth adding additional variables such as this.
  58. if (state.VideoType == VideoType.VideoFile)
  59. {
  60. var hwType = encodingOptions.HardwareAccelerationType;
  61. var codecMap = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
  62. {
  63. {"qsv", hwEncoder + "_qsv"},
  64. {hwEncoder + "_qsv", hwEncoder + "_qsv"},
  65. {"nvenc", hwEncoder + "_nvenc"},
  66. {"amf", hwEncoder + "_amf"},
  67. {"omx", hwEncoder + "_omx"},
  68. {hwEncoder + "_v4l2m2m", hwEncoder + "_v4l2m2m"},
  69. {"mediacodec", hwEncoder + "_mediacodec"},
  70. {"vaapi", hwEncoder + "_vaapi"},
  71. {"videotoolbox", hwEncoder + "_videotoolbox"}
  72. };
  73. if (!string.IsNullOrEmpty(hwType)
  74. && encodingOptions.EnableHardwareEncoding
  75. && codecMap.ContainsKey(hwType))
  76. {
  77. var preferredEncoder = codecMap[hwType];
  78. if (_mediaEncoder.SupportsEncoder(preferredEncoder))
  79. {
  80. return preferredEncoder;
  81. }
  82. }
  83. }
  84. return defaultEncoder;
  85. }
  86. private bool IsVaapiSupported(EncodingJobInfo state)
  87. {
  88. var videoStream = state.VideoStream;
  89. // vaapi will throw an error with this input
  90. // [vaapi @ 0x7faed8000960] No VAAPI support for codec mpeg4 profile -99.
  91. if (string.Equals(videoStream?.Codec, "mpeg4", StringComparison.OrdinalIgnoreCase))
  92. {
  93. return false;
  94. }
  95. return _mediaEncoder.SupportsHwaccel("vaapi");
  96. }
  97. /// <summary>
  98. /// Gets the name of the output video codec.
  99. /// </summary>
  100. public string GetVideoEncoder(EncodingJobInfo state, EncodingOptions encodingOptions)
  101. {
  102. var codec = state.OutputVideoCodec;
  103. if (!string.IsNullOrEmpty(codec))
  104. {
  105. if (string.Equals(codec, "h265", StringComparison.OrdinalIgnoreCase)
  106. || string.Equals(codec, "hevc", StringComparison.OrdinalIgnoreCase))
  107. {
  108. return GetH265Encoder(state, encodingOptions);
  109. }
  110. if (string.Equals(codec, "h264", StringComparison.OrdinalIgnoreCase))
  111. {
  112. return GetH264Encoder(state, encodingOptions);
  113. }
  114. if (string.Equals(codec, "vpx", StringComparison.OrdinalIgnoreCase))
  115. {
  116. return "libvpx";
  117. }
  118. if (string.Equals(codec, "wmv", StringComparison.OrdinalIgnoreCase))
  119. {
  120. return "wmv2";
  121. }
  122. if (string.Equals(codec, "theora", StringComparison.OrdinalIgnoreCase))
  123. {
  124. return "libtheora";
  125. }
  126. return codec.ToLowerInvariant();
  127. }
  128. return "copy";
  129. }
  130. /// <summary>
  131. /// Gets the user agent param.
  132. /// </summary>
  133. /// <param name="state">The state.</param>
  134. /// <returns>System.String.</returns>
  135. public string GetUserAgentParam(EncodingJobInfo state)
  136. {
  137. if (state.RemoteHttpHeaders.TryGetValue("User-Agent", out string useragent))
  138. {
  139. return "-user_agent \"" + useragent + "\"";
  140. }
  141. return string.Empty;
  142. }
  143. public static string GetInputFormat(string container)
  144. {
  145. if (string.IsNullOrEmpty(container))
  146. {
  147. return null;
  148. }
  149. container = container.Replace("mkv", "matroska", StringComparison.OrdinalIgnoreCase);
  150. if (string.Equals(container, "ts", StringComparison.OrdinalIgnoreCase))
  151. {
  152. return "mpegts";
  153. }
  154. // For these need to find out the ffmpeg names
  155. if (string.Equals(container, "m2ts", StringComparison.OrdinalIgnoreCase))
  156. {
  157. return null;
  158. }
  159. if (string.Equals(container, "wmv", StringComparison.OrdinalIgnoreCase))
  160. {
  161. return null;
  162. }
  163. if (string.Equals(container, "mts", StringComparison.OrdinalIgnoreCase))
  164. {
  165. return null;
  166. }
  167. if (string.Equals(container, "vob", StringComparison.OrdinalIgnoreCase))
  168. {
  169. return null;
  170. }
  171. if (string.Equals(container, "mpg", StringComparison.OrdinalIgnoreCase))
  172. {
  173. return null;
  174. }
  175. if (string.Equals(container, "mpeg", StringComparison.OrdinalIgnoreCase))
  176. {
  177. return null;
  178. }
  179. if (string.Equals(container, "rec", StringComparison.OrdinalIgnoreCase))
  180. {
  181. return null;
  182. }
  183. if (string.Equals(container, "dvr-ms", StringComparison.OrdinalIgnoreCase))
  184. {
  185. return null;
  186. }
  187. if (string.Equals(container, "ogm", StringComparison.OrdinalIgnoreCase))
  188. {
  189. return null;
  190. }
  191. if (string.Equals(container, "divx", StringComparison.OrdinalIgnoreCase))
  192. {
  193. return null;
  194. }
  195. if (string.Equals(container, "tp", StringComparison.OrdinalIgnoreCase))
  196. {
  197. return null;
  198. }
  199. if (string.Equals(container, "rmvb", StringComparison.OrdinalIgnoreCase))
  200. {
  201. return null;
  202. }
  203. if (string.Equals(container, "rtp", StringComparison.OrdinalIgnoreCase))
  204. {
  205. return null;
  206. }
  207. // Seeing reported failures here, not sure yet if this is related to specfying input format
  208. if (string.Equals(container, "m4v", StringComparison.OrdinalIgnoreCase))
  209. {
  210. return null;
  211. }
  212. // obviously don't do this for strm files
  213. if (string.Equals(container, "strm", StringComparison.OrdinalIgnoreCase))
  214. {
  215. return null;
  216. }
  217. return container;
  218. }
  219. public string GetDecoderFromCodec(string codec)
  220. {
  221. // For these need to find out the ffmpeg names
  222. if (string.Equals(codec, "mp2", StringComparison.OrdinalIgnoreCase))
  223. {
  224. return null;
  225. }
  226. if (string.Equals(codec, "aac_latm", StringComparison.OrdinalIgnoreCase))
  227. {
  228. return null;
  229. }
  230. if (string.Equals(codec, "eac3", StringComparison.OrdinalIgnoreCase))
  231. {
  232. return null;
  233. }
  234. if (_mediaEncoder.SupportsDecoder(codec))
  235. {
  236. return codec;
  237. }
  238. return null;
  239. }
  240. /// <summary>
  241. /// Infers the audio codec based on the url.
  242. /// </summary>
  243. public string InferAudioCodec(string container)
  244. {
  245. var ext = "." + (container ?? string.Empty);
  246. if (string.Equals(ext, ".mp3", StringComparison.OrdinalIgnoreCase))
  247. {
  248. return "mp3";
  249. }
  250. if (string.Equals(ext, ".aac", StringComparison.OrdinalIgnoreCase))
  251. {
  252. return "aac";
  253. }
  254. if (string.Equals(ext, ".wma", StringComparison.OrdinalIgnoreCase))
  255. {
  256. return "wma";
  257. }
  258. if (string.Equals(ext, ".ogg", StringComparison.OrdinalIgnoreCase))
  259. {
  260. return "vorbis";
  261. }
  262. if (string.Equals(ext, ".oga", StringComparison.OrdinalIgnoreCase))
  263. {
  264. return "vorbis";
  265. }
  266. if (string.Equals(ext, ".ogv", StringComparison.OrdinalIgnoreCase))
  267. {
  268. return "vorbis";
  269. }
  270. if (string.Equals(ext, ".webm", StringComparison.OrdinalIgnoreCase))
  271. {
  272. return "vorbis";
  273. }
  274. if (string.Equals(ext, ".webma", StringComparison.OrdinalIgnoreCase))
  275. {
  276. return "vorbis";
  277. }
  278. return "copy";
  279. }
  280. /// <summary>
  281. /// Infers the video codec.
  282. /// </summary>
  283. /// <param name="url">The URL.</param>
  284. /// <returns>System.Nullable{VideoCodecs}.</returns>
  285. public string InferVideoCodec(string url)
  286. {
  287. var ext = Path.GetExtension(url);
  288. if (string.Equals(ext, ".asf", StringComparison.OrdinalIgnoreCase))
  289. {
  290. return "wmv";
  291. }
  292. if (string.Equals(ext, ".webm", StringComparison.OrdinalIgnoreCase))
  293. {
  294. return "vpx";
  295. }
  296. if (string.Equals(ext, ".ogg", StringComparison.OrdinalIgnoreCase) || string.Equals(ext, ".ogv", StringComparison.OrdinalIgnoreCase))
  297. {
  298. return "theora";
  299. }
  300. if (string.Equals(ext, ".m3u8", StringComparison.OrdinalIgnoreCase) || string.Equals(ext, ".ts", StringComparison.OrdinalIgnoreCase))
  301. {
  302. return "h264";
  303. }
  304. return "copy";
  305. }
  306. public int GetVideoProfileScore(string profile)
  307. {
  308. // strip spaces because they may be stripped out on the query string
  309. profile = profile.Replace(" ", "");
  310. return Array.FindIndex(_videoProfiles, x => string.Equals(x, profile, StringComparison.OrdinalIgnoreCase));
  311. }
  312. public string GetInputPathArgument(EncodingJobInfo state)
  313. {
  314. var protocol = state.InputProtocol;
  315. var mediaPath = state.MediaPath ?? string.Empty;
  316. string[] inputPath;
  317. if (state.IsInputVideo
  318. && !(state.VideoType == VideoType.Iso && state.IsoMount == null))
  319. {
  320. inputPath = MediaEncoderHelpers.GetInputArgument(
  321. _fileSystem,
  322. mediaPath,
  323. state.IsoMount,
  324. state.PlayableStreamFileNames);
  325. }
  326. else
  327. {
  328. inputPath = new[] { mediaPath };
  329. }
  330. return _mediaEncoder.GetInputArgument(inputPath, protocol);
  331. }
  332. /// <summary>
  333. /// Gets the audio encoder.
  334. /// </summary>
  335. /// <param name="state">The state.</param>
  336. /// <returns>System.String.</returns>
  337. public string GetAudioEncoder(EncodingJobInfo state)
  338. {
  339. var codec = state.OutputAudioCodec;
  340. if (string.Equals(codec, "aac", StringComparison.OrdinalIgnoreCase))
  341. {
  342. // Use libfdk_aac for better audio quality if using custom build of FFmpeg which has fdk_aac support
  343. if (_mediaEncoder.SupportsEncoder("libfdk_aac"))
  344. {
  345. return "libfdk_aac";
  346. }
  347. return "aac";
  348. }
  349. if (string.Equals(codec, "mp3", StringComparison.OrdinalIgnoreCase))
  350. {
  351. return "libmp3lame";
  352. }
  353. if (string.Equals(codec, "vorbis", StringComparison.OrdinalIgnoreCase))
  354. {
  355. return "libvorbis";
  356. }
  357. if (string.Equals(codec, "wma", StringComparison.OrdinalIgnoreCase))
  358. {
  359. return "wmav2";
  360. }
  361. if (string.Equals(codec, "opus", StringComparison.OrdinalIgnoreCase))
  362. {
  363. return "libopus";
  364. }
  365. return codec.ToLowerInvariant();
  366. }
  367. /// <summary>
  368. /// Gets the input argument.
  369. /// </summary>
  370. public string GetInputArgument(EncodingJobInfo state, EncodingOptions encodingOptions)
  371. {
  372. var arg = new StringBuilder();
  373. var videoDecoder = GetHardwareAcceleratedVideoDecoder(state, encodingOptions) ?? string.Empty;
  374. var outputVideoCodec = GetVideoEncoder(state, encodingOptions) ?? string.Empty;
  375. var isVaapiDecoder = videoDecoder.IndexOf("vaapi", StringComparison.OrdinalIgnoreCase) != -1;
  376. var isVaapiEncoder = outputVideoCodec.IndexOf("vaapi", StringComparison.OrdinalIgnoreCase) != -1;
  377. var isQsvDecoder = videoDecoder.IndexOf("qsv", StringComparison.OrdinalIgnoreCase) != -1;
  378. var isQsvEncoder = outputVideoCodec.IndexOf("qsv", StringComparison.OrdinalIgnoreCase) != -1;
  379. var isWindows = RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
  380. var isLinux = RuntimeInformation.IsOSPlatform(OSPlatform.Linux);
  381. var isMacOS = RuntimeInformation.IsOSPlatform(OSPlatform.OSX);
  382. if (!IsCopyCodec(outputVideoCodec))
  383. {
  384. if (state.IsVideoRequest
  385. && _mediaEncoder.SupportsHwaccel("vaapi")
  386. && string.Equals(encodingOptions.HardwareAccelerationType, "vaapi", StringComparison.OrdinalIgnoreCase))
  387. {
  388. if (isVaapiDecoder)
  389. {
  390. arg.Append("-hwaccel_output_format vaapi ")
  391. .Append("-vaapi_device ")
  392. .Append(encodingOptions.VaapiDevice)
  393. .Append(" ");
  394. }
  395. else if (!isVaapiDecoder && isVaapiEncoder)
  396. {
  397. arg.Append("-vaapi_device ")
  398. .Append(encodingOptions.VaapiDevice)
  399. .Append(" ");
  400. }
  401. }
  402. if (state.IsVideoRequest
  403. && string.Equals(encodingOptions.HardwareAccelerationType, "qsv", StringComparison.OrdinalIgnoreCase))
  404. {
  405. var hasGraphicalSubs = state.SubtitleStream != null && !state.SubtitleStream.IsTextSubtitleStream && state.SubtitleDeliveryMethod == SubtitleDeliveryMethod.Encode;
  406. if (isQsvEncoder)
  407. {
  408. if (isQsvDecoder)
  409. {
  410. if (isLinux)
  411. {
  412. if (hasGraphicalSubs)
  413. {
  414. arg.Append("-init_hw_device qsv=hw -filter_hw_device hw ");
  415. }
  416. else
  417. {
  418. arg.Append("-hwaccel qsv ");
  419. }
  420. }
  421. if (isWindows)
  422. {
  423. arg.Append("-hwaccel qsv ");
  424. }
  425. }
  426. // While using SW decoder
  427. else
  428. {
  429. arg.Append("-init_hw_device qsv=hw -filter_hw_device hw ");
  430. }
  431. }
  432. }
  433. if (state.IsVideoRequest
  434. && string.Equals(encodingOptions.HardwareAccelerationType, "videotoolbox", StringComparison.OrdinalIgnoreCase))
  435. {
  436. arg.Append("-hwaccel videotoolbox ");
  437. }
  438. }
  439. arg.Append("-i ")
  440. .Append(GetInputPathArgument(state));
  441. if (state.SubtitleStream != null
  442. && state.SubtitleDeliveryMethod == SubtitleDeliveryMethod.Encode
  443. && state.SubtitleStream.IsExternal && !state.SubtitleStream.IsTextSubtitleStream)
  444. {
  445. var subtitlePath = state.SubtitleStream.Path;
  446. if (string.Equals(Path.GetExtension(subtitlePath), ".sub", StringComparison.OrdinalIgnoreCase))
  447. {
  448. var idxFile = Path.ChangeExtension(subtitlePath, ".idx");
  449. if (File.Exists(idxFile))
  450. {
  451. subtitlePath = idxFile;
  452. }
  453. }
  454. arg.Append(" -i \"").Append(subtitlePath).Append('\"');
  455. }
  456. return arg.ToString();
  457. }
  458. /// <summary>
  459. /// Determines whether the specified stream is H264.
  460. /// </summary>
  461. /// <param name="stream">The stream.</param>
  462. /// <returns><c>true</c> if the specified stream is H264; otherwise, <c>false</c>.</returns>
  463. public bool IsH264(MediaStream stream)
  464. {
  465. var codec = stream.Codec ?? string.Empty;
  466. return codec.IndexOf("264", StringComparison.OrdinalIgnoreCase) != -1
  467. || codec.IndexOf("avc", StringComparison.OrdinalIgnoreCase) != -1;
  468. }
  469. public bool IsH265(MediaStream stream)
  470. {
  471. var codec = stream.Codec ?? string.Empty;
  472. return codec.IndexOf("265", StringComparison.OrdinalIgnoreCase) != -1
  473. || codec.IndexOf("hevc", StringComparison.OrdinalIgnoreCase) != -1;
  474. }
  475. // TODO This is auto inserted into the mpegts mux so it might not be needed
  476. // https://www.ffmpeg.org/ffmpeg-bitstream-filters.html#h264_005fmp4toannexb
  477. public string GetBitStreamArgs(MediaStream stream)
  478. {
  479. if (IsH264(stream))
  480. {
  481. return "-bsf:v h264_mp4toannexb";
  482. }
  483. else if (IsH265(stream))
  484. {
  485. return "-bsf:v hevc_mp4toannexb";
  486. }
  487. else
  488. {
  489. return null;
  490. }
  491. }
  492. public string GetVideoBitrateParam(EncodingJobInfo state, string videoCodec)
  493. {
  494. var bitrate = state.OutputVideoBitrate;
  495. if (bitrate.HasValue)
  496. {
  497. if (string.Equals(videoCodec, "libvpx", StringComparison.OrdinalIgnoreCase))
  498. {
  499. // When crf is used with vpx, b:v becomes a max rate
  500. // https://trac.ffmpeg.org/wiki/Encode/VP9
  501. return string.Format(
  502. CultureInfo.InvariantCulture,
  503. " -maxrate:v {0} -bufsize:v {1} -b:v {0}",
  504. bitrate.Value,
  505. bitrate.Value * 2);
  506. }
  507. if (string.Equals(videoCodec, "msmpeg4", StringComparison.OrdinalIgnoreCase))
  508. {
  509. return string.Format(
  510. CultureInfo.InvariantCulture,
  511. " -b:v {0}",
  512. bitrate.Value);
  513. }
  514. if (string.Equals(videoCodec, "libx264", StringComparison.OrdinalIgnoreCase) ||
  515. string.Equals(videoCodec, "libx265", StringComparison.OrdinalIgnoreCase))
  516. {
  517. // h264
  518. return string.Format(
  519. CultureInfo.InvariantCulture,
  520. " -maxrate {0} -bufsize {1}",
  521. bitrate.Value,
  522. bitrate.Value * 2);
  523. }
  524. // h264
  525. return string.Format(
  526. CultureInfo.InvariantCulture,
  527. " -b:v {0} -maxrate {0} -bufsize {1}",
  528. bitrate.Value,
  529. bitrate.Value * 2);
  530. }
  531. return string.Empty;
  532. }
  533. public string NormalizeTranscodingLevel(string videoCodec, string level)
  534. {
  535. // Clients may direct play higher than level 41, but there's no reason to transcode higher
  536. if (double.TryParse(level, NumberStyles.Any, _usCulture, out double requestLevel)
  537. && requestLevel > 41
  538. && (string.Equals(videoCodec, "h264", StringComparison.OrdinalIgnoreCase)
  539. || string.Equals(videoCodec, "h265", StringComparison.OrdinalIgnoreCase)
  540. || string.Equals(videoCodec, "hevc", StringComparison.OrdinalIgnoreCase)))
  541. {
  542. return "41";
  543. }
  544. return level;
  545. }
  546. /// <summary>
  547. /// Gets the text subtitle param.
  548. /// </summary>
  549. /// <param name="state">The state.</param>
  550. /// <returns>System.String.</returns>
  551. public string GetTextSubtitleParam(EncodingJobInfo state)
  552. {
  553. var seconds = Math.Round(TimeSpan.FromTicks(state.StartTimeTicks ?? 0).TotalSeconds);
  554. // hls always copies timestamps
  555. var setPtsParam = state.CopyTimestamps || state.TranscodingType != TranscodingJobType.Progressive
  556. ? string.Empty
  557. : string.Format(CultureInfo.InvariantCulture, ",setpts=PTS -{0}/TB", seconds);
  558. // TODO
  559. // var fallbackFontPath = Path.Combine(_appPaths.ProgramDataPath, "fonts", "DroidSansFallback.ttf");
  560. // string fallbackFontParam = string.Empty;
  561. // if (!File.Exists(fallbackFontPath))
  562. // {
  563. // _fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(fallbackFontPath));
  564. // using (var stream = _assemblyInfo.GetManifestResourceStream(GetType(), GetType().Namespace + ".DroidSansFallback.ttf"))
  565. // {
  566. // using (var fileStream = new FileStream(fallbackFontPath, FileMode.Create, FileAccess.Write, FileShare.Read))
  567. // {
  568. // stream.CopyTo(fileStream);
  569. // }
  570. // }
  571. // }
  572. // fallbackFontParam = string.Format(":force_style='FontName=Droid Sans Fallback':fontsdir='{0}'", _mediaEncoder.EscapeSubtitleFilterPath(_fileSystem.GetDirectoryName(fallbackFontPath)));
  573. if (state.SubtitleStream.IsExternal)
  574. {
  575. var subtitlePath = state.SubtitleStream.Path;
  576. var charsetParam = string.Empty;
  577. if (!string.IsNullOrEmpty(state.SubtitleStream.Language))
  578. {
  579. var charenc = _subtitleEncoder.GetSubtitleFileCharacterSet(
  580. subtitlePath,
  581. state.SubtitleStream.Language,
  582. state.MediaSource.Protocol,
  583. CancellationToken.None).GetAwaiter().GetResult();
  584. if (!string.IsNullOrEmpty(charenc))
  585. {
  586. charsetParam = ":charenc=" + charenc;
  587. }
  588. }
  589. // TODO: Perhaps also use original_size=1920x800 ??
  590. return string.Format(
  591. CultureInfo.InvariantCulture,
  592. "subtitles=filename='{0}'{1}{2}",
  593. _mediaEncoder.EscapeSubtitleFilterPath(subtitlePath),
  594. charsetParam,
  595. // fallbackFontParam,
  596. setPtsParam);
  597. }
  598. var mediaPath = state.MediaPath ?? string.Empty;
  599. return string.Format(
  600. CultureInfo.InvariantCulture,
  601. "subtitles='{0}:si={1}'{2}",
  602. _mediaEncoder.EscapeSubtitleFilterPath(mediaPath),
  603. state.InternalSubtitleStreamOffset.ToString(_usCulture),
  604. // fallbackFontParam,
  605. setPtsParam);
  606. }
  607. public double? GetFramerateParam(EncodingJobInfo state)
  608. {
  609. var request = state.BaseRequest;
  610. if (request.Framerate.HasValue)
  611. {
  612. return request.Framerate.Value;
  613. }
  614. var maxrate = request.MaxFramerate;
  615. if (maxrate.HasValue && state.VideoStream != null)
  616. {
  617. var contentRate = state.VideoStream.AverageFrameRate ?? state.VideoStream.RealFrameRate;
  618. if (contentRate.HasValue && contentRate.Value > maxrate.Value)
  619. {
  620. return maxrate;
  621. }
  622. }
  623. return null;
  624. }
  625. /// <summary>
  626. /// Gets the video bitrate to specify on the command line.
  627. /// </summary>
  628. public string GetVideoQualityParam(EncodingJobInfo state, string videoEncoder, EncodingOptions encodingOptions, string defaultPreset)
  629. {
  630. var param = string.Empty;
  631. var isVc1 = state.VideoStream != null &&
  632. string.Equals(state.VideoStream.Codec, "vc1", StringComparison.OrdinalIgnoreCase);
  633. var isLibX265 = string.Equals(videoEncoder, "libx265", StringComparison.OrdinalIgnoreCase);
  634. if (string.Equals(videoEncoder, "libx264", StringComparison.OrdinalIgnoreCase) || isLibX265)
  635. {
  636. if (!string.IsNullOrEmpty(encodingOptions.EncoderPreset))
  637. {
  638. param += "-preset " + encodingOptions.EncoderPreset;
  639. }
  640. else
  641. {
  642. param += "-preset " + defaultPreset;
  643. }
  644. int encodeCrf = encodingOptions.H264Crf;
  645. if (isLibX265)
  646. {
  647. encodeCrf = encodingOptions.H265Crf;
  648. }
  649. if (encodeCrf >= 0 && encodeCrf <= 51)
  650. {
  651. param += " -crf " + encodeCrf.ToString(CultureInfo.InvariantCulture);
  652. }
  653. else
  654. {
  655. string defaultCrf = "23";
  656. if (isLibX265)
  657. {
  658. defaultCrf = "28";
  659. }
  660. param += " -crf " + defaultCrf;
  661. }
  662. }
  663. else if (string.Equals(videoEncoder, "h264_qsv", StringComparison.OrdinalIgnoreCase)) // h264 (h264_qsv)
  664. {
  665. string[] valid_h264_qsv = { "veryslow", "slower", "slow", "medium", "fast", "faster", "veryfast" };
  666. if (valid_h264_qsv.Contains(encodingOptions.EncoderPreset, StringComparer.OrdinalIgnoreCase))
  667. {
  668. param += "-preset " + encodingOptions.EncoderPreset;
  669. }
  670. else
  671. {
  672. param += "-preset 7";
  673. }
  674. param += " -look_ahead 0";
  675. }
  676. else if (string.Equals(videoEncoder, "h264_nvenc", StringComparison.OrdinalIgnoreCase) // h264 (h264_nvenc)
  677. || string.Equals(videoEncoder, "hevc_nvenc", StringComparison.OrdinalIgnoreCase))
  678. {
  679. switch (encodingOptions.EncoderPreset)
  680. {
  681. case "veryslow":
  682. param += "-preset slow"; // lossless is only supported on maxwell and newer(2014+)
  683. break;
  684. case "slow":
  685. case "slower":
  686. param += "-preset slow";
  687. break;
  688. case "medium":
  689. param += "-preset medium";
  690. break;
  691. case "fast":
  692. case "faster":
  693. case "veryfast":
  694. case "superfast":
  695. case "ultrafast":
  696. param += "-preset fast";
  697. break;
  698. default:
  699. param += "-preset default";
  700. break;
  701. }
  702. }
  703. else if (string.Equals(videoEncoder, "h264_amf", StringComparison.OrdinalIgnoreCase)
  704. || string.Equals(videoEncoder, "hevc_amf", StringComparison.OrdinalIgnoreCase))
  705. {
  706. switch (encodingOptions.EncoderPreset)
  707. {
  708. case "veryslow":
  709. case "slow":
  710. case "slower":
  711. param += "-quality quality";
  712. break;
  713. case "medium":
  714. param += "-quality balanced";
  715. break;
  716. case "fast":
  717. case "faster":
  718. case "veryfast":
  719. case "superfast":
  720. case "ultrafast":
  721. param += "-quality speed";
  722. break;
  723. default:
  724. param += "-quality speed";
  725. break;
  726. }
  727. }
  728. else if (string.Equals(videoEncoder, "libvpx", StringComparison.OrdinalIgnoreCase)) // webm
  729. {
  730. // Values 0-3, 0 being highest quality but slower
  731. var profileScore = 0;
  732. string crf;
  733. var qmin = "0";
  734. var qmax = "50";
  735. crf = "10";
  736. if (isVc1)
  737. {
  738. profileScore++;
  739. }
  740. // Max of 2
  741. profileScore = Math.Min(profileScore, 2);
  742. // http://www.webmproject.org/docs/encoder-parameters/
  743. param += string.Format("-speed 16 -quality good -profile:v {0} -slices 8 -crf {1} -qmin {2} -qmax {3}",
  744. profileScore.ToString(_usCulture),
  745. crf,
  746. qmin,
  747. qmax);
  748. }
  749. else if (string.Equals(videoEncoder, "mpeg4", StringComparison.OrdinalIgnoreCase))
  750. {
  751. param += "-mbd rd -flags +mv4+aic -trellis 2 -cmp 2 -subcmp 2 -bf 2";
  752. }
  753. else if (string.Equals(videoEncoder, "wmv2", StringComparison.OrdinalIgnoreCase)) // asf/wmv
  754. {
  755. param += "-qmin 2";
  756. }
  757. else if (string.Equals(videoEncoder, "msmpeg4", StringComparison.OrdinalIgnoreCase))
  758. {
  759. param += "-mbd 2";
  760. }
  761. param += GetVideoBitrateParam(state, videoEncoder);
  762. var framerate = GetFramerateParam(state);
  763. if (framerate.HasValue)
  764. {
  765. param += string.Format(" -r {0}", framerate.Value.ToString(_usCulture));
  766. }
  767. var targetVideoCodec = state.ActualOutputVideoCodec;
  768. var profile = state.GetRequestedProfiles(targetVideoCodec).FirstOrDefault();
  769. // vaapi does not support Baseline profile, force Constrained Baseline in this case,
  770. // which is compatible (and ugly)
  771. if (string.Equals(videoEncoder, "h264_vaapi", StringComparison.OrdinalIgnoreCase)
  772. && profile != null
  773. && profile.IndexOf("baseline", StringComparison.OrdinalIgnoreCase) != -1)
  774. {
  775. profile = "constrained_baseline";
  776. }
  777. if (!string.IsNullOrEmpty(profile))
  778. {
  779. if (!string.Equals(videoEncoder, "h264_omx", StringComparison.OrdinalIgnoreCase)
  780. && !string.Equals(videoEncoder, "h264_v4l2m2m", StringComparison.OrdinalIgnoreCase))
  781. {
  782. // not supported by h264_omx
  783. param += " -profile:v " + profile;
  784. }
  785. }
  786. var level = state.GetRequestedLevel(targetVideoCodec);
  787. if (!string.IsNullOrEmpty(level))
  788. {
  789. level = NormalizeTranscodingLevel(state.OutputVideoCodec, level);
  790. // h264_qsv and h264_nvenc expect levels to be expressed as a decimal. libx264 supports decimal and non-decimal format
  791. // also needed for libx264 due to https://trac.ffmpeg.org/ticket/3307
  792. if (string.Equals(videoEncoder, "h264_qsv", StringComparison.OrdinalIgnoreCase)
  793. || string.Equals(videoEncoder, "libx264", StringComparison.OrdinalIgnoreCase)
  794. || string.Equals(videoEncoder, "libx265", StringComparison.OrdinalIgnoreCase))
  795. {
  796. switch (level)
  797. {
  798. case "30":
  799. param += " -level 3.0";
  800. break;
  801. case "31":
  802. param += " -level 3.1";
  803. break;
  804. case "32":
  805. param += " -level 3.2";
  806. break;
  807. case "40":
  808. param += " -level 4.0";
  809. break;
  810. case "41":
  811. param += " -level 4.1";
  812. break;
  813. case "42":
  814. param += " -level 4.2";
  815. break;
  816. case "50":
  817. param += " -level 5.0";
  818. break;
  819. case "51":
  820. param += " -level 5.1";
  821. break;
  822. case "52":
  823. param += " -level 5.2";
  824. break;
  825. default:
  826. param += " -level " + level;
  827. break;
  828. }
  829. }
  830. else if (string.Equals(videoEncoder, "h264_nvenc", StringComparison.OrdinalIgnoreCase)
  831. || string.Equals(videoEncoder, "hevc_nvenc", StringComparison.OrdinalIgnoreCase))
  832. {
  833. // nvenc doesn't decode with param -level set ?!
  834. // TODO:
  835. }
  836. else if (!string.Equals(videoEncoder, "h264_omx", StringComparison.OrdinalIgnoreCase))
  837. {
  838. param += " -level " + level;
  839. }
  840. }
  841. if (string.Equals(videoEncoder, "libx264", StringComparison.OrdinalIgnoreCase))
  842. {
  843. param += " -x264opts:0 subme=0:me_range=4:rc_lookahead=10:me=dia:no_chroma_me:8x8dct=0:partitions=none";
  844. }
  845. if (string.Equals(videoEncoder, "libx265", StringComparison.OrdinalIgnoreCase))
  846. {
  847. // todo
  848. }
  849. if (!string.Equals(videoEncoder, "h264_omx", StringComparison.OrdinalIgnoreCase)
  850. && !string.Equals(videoEncoder, "h264_qsv", StringComparison.OrdinalIgnoreCase)
  851. && !string.Equals(videoEncoder, "h264_vaapi", StringComparison.OrdinalIgnoreCase)
  852. && !string.Equals(videoEncoder, "h264_v4l2m2m", StringComparison.OrdinalIgnoreCase))
  853. {
  854. param = "-pix_fmt yuv420p " + param;
  855. }
  856. if (string.Equals(videoEncoder, "h264_v4l2m2m", StringComparison.OrdinalIgnoreCase))
  857. {
  858. param = "-pix_fmt nv21 " + param;
  859. }
  860. return param;
  861. }
  862. public bool CanStreamCopyVideo(EncodingJobInfo state, MediaStream videoStream)
  863. {
  864. var request = state.BaseRequest;
  865. if (!request.AllowVideoStreamCopy)
  866. {
  867. return false;
  868. }
  869. if (videoStream.IsInterlaced
  870. && state.DeInterlace(videoStream.Codec, false))
  871. {
  872. return false;
  873. }
  874. if (videoStream.IsAnamorphic ?? false)
  875. {
  876. if (request.RequireNonAnamorphic)
  877. {
  878. return false;
  879. }
  880. }
  881. // Can't stream copy if we're burning in subtitles
  882. if (request.SubtitleStreamIndex.HasValue
  883. && state.SubtitleDeliveryMethod == SubtitleDeliveryMethod.Encode)
  884. {
  885. return false;
  886. }
  887. if (string.Equals("h264", videoStream.Codec, StringComparison.OrdinalIgnoreCase)
  888. && videoStream.IsAVC.HasValue
  889. && !videoStream.IsAVC.Value
  890. && request.RequireAvc)
  891. {
  892. return false;
  893. }
  894. // Source and target codecs must match
  895. if (string.IsNullOrEmpty(videoStream.Codec)
  896. || !state.SupportedVideoCodecs.Contains(videoStream.Codec, StringComparer.OrdinalIgnoreCase))
  897. {
  898. return false;
  899. }
  900. var requestedProfiles = state.GetRequestedProfiles(videoStream.Codec);
  901. // If client is requesting a specific video profile, it must match the source
  902. if (requestedProfiles.Length > 0)
  903. {
  904. if (string.IsNullOrEmpty(videoStream.Profile))
  905. {
  906. // return false;
  907. }
  908. var requestedProfile = requestedProfiles[0];
  909. // strip spaces because they may be stripped out on the query string as well
  910. if (!string.IsNullOrEmpty(videoStream.Profile) && !requestedProfiles.Contains(videoStream.Profile.Replace(" ", ""), StringComparer.OrdinalIgnoreCase))
  911. {
  912. var currentScore = GetVideoProfileScore(videoStream.Profile);
  913. var requestedScore = GetVideoProfileScore(requestedProfile);
  914. if (currentScore == -1 || currentScore > requestedScore)
  915. {
  916. return false;
  917. }
  918. }
  919. }
  920. // Video width must fall within requested value
  921. if (request.MaxWidth.HasValue
  922. && (!videoStream.Width.HasValue || videoStream.Width.Value > request.MaxWidth.Value))
  923. {
  924. return false;
  925. }
  926. // Video height must fall within requested value
  927. if (request.MaxHeight.HasValue
  928. && (!videoStream.Height.HasValue || videoStream.Height.Value > request.MaxHeight.Value))
  929. {
  930. return false;
  931. }
  932. // Video framerate must fall within requested value
  933. var requestedFramerate = request.MaxFramerate ?? request.Framerate;
  934. if (requestedFramerate.HasValue)
  935. {
  936. var videoFrameRate = videoStream.AverageFrameRate ?? videoStream.RealFrameRate;
  937. if (!videoFrameRate.HasValue || videoFrameRate.Value > requestedFramerate.Value)
  938. {
  939. return false;
  940. }
  941. }
  942. // Video bitrate must fall within requested value
  943. if (request.VideoBitRate.HasValue
  944. && (!videoStream.BitRate.HasValue || videoStream.BitRate.Value > request.VideoBitRate.Value))
  945. {
  946. return false;
  947. }
  948. var maxBitDepth = state.GetRequestedVideoBitDepth(videoStream.Codec);
  949. if (maxBitDepth.HasValue)
  950. {
  951. if (videoStream.BitDepth.HasValue && videoStream.BitDepth.Value > maxBitDepth.Value)
  952. {
  953. return false;
  954. }
  955. }
  956. var maxRefFrames = state.GetRequestedMaxRefFrames(videoStream.Codec);
  957. if (maxRefFrames.HasValue
  958. && videoStream.RefFrames.HasValue && videoStream.RefFrames.Value > maxRefFrames.Value)
  959. {
  960. return false;
  961. }
  962. // If a specific level was requested, the source must match or be less than
  963. var level = state.GetRequestedLevel(videoStream.Codec);
  964. if (!string.IsNullOrEmpty(level)
  965. && double.TryParse(level, NumberStyles.Any, _usCulture, out var requestLevel))
  966. {
  967. if (!videoStream.Level.HasValue)
  968. {
  969. // return false;
  970. }
  971. if (videoStream.Level.HasValue && videoStream.Level.Value > requestLevel)
  972. {
  973. return false;
  974. }
  975. }
  976. if (string.Equals(state.InputContainer, "avi", StringComparison.OrdinalIgnoreCase)
  977. && string.Equals(videoStream.Codec, "h264", StringComparison.OrdinalIgnoreCase)
  978. && !(videoStream.IsAVC ?? false))
  979. {
  980. // see Coach S01E01 - Kelly and the Professor(0).avi
  981. return false;
  982. }
  983. return request.EnableAutoStreamCopy;
  984. }
  985. public bool CanStreamCopyAudio(EncodingJobInfo state, MediaStream audioStream, IEnumerable<string> supportedAudioCodecs)
  986. {
  987. var request = state.BaseRequest;
  988. if (!request.AllowAudioStreamCopy)
  989. {
  990. return false;
  991. }
  992. var maxBitDepth = state.GetRequestedAudioBitDepth(audioStream.Codec);
  993. if (maxBitDepth.HasValue
  994. && audioStream.BitDepth.HasValue
  995. && audioStream.BitDepth.Value > maxBitDepth.Value)
  996. {
  997. return false;
  998. }
  999. // Source and target codecs must match
  1000. if (string.IsNullOrEmpty(audioStream.Codec)
  1001. || !supportedAudioCodecs.Contains(audioStream.Codec, StringComparer.OrdinalIgnoreCase))
  1002. {
  1003. return false;
  1004. }
  1005. // Channels must fall within requested value
  1006. var channels = state.GetRequestedAudioChannels(audioStream.Codec);
  1007. if (channels.HasValue)
  1008. {
  1009. if (!audioStream.Channels.HasValue || audioStream.Channels.Value <= 0)
  1010. {
  1011. return false;
  1012. }
  1013. if (audioStream.Channels.Value > channels.Value)
  1014. {
  1015. return false;
  1016. }
  1017. }
  1018. // Sample rate must fall within requested value
  1019. if (request.AudioSampleRate.HasValue)
  1020. {
  1021. if (!audioStream.SampleRate.HasValue || audioStream.SampleRate.Value <= 0)
  1022. {
  1023. return false;
  1024. }
  1025. if (audioStream.SampleRate.Value > request.AudioSampleRate.Value)
  1026. {
  1027. return false;
  1028. }
  1029. }
  1030. // Video bitrate must fall within requested value
  1031. if (request.AudioBitRate.HasValue)
  1032. {
  1033. if (!audioStream.BitRate.HasValue || audioStream.BitRate.Value <= 0)
  1034. {
  1035. return false;
  1036. }
  1037. if (audioStream.BitRate.Value > request.AudioBitRate.Value)
  1038. {
  1039. return false;
  1040. }
  1041. }
  1042. return request.EnableAutoStreamCopy;
  1043. }
  1044. public int? GetVideoBitrateParamValue(BaseEncodingJobOptions request, MediaStream videoStream, string outputVideoCodec)
  1045. {
  1046. var bitrate = request.VideoBitRate;
  1047. if (videoStream != null)
  1048. {
  1049. var isUpscaling = request.Height.HasValue
  1050. && videoStream.Height.HasValue
  1051. && request.Height.Value > videoStream.Height.Value
  1052. && request.Width.HasValue
  1053. && videoStream.Width.HasValue
  1054. && request.Width.Value > videoStream.Width.Value;
  1055. // Don't allow bitrate increases unless upscaling
  1056. if (!isUpscaling && bitrate.HasValue && videoStream.BitRate.HasValue)
  1057. {
  1058. bitrate = GetMinBitrate(videoStream.BitRate.Value, bitrate.Value);
  1059. }
  1060. if (bitrate.HasValue)
  1061. {
  1062. var inputVideoCodec = videoStream.Codec;
  1063. bitrate = ScaleBitrate(bitrate.Value, inputVideoCodec, outputVideoCodec);
  1064. // If a max bitrate was requested, don't let the scaled bitrate exceed it
  1065. if (request.VideoBitRate.HasValue)
  1066. {
  1067. bitrate = Math.Min(bitrate.Value, request.VideoBitRate.Value);
  1068. }
  1069. }
  1070. }
  1071. return bitrate;
  1072. }
  1073. private int GetMinBitrate(int sourceBitrate, int requestedBitrate)
  1074. {
  1075. // these values were chosen from testing to improve low bitrate streams
  1076. if (sourceBitrate <= 2000000)
  1077. {
  1078. sourceBitrate = Convert.ToInt32(sourceBitrate * 2.5);
  1079. }
  1080. else if (sourceBitrate <= 3000000)
  1081. {
  1082. sourceBitrate *= 2;
  1083. }
  1084. var bitrate = Math.Min(sourceBitrate, requestedBitrate);
  1085. return bitrate;
  1086. }
  1087. private static double GetVideoBitrateScaleFactor(string codec)
  1088. {
  1089. if (string.Equals(codec, "h265", StringComparison.OrdinalIgnoreCase)
  1090. || string.Equals(codec, "hevc", StringComparison.OrdinalIgnoreCase)
  1091. || string.Equals(codec, "vp9", StringComparison.OrdinalIgnoreCase))
  1092. {
  1093. return .5;
  1094. }
  1095. return 1;
  1096. }
  1097. private static int ScaleBitrate(int bitrate, string inputVideoCodec, string outputVideoCodec)
  1098. {
  1099. var inputScaleFactor = GetVideoBitrateScaleFactor(inputVideoCodec);
  1100. var outputScaleFactor = GetVideoBitrateScaleFactor(outputVideoCodec);
  1101. var scaleFactor = outputScaleFactor / inputScaleFactor;
  1102. if (bitrate <= 500000)
  1103. {
  1104. scaleFactor = Math.Max(scaleFactor, 4);
  1105. }
  1106. else if (bitrate <= 1000000)
  1107. {
  1108. scaleFactor = Math.Max(scaleFactor, 3);
  1109. }
  1110. else if (bitrate <= 2000000)
  1111. {
  1112. scaleFactor = Math.Max(scaleFactor, 2.5);
  1113. }
  1114. else if (bitrate <= 3000000)
  1115. {
  1116. scaleFactor = Math.Max(scaleFactor, 2);
  1117. }
  1118. return Convert.ToInt32(scaleFactor * bitrate);
  1119. }
  1120. public int? GetAudioBitrateParam(BaseEncodingJobOptions request, MediaStream audioStream)
  1121. {
  1122. if (request.AudioBitRate.HasValue)
  1123. {
  1124. // Don't encode any higher than this
  1125. return Math.Min(384000, request.AudioBitRate.Value);
  1126. }
  1127. return null;
  1128. }
  1129. public string GetAudioFilterParam(EncodingJobInfo state, EncodingOptions encodingOptions, bool isHls)
  1130. {
  1131. var channels = state.OutputAudioChannels;
  1132. var filters = new List<string>();
  1133. // Boost volume to 200% when downsampling from 6ch to 2ch
  1134. if (channels.HasValue
  1135. && channels.Value <= 2
  1136. && state.AudioStream != null
  1137. && state.AudioStream.Channels.HasValue
  1138. && state.AudioStream.Channels.Value > 5
  1139. && !encodingOptions.DownMixAudioBoost.Equals(1))
  1140. {
  1141. filters.Add("volume=" + encodingOptions.DownMixAudioBoost.ToString(_usCulture));
  1142. }
  1143. var isCopyingTimestamps = state.CopyTimestamps || state.TranscodingType != TranscodingJobType.Progressive;
  1144. if (state.SubtitleStream != null && state.SubtitleStream.IsTextSubtitleStream && state.SubtitleDeliveryMethod == SubtitleDeliveryMethod.Encode && !isCopyingTimestamps)
  1145. {
  1146. var seconds = TimeSpan.FromTicks(state.StartTimeTicks ?? 0).TotalSeconds;
  1147. filters.Add(
  1148. string.Format(
  1149. CultureInfo.InvariantCulture,
  1150. "asetpts=PTS-{0}/TB",
  1151. Math.Round(seconds)));
  1152. }
  1153. if (filters.Count > 0)
  1154. {
  1155. return "-af \"" + string.Join(",", filters) + "\"";
  1156. }
  1157. return string.Empty;
  1158. }
  1159. /// <summary>
  1160. /// Gets the number of audio channels to specify on the command line.
  1161. /// </summary>
  1162. /// <param name="state">The state.</param>
  1163. /// <param name="audioStream">The audio stream.</param>
  1164. /// <param name="outputAudioCodec">The output audio codec.</param>
  1165. /// <returns>System.Nullable{System.Int32}.</returns>
  1166. public int? GetNumAudioChannelsParam(EncodingJobInfo state, MediaStream audioStream, string outputAudioCodec)
  1167. {
  1168. var request = state.BaseRequest;
  1169. var inputChannels = audioStream?.Channels;
  1170. if (inputChannels <= 0)
  1171. {
  1172. inputChannels = null;
  1173. }
  1174. var codec = outputAudioCodec ?? string.Empty;
  1175. int? transcoderChannelLimit;
  1176. if (codec.IndexOf("wma", StringComparison.OrdinalIgnoreCase) != -1)
  1177. {
  1178. // wmav2 currently only supports two channel output
  1179. transcoderChannelLimit = 2;
  1180. }
  1181. else if (codec.IndexOf("mp3", StringComparison.OrdinalIgnoreCase) != -1)
  1182. {
  1183. // libmp3lame currently only supports two channel output
  1184. transcoderChannelLimit = 2;
  1185. }
  1186. else
  1187. {
  1188. // If we don't have any media info then limit it to 6 to prevent encoding errors due to asking for too many channels
  1189. transcoderChannelLimit = 6;
  1190. }
  1191. var isTranscodingAudio = !IsCopyCodec(codec);
  1192. int? resultChannels = state.GetRequestedAudioChannels(codec);
  1193. if (isTranscodingAudio)
  1194. {
  1195. resultChannels = GetMinValue(request.TranscodingMaxAudioChannels, resultChannels);
  1196. }
  1197. if (inputChannels.HasValue)
  1198. {
  1199. resultChannels = resultChannels.HasValue
  1200. ? Math.Min(resultChannels.Value, inputChannels.Value)
  1201. : inputChannels.Value;
  1202. }
  1203. if (isTranscodingAudio && transcoderChannelLimit.HasValue)
  1204. {
  1205. resultChannels = resultChannels.HasValue
  1206. ? Math.Min(resultChannels.Value, transcoderChannelLimit.Value)
  1207. : transcoderChannelLimit.Value;
  1208. }
  1209. return resultChannels;
  1210. }
  1211. private int? GetMinValue(int? val1, int? val2)
  1212. {
  1213. if (!val1.HasValue)
  1214. {
  1215. return val2;
  1216. }
  1217. if (!val2.HasValue)
  1218. {
  1219. return val1;
  1220. }
  1221. return Math.Min(val1.Value, val2.Value);
  1222. }
  1223. /// <summary>
  1224. /// Enforces the resolution limit.
  1225. /// </summary>
  1226. /// <param name="state">The state.</param>
  1227. public void EnforceResolutionLimit(EncodingJobInfo state)
  1228. {
  1229. var videoRequest = state.BaseRequest;
  1230. // Switch the incoming params to be ceilings rather than fixed values
  1231. videoRequest.MaxWidth = videoRequest.MaxWidth ?? videoRequest.Width;
  1232. videoRequest.MaxHeight = videoRequest.MaxHeight ?? videoRequest.Height;
  1233. videoRequest.Width = null;
  1234. videoRequest.Height = null;
  1235. }
  1236. /// <summary>
  1237. /// Gets the fast seek command line parameter.
  1238. /// </summary>
  1239. /// <param name="request">The request.</param>
  1240. /// <returns>System.String.</returns>
  1241. /// <value>The fast seek command line parameter.</value>
  1242. public string GetFastSeekCommandLineParameter(BaseEncodingJobOptions request)
  1243. {
  1244. var time = request.StartTimeTicks ?? 0;
  1245. if (time > 0)
  1246. {
  1247. return string.Format("-ss {0}", _mediaEncoder.GetTimeParameter(time));
  1248. }
  1249. return string.Empty;
  1250. }
  1251. /// <summary>
  1252. /// Gets the map args.
  1253. /// </summary>
  1254. /// <param name="state">The state.</param>
  1255. /// <returns>System.String.</returns>
  1256. public string GetMapArgs(EncodingJobInfo state)
  1257. {
  1258. // If we don't have known media info
  1259. // If input is video, use -sn to drop subtitles
  1260. // Otherwise just return empty
  1261. if (state.VideoStream == null && state.AudioStream == null)
  1262. {
  1263. return state.IsInputVideo ? "-sn" : string.Empty;
  1264. }
  1265. // We have media info, but we don't know the stream indexes
  1266. if (state.VideoStream != null && state.VideoStream.Index == -1)
  1267. {
  1268. return "-sn";
  1269. }
  1270. // We have media info, but we don't know the stream indexes
  1271. if (state.AudioStream != null && state.AudioStream.Index == -1)
  1272. {
  1273. return state.IsInputVideo ? "-sn" : string.Empty;
  1274. }
  1275. var args = string.Empty;
  1276. if (state.VideoStream != null)
  1277. {
  1278. args += string.Format(
  1279. CultureInfo.InvariantCulture,
  1280. "-map 0:{0}",
  1281. state.VideoStream.Index);
  1282. }
  1283. else
  1284. {
  1285. // No known video stream
  1286. args += "-vn";
  1287. }
  1288. if (state.AudioStream != null)
  1289. {
  1290. args += string.Format(
  1291. CultureInfo.InvariantCulture,
  1292. " -map 0:{0}",
  1293. state.AudioStream.Index);
  1294. }
  1295. else
  1296. {
  1297. args += " -map -0:a";
  1298. }
  1299. var subtitleMethod = state.SubtitleDeliveryMethod;
  1300. if (state.SubtitleStream == null || subtitleMethod == SubtitleDeliveryMethod.Hls)
  1301. {
  1302. args += " -map -0:s";
  1303. }
  1304. else if (subtitleMethod == SubtitleDeliveryMethod.Embed)
  1305. {
  1306. args += string.Format(
  1307. CultureInfo.InvariantCulture,
  1308. " -map 0:{0}",
  1309. state.SubtitleStream.Index);
  1310. }
  1311. else if (state.SubtitleStream.IsExternal && !state.SubtitleStream.IsTextSubtitleStream)
  1312. {
  1313. args += " -map 1:0 -sn";
  1314. }
  1315. return args;
  1316. }
  1317. /// <summary>
  1318. /// Determines which stream will be used for playback.
  1319. /// </summary>
  1320. /// <param name="allStream">All stream.</param>
  1321. /// <param name="desiredIndex">Index of the desired.</param>
  1322. /// <param name="type">The type.</param>
  1323. /// <param name="returnFirstIfNoIndex">if set to <c>true</c> [return first if no index].</param>
  1324. /// <returns>MediaStream.</returns>
  1325. public MediaStream GetMediaStream(IEnumerable<MediaStream> allStream, int? desiredIndex, MediaStreamType type, bool returnFirstIfNoIndex = true)
  1326. {
  1327. var streams = allStream.Where(s => s.Type == type).OrderBy(i => i.Index).ToList();
  1328. if (desiredIndex.HasValue)
  1329. {
  1330. var stream = streams.FirstOrDefault(s => s.Index == desiredIndex.Value);
  1331. if (stream != null)
  1332. {
  1333. return stream;
  1334. }
  1335. }
  1336. if (returnFirstIfNoIndex && type == MediaStreamType.Audio)
  1337. {
  1338. return streams.FirstOrDefault(i => i.Channels.HasValue && i.Channels.Value > 0) ??
  1339. streams.FirstOrDefault();
  1340. }
  1341. // Just return the first one
  1342. return returnFirstIfNoIndex ? streams.FirstOrDefault() : null;
  1343. }
  1344. /// <summary>
  1345. /// Gets the graphical subtitle param.
  1346. /// </summary>
  1347. public string GetGraphicalSubtitleParam(
  1348. EncodingJobInfo state,
  1349. EncodingOptions options,
  1350. string outputVideoCodec)
  1351. {
  1352. outputVideoCodec ??= string.Empty;
  1353. var outputSizeParam = string.Empty;
  1354. var request = state.BaseRequest;
  1355. // Add resolution params, if specified
  1356. if (request.Width.HasValue
  1357. || request.Height.HasValue
  1358. || request.MaxHeight.HasValue
  1359. || request.MaxWidth.HasValue)
  1360. {
  1361. outputSizeParam = GetOutputSizeParam(state, options, outputVideoCodec).TrimEnd('"');
  1362. var index = outputSizeParam.IndexOf("hwdownload", StringComparison.OrdinalIgnoreCase);
  1363. if (index != -1)
  1364. {
  1365. outputSizeParam = outputSizeParam.Substring(index);
  1366. }
  1367. else
  1368. {
  1369. index = outputSizeParam.IndexOf("hwupload=extra_hw_frames", StringComparison.OrdinalIgnoreCase);
  1370. if (index != -1)
  1371. {
  1372. outputSizeParam = outputSizeParam.Substring(index);
  1373. }
  1374. else
  1375. {
  1376. index = outputSizeParam.IndexOf("format", StringComparison.OrdinalIgnoreCase);
  1377. if (index != -1)
  1378. {
  1379. outputSizeParam = outputSizeParam.Substring(index);
  1380. }
  1381. else
  1382. {
  1383. index = outputSizeParam.IndexOf("yadif", StringComparison.OrdinalIgnoreCase);
  1384. if (index != -1)
  1385. {
  1386. outputSizeParam = outputSizeParam.Substring(index);
  1387. }
  1388. else
  1389. {
  1390. index = outputSizeParam.IndexOf("scale", StringComparison.OrdinalIgnoreCase);
  1391. if (index != -1)
  1392. {
  1393. outputSizeParam = outputSizeParam.Substring(index);
  1394. }
  1395. else
  1396. {
  1397. index = outputSizeParam.IndexOf("vpp", StringComparison.OrdinalIgnoreCase);
  1398. if (index != -1)
  1399. {
  1400. outputSizeParam = outputSizeParam.Substring(index);
  1401. }
  1402. }
  1403. }
  1404. }
  1405. }
  1406. }
  1407. }
  1408. var videoSizeParam = string.Empty;
  1409. var videoDecoder = GetHardwareAcceleratedVideoDecoder(state, options) ?? string.Empty;
  1410. var isLinux = RuntimeInformation.IsOSPlatform(OSPlatform.Linux);
  1411. // Setup subtitle scaling
  1412. if (state.VideoStream != null && state.VideoStream.Width.HasValue && state.VideoStream.Height.HasValue)
  1413. {
  1414. // Adjust the size of graphical subtitles to fit the video stream.
  1415. var videoStream = state.VideoStream;
  1416. var inputWidth = videoStream?.Width;
  1417. var inputHeight = videoStream?.Height;
  1418. var (width, height) = GetFixedOutputSize(inputWidth, inputHeight, request.Width, request.Height, request.MaxWidth, request.MaxHeight);
  1419. if (width.HasValue && height.HasValue)
  1420. {
  1421. videoSizeParam = string.Format(
  1422. CultureInfo.InvariantCulture,
  1423. "scale={0}x{1}",
  1424. width.Value,
  1425. height.Value);
  1426. }
  1427. // For QSV, feed it into hardware encoder now
  1428. if (isLinux && string.Equals(outputVideoCodec, "h264_qsv", StringComparison.OrdinalIgnoreCase))
  1429. {
  1430. videoSizeParam += ",hwupload=extra_hw_frames=64";
  1431. }
  1432. }
  1433. var mapPrefix = state.SubtitleStream.IsExternal ?
  1434. 1 :
  1435. 0;
  1436. var subtitleStreamIndex = state.SubtitleStream.IsExternal
  1437. ? 0
  1438. : state.SubtitleStream.Index;
  1439. // Setup default filtergraph utilizing FFMpeg overlay() and FFMpeg scale() (see the return of this function for index reference)
  1440. // Always put the scaler before the overlay for better performance
  1441. var retStr = !string.IsNullOrEmpty(outputSizeParam) ?
  1442. " -filter_complex \"[{0}:{1}]{4}[sub];[0:{2}]{3}[base];[base][sub]overlay\"" :
  1443. " -filter_complex \"[{0}:{1}]{4}[sub];[0:{2}][sub]overlay\"";
  1444. // When the input may or may not be hardware VAAPI decodable
  1445. if (string.Equals(outputVideoCodec, "h264_vaapi", StringComparison.OrdinalIgnoreCase))
  1446. {
  1447. /*
  1448. [base]: HW scaling video to OutputSize
  1449. [sub]: SW scaling subtitle to FixedOutputSize
  1450. [base][sub]: SW overlay
  1451. */
  1452. retStr = " -filter_complex \"[{0}:{1}]{4}[sub];[0:{2}]{3},hwdownload[base];[base][sub]overlay,format=nv12,hwupload\"";
  1453. }
  1454. // If we're hardware VAAPI decoding and software encoding, download frames from the decoder first
  1455. else if (_mediaEncoder.SupportsHwaccel("vaapi") && videoDecoder.IndexOf("vaapi", StringComparison.OrdinalIgnoreCase) != -1
  1456. && string.Equals(outputVideoCodec, "libx264", StringComparison.OrdinalIgnoreCase))
  1457. {
  1458. /*
  1459. [base]: SW scaling video to OutputSize
  1460. [sub]: SW scaling subtitle to FixedOutputSize
  1461. [base][sub]: SW overlay
  1462. */
  1463. retStr = " -filter_complex \"[{0}:{1}]{4}[sub];[0:{2}]{3}[base];[base][sub]overlay\"";
  1464. }
  1465. else if (string.Equals(outputVideoCodec, "h264_qsv", StringComparison.OrdinalIgnoreCase))
  1466. {
  1467. /*
  1468. QSV in FFMpeg can now setup hardware overlay for transcodes.
  1469. For software decoding and hardware encoding option, frames must be hwuploaded into hardware
  1470. with fixed frame size.
  1471. Currently only supports linux.
  1472. */
  1473. if (isLinux)
  1474. {
  1475. retStr = !string.IsNullOrEmpty(outputSizeParam) ?
  1476. " -filter_complex \"[{0}:{1}]{4}[sub];[0:{2}]{3}[base];[base][sub]overlay_qsv\"" :
  1477. " -filter_complex \"[{0}:{1}]{4}[sub];[0:{2}][sub]overlay_qsv\"";
  1478. }
  1479. }
  1480. return string.Format(
  1481. CultureInfo.InvariantCulture,
  1482. retStr,
  1483. mapPrefix,
  1484. subtitleStreamIndex,
  1485. state.VideoStream.Index,
  1486. outputSizeParam,
  1487. videoSizeParam);
  1488. }
  1489. private (int? width, int? height) GetFixedOutputSize(
  1490. int? videoWidth,
  1491. int? videoHeight,
  1492. int? requestedWidth,
  1493. int? requestedHeight,
  1494. int? requestedMaxWidth,
  1495. int? requestedMaxHeight)
  1496. {
  1497. if (!videoWidth.HasValue && !requestedWidth.HasValue)
  1498. {
  1499. return (null, null);
  1500. }
  1501. if (!videoHeight.HasValue && !requestedHeight.HasValue)
  1502. {
  1503. return (null, null);
  1504. }
  1505. decimal inputWidth = Convert.ToDecimal(videoWidth ?? requestedWidth);
  1506. decimal inputHeight = Convert.ToDecimal(videoHeight ?? requestedHeight);
  1507. decimal outputWidth = requestedWidth.HasValue ? Convert.ToDecimal(requestedWidth.Value) : inputWidth;
  1508. decimal outputHeight = requestedHeight.HasValue ? Convert.ToDecimal(requestedHeight.Value) : inputHeight;
  1509. decimal maximumWidth = requestedMaxWidth.HasValue ? Convert.ToDecimal(requestedMaxWidth.Value) : outputWidth;
  1510. decimal maximumHeight = requestedMaxHeight.HasValue ? Convert.ToDecimal(requestedMaxHeight.Value) : outputHeight;
  1511. if (outputWidth > maximumWidth || outputHeight > maximumHeight)
  1512. {
  1513. var scale = Math.Min(maximumWidth / outputWidth, maximumHeight / outputHeight);
  1514. outputWidth = Math.Min(maximumWidth, Math.Truncate(outputWidth * scale));
  1515. outputHeight = Math.Min(maximumHeight, Math.Truncate(outputHeight * scale));
  1516. }
  1517. outputWidth = 2 * Math.Truncate(outputWidth / 2);
  1518. outputHeight = 2 * Math.Truncate(outputHeight / 2);
  1519. return (Convert.ToInt32(outputWidth), Convert.ToInt32(outputHeight));
  1520. }
  1521. public List<string> GetScalingFilters(EncodingJobInfo state,
  1522. int? videoWidth,
  1523. int? videoHeight,
  1524. Video3DFormat? threedFormat,
  1525. string videoDecoder,
  1526. string videoEncoder,
  1527. int? requestedWidth,
  1528. int? requestedHeight,
  1529. int? requestedMaxWidth,
  1530. int? requestedMaxHeight)
  1531. {
  1532. var filters = new List<string>();
  1533. var (width, height) = GetFixedOutputSize(
  1534. videoWidth,
  1535. videoHeight,
  1536. requestedWidth,
  1537. requestedHeight,
  1538. requestedMaxWidth,
  1539. requestedMaxHeight);
  1540. if ((string.Equals(videoEncoder, "h264_vaapi", StringComparison.OrdinalIgnoreCase)
  1541. || string.Equals(videoEncoder, "h264_qsv", StringComparison.OrdinalIgnoreCase))
  1542. && width.HasValue
  1543. && height.HasValue)
  1544. {
  1545. // Given the input dimensions (inputWidth, inputHeight), determine the output dimensions
  1546. // (outputWidth, outputHeight). The user may request precise output dimensions or maximum
  1547. // output dimensions. Output dimensions are guaranteed to be even.
  1548. var outputWidth = width.Value;
  1549. var outputHeight = height.Value;
  1550. var qsv_or_vaapi = string.Equals(videoEncoder, "h264_qsv", StringComparison.OrdinalIgnoreCase);
  1551. var isDeintEnabled = state.DeInterlace("h264", true)
  1552. || state.DeInterlace("avc", true)
  1553. || state.DeInterlace("h265", true)
  1554. || state.DeInterlace("hevc", true);
  1555. if (!videoWidth.HasValue
  1556. || outputWidth != videoWidth.Value
  1557. || !videoHeight.HasValue
  1558. || outputHeight != videoHeight.Value)
  1559. {
  1560. // Force nv12 pixel format to enable 10-bit to 8-bit colour conversion.
  1561. // use vpp_qsv filter to avoid green bar when the fixed output size is requested.
  1562. filters.Add(
  1563. string.Format(
  1564. CultureInfo.InvariantCulture,
  1565. "{0}=w={1}:h={2}:format=nv12{3}",
  1566. qsv_or_vaapi ? "vpp_qsv" : "scale_vaapi",
  1567. outputWidth,
  1568. outputHeight,
  1569. (qsv_or_vaapi && isDeintEnabled) ? ":deinterlace=1" : string.Empty));
  1570. }
  1571. else
  1572. {
  1573. filters.Add(
  1574. string.Format(
  1575. CultureInfo.InvariantCulture,
  1576. "{0}=format=nv12{1}",
  1577. qsv_or_vaapi ? "vpp_qsv" : "scale_vaapi",
  1578. (qsv_or_vaapi && isDeintEnabled) ? ":deinterlace=1" : string.Empty));
  1579. }
  1580. }
  1581. else if ((videoDecoder ?? string.Empty).IndexOf("cuvid", StringComparison.OrdinalIgnoreCase) != -1
  1582. && width.HasValue
  1583. && height.HasValue)
  1584. {
  1585. // Nothing to do, it's handled as an input resize filter
  1586. }
  1587. else
  1588. {
  1589. var isExynosV4L2 = string.Equals(videoEncoder, "h264_v4l2m2m", StringComparison.OrdinalIgnoreCase);
  1590. // If fixed dimensions were supplied
  1591. if (requestedWidth.HasValue && requestedHeight.HasValue)
  1592. {
  1593. if (isExynosV4L2)
  1594. {
  1595. var widthParam = requestedWidth.Value.ToString(_usCulture);
  1596. var heightParam = requestedHeight.Value.ToString(_usCulture);
  1597. filters.Add(
  1598. string.Format(
  1599. CultureInfo.InvariantCulture,
  1600. "scale=trunc({0}/64)*64:trunc({1}/2)*2",
  1601. widthParam,
  1602. heightParam));
  1603. }
  1604. else
  1605. {
  1606. filters.Add(GetFixedSizeScalingFilter(threedFormat, requestedWidth.Value, requestedHeight.Value));
  1607. }
  1608. }
  1609. // 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
  1610. else if (requestedMaxWidth.HasValue && requestedMaxHeight.HasValue)
  1611. {
  1612. var maxWidthParam = requestedMaxWidth.Value.ToString(_usCulture);
  1613. var maxHeightParam = requestedMaxHeight.Value.ToString(_usCulture);
  1614. if (isExynosV4L2)
  1615. {
  1616. filters.Add(
  1617. string.Format(
  1618. CultureInfo.InvariantCulture,
  1619. "scale=trunc(min(max(iw\\,ih*dar)\\,min({0}\\,{1}*dar))/64)*64:trunc(min(max(iw/dar\\,ih)\\,min({0}/dar\\,{1}))/2)*2",
  1620. maxWidthParam,
  1621. maxHeightParam));
  1622. }
  1623. else
  1624. {
  1625. filters.Add(
  1626. string.Format(
  1627. CultureInfo.InvariantCulture,
  1628. "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",
  1629. maxWidthParam,
  1630. maxHeightParam));
  1631. }
  1632. }
  1633. // If a fixed width was requested
  1634. else if (requestedWidth.HasValue)
  1635. {
  1636. if (threedFormat.HasValue)
  1637. {
  1638. // This method can handle 0 being passed in for the requested height
  1639. filters.Add(GetFixedSizeScalingFilter(threedFormat, requestedWidth.Value, 0));
  1640. }
  1641. else
  1642. {
  1643. var widthParam = requestedWidth.Value.ToString(_usCulture);
  1644. filters.Add(
  1645. string.Format(
  1646. CultureInfo.InvariantCulture,
  1647. "scale={0}:trunc(ow/a/2)*2",
  1648. widthParam));
  1649. }
  1650. }
  1651. // If a fixed height was requested
  1652. else if (requestedHeight.HasValue)
  1653. {
  1654. var heightParam = requestedHeight.Value.ToString(_usCulture);
  1655. if (isExynosV4L2)
  1656. {
  1657. filters.Add(
  1658. string.Format(
  1659. CultureInfo.InvariantCulture,
  1660. "scale=trunc(oh*a/64)*64:{0}",
  1661. heightParam));
  1662. }
  1663. else
  1664. {
  1665. filters.Add(
  1666. string.Format(
  1667. CultureInfo.InvariantCulture,
  1668. "scale=trunc(oh*a/2)*2:{0}",
  1669. heightParam));
  1670. }
  1671. }
  1672. // If a max width was requested
  1673. else if (requestedMaxWidth.HasValue)
  1674. {
  1675. var maxWidthParam = requestedMaxWidth.Value.ToString(_usCulture);
  1676. if (isExynosV4L2)
  1677. {
  1678. filters.Add(
  1679. string.Format(
  1680. CultureInfo.InvariantCulture,
  1681. "scale=trunc(min(max(iw\\,ih*dar)\\,{0})/64)*64:trunc(ow/dar/2)*2",
  1682. maxWidthParam));
  1683. }
  1684. else
  1685. {
  1686. filters.Add(
  1687. string.Format(
  1688. CultureInfo.InvariantCulture,
  1689. "scale=trunc(min(max(iw\\,ih*dar)\\,{0})/2)*2:trunc(ow/dar/2)*2",
  1690. maxWidthParam));
  1691. }
  1692. }
  1693. // If a max height was requested
  1694. else if (requestedMaxHeight.HasValue)
  1695. {
  1696. var maxHeightParam = requestedMaxHeight.Value.ToString(_usCulture);
  1697. if (isExynosV4L2)
  1698. {
  1699. filters.Add(
  1700. string.Format(
  1701. CultureInfo.InvariantCulture,
  1702. "scale=trunc(oh*a/64)*64:min(max(iw/dar\\,ih)\\,{0})",
  1703. maxHeightParam));
  1704. }
  1705. else
  1706. {
  1707. filters.Add(
  1708. string.Format(
  1709. CultureInfo.InvariantCulture,
  1710. "scale=trunc(oh*a/2)*2:min(max(iw/dar\\,ih)\\,{0})",
  1711. maxHeightParam));
  1712. }
  1713. }
  1714. }
  1715. return filters;
  1716. }
  1717. private string GetFixedSizeScalingFilter(Video3DFormat? threedFormat, int requestedWidth, int requestedHeight)
  1718. {
  1719. var widthParam = requestedWidth.ToString(CultureInfo.InvariantCulture);
  1720. var heightParam = requestedHeight.ToString(CultureInfo.InvariantCulture);
  1721. string filter = null;
  1722. if (threedFormat.HasValue)
  1723. {
  1724. switch (threedFormat.Value)
  1725. {
  1726. case Video3DFormat.HalfSideBySide:
  1727. filter = "crop=iw/2:ih:0:0,scale=(iw*2):ih,setdar=dar=a,crop=min(iw\\,ih*dar):min(ih\\,iw/dar):(iw-min(iw\\,iw*sar))/2:(ih - min (ih\\,ih/sar))/2,setsar=sar=1,scale={0}:trunc({0}/dar/2)*2";
  1728. // hsbs crop width in half,scale to correct size, set the display aspect,crop out any black bars we may have made the scale width to requestedWidth. Work out the correct height based on the display aspect it will maintain the aspect where -1 in this case (3d) may not.
  1729. break;
  1730. case Video3DFormat.FullSideBySide:
  1731. filter = "crop=iw/2:ih:0:0,setdar=dar=a,crop=min(iw\\,ih*dar):min(ih\\,iw/dar):(iw-min(iw\\,iw*sar))/2:(ih - min (ih\\,ih/sar))/2,setsar=sar=1,scale={0}:trunc({0}/dar/2)*2";
  1732. // fsbs crop width in half,set the display aspect,crop out any black bars we may have made the scale width to requestedWidth.
  1733. break;
  1734. case Video3DFormat.HalfTopAndBottom:
  1735. filter = "crop=iw:ih/2:0:0,scale=(iw*2):ih),setdar=dar=a,crop=min(iw\\,ih*dar):min(ih\\,iw/dar):(iw-min(iw\\,iw*sar))/2:(ih - min (ih\\,ih/sar))/2,setsar=sar=1,scale={0}:trunc({0}/dar/2)*2";
  1736. // htab crop height in half,scale to correct size, set the display aspect,crop out any black bars we may have made the scale width to requestedWidth
  1737. break;
  1738. case Video3DFormat.FullTopAndBottom:
  1739. filter = "crop=iw:ih/2:0:0,setdar=dar=a,crop=min(iw\\,ih*dar):min(ih\\,iw/dar):(iw-min(iw\\,iw*sar))/2:(ih - min (ih\\,ih/sar))/2,setsar=sar=1,scale={0}:trunc({0}/dar/2)*2";
  1740. // ftab crop height in half, set the display aspect,crop out any black bars we may have made the scale width to requestedWidth
  1741. break;
  1742. default:
  1743. break;
  1744. }
  1745. }
  1746. // default
  1747. if (filter == null)
  1748. {
  1749. if (requestedHeight > 0)
  1750. {
  1751. filter = "scale=trunc({0}/2)*2:trunc({1}/2)*2";
  1752. }
  1753. else
  1754. {
  1755. filter = "scale={0}:trunc({0}/dar/2)*2";
  1756. }
  1757. }
  1758. return string.Format(CultureInfo.InvariantCulture, filter, widthParam, heightParam);
  1759. }
  1760. /// <summary>
  1761. /// If we're going to put a fixed size on the command line, this will calculate it.
  1762. /// </summary>
  1763. public string GetOutputSizeParam(
  1764. EncodingJobInfo state,
  1765. EncodingOptions options,
  1766. string outputVideoCodec)
  1767. {
  1768. // http://sonnati.wordpress.com/2012/10/19/ffmpeg-the-swiss-army-knife-of-internet-streaming-part-vi/
  1769. var request = state.BaseRequest;
  1770. var videoStream = state.VideoStream;
  1771. var filters = new List<string>();
  1772. var videoDecoder = GetHardwareAcceleratedVideoDecoder(state, options) ?? string.Empty;
  1773. var inputWidth = videoStream?.Width;
  1774. var inputHeight = videoStream?.Height;
  1775. var threeDFormat = state.MediaSource.Video3DFormat;
  1776. var isVaapiDecoder = videoDecoder.IndexOf("vaapi", StringComparison.OrdinalIgnoreCase) != -1;
  1777. var isVaapiH264Encoder = outputVideoCodec.IndexOf("h264_vaapi", StringComparison.OrdinalIgnoreCase) != -1;
  1778. var isQsvH264Encoder = outputVideoCodec.IndexOf("h264_qsv", StringComparison.OrdinalIgnoreCase) != -1;
  1779. var isNvdecH264Decoder = videoDecoder.IndexOf("h264_cuvid", StringComparison.OrdinalIgnoreCase) != -1;
  1780. var isLibX264Encoder = outputVideoCodec.IndexOf("libx264", StringComparison.OrdinalIgnoreCase) != -1;
  1781. var isLinux = RuntimeInformation.IsOSPlatform(OSPlatform.Linux);
  1782. var hasTextSubs = state.SubtitleStream != null && state.SubtitleStream.IsTextSubtitleStream && state.SubtitleDeliveryMethod == SubtitleDeliveryMethod.Encode;
  1783. var hasGraphicalSubs = state.SubtitleStream != null && !state.SubtitleStream.IsTextSubtitleStream && state.SubtitleDeliveryMethod == SubtitleDeliveryMethod.Encode;
  1784. // When the input may or may not be hardware VAAPI decodable
  1785. if (isVaapiH264Encoder)
  1786. {
  1787. filters.Add("format=nv12|vaapi");
  1788. filters.Add("hwupload");
  1789. }
  1790. // When burning in graphical subtitles using overlay_qsv, upload videostream to the same qsv context
  1791. else if (isLinux && hasGraphicalSubs && isQsvH264Encoder)
  1792. {
  1793. filters.Add("hwupload=extra_hw_frames=64");
  1794. }
  1795. // If we're hardware VAAPI decoding and software encoding, download frames from the decoder first
  1796. else if (IsVaapiSupported(state) && isVaapiDecoder && isLibX264Encoder)
  1797. {
  1798. var codec = videoStream.Codec.ToLowerInvariant();
  1799. var isColorDepth10 = IsColorDepth10(state);
  1800. // Assert 10-bit hardware VAAPI decodable
  1801. if (isColorDepth10 && (string.Equals(codec, "hevc", StringComparison.OrdinalIgnoreCase)
  1802. || string.Equals(codec, "h265", StringComparison.OrdinalIgnoreCase)
  1803. || string.Equals(codec, "vp9", StringComparison.OrdinalIgnoreCase)))
  1804. {
  1805. /*
  1806. Download data from GPU to CPU as p010le format.
  1807. Colorspace conversion is unnecessary here as libx264 will handle it.
  1808. If this step is missing, it will fail on AMD but not on intel.
  1809. */
  1810. filters.Add("hwdownload");
  1811. filters.Add("format=p010le");
  1812. }
  1813. // Assert 8-bit hardware VAAPI decodable
  1814. else if (!isColorDepth10)
  1815. {
  1816. filters.Add("hwdownload");
  1817. filters.Add("format=nv12");
  1818. }
  1819. }
  1820. // Add hardware deinterlace filter before scaling filter
  1821. if (state.DeInterlace("h264", true) || state.DeInterlace("avc", true))
  1822. {
  1823. if (isVaapiH264Encoder)
  1824. {
  1825. filters.Add(string.Format(CultureInfo.InvariantCulture, "deinterlace_vaapi"));
  1826. }
  1827. }
  1828. // Add software deinterlace filter before scaling filter
  1829. if (state.DeInterlace("h264", true)
  1830. || state.DeInterlace("avc", true)
  1831. || state.DeInterlace("h265", true)
  1832. || state.DeInterlace("hevc", true))
  1833. {
  1834. var deintParam = string.Empty;
  1835. var inputFramerate = videoStream?.RealFrameRate;
  1836. // If it is already 60fps then it will create an output framerate that is much too high for roku and others to handle
  1837. if (string.Equals(options.DeinterlaceMethod, "yadif_bob", StringComparison.OrdinalIgnoreCase) && (inputFramerate ?? 60) <= 30)
  1838. {
  1839. deintParam = "yadif=1:-1:0";
  1840. }
  1841. else
  1842. {
  1843. deintParam = "yadif=0:-1:0";
  1844. }
  1845. if (!string.IsNullOrEmpty(deintParam))
  1846. {
  1847. if (!isVaapiH264Encoder && !isQsvH264Encoder && !isNvdecH264Decoder)
  1848. {
  1849. filters.Add(deintParam);
  1850. }
  1851. }
  1852. }
  1853. // Add scaling filter: scale_*=format=nv12 or scale_*=w=*:h=*:format=nv12 or scale=expr
  1854. filters.AddRange(GetScalingFilters(state, inputWidth, inputHeight, threeDFormat, videoDecoder, outputVideoCodec, request.Width, request.Height, request.MaxWidth, request.MaxHeight));
  1855. // Add parameters to use VAAPI with burn-in text subtitles (GH issue #642)
  1856. if (isVaapiH264Encoder)
  1857. {
  1858. if (hasTextSubs)
  1859. {
  1860. // Test passed on Intel and AMD gfx
  1861. filters.Add("hwmap=mode=read+write");
  1862. filters.Add("format=nv12");
  1863. }
  1864. }
  1865. var output = string.Empty;
  1866. if (hasTextSubs)
  1867. {
  1868. var subParam = GetTextSubtitleParam(state);
  1869. filters.Add(subParam);
  1870. // Ensure proper filters are passed to ffmpeg in case of hardware acceleration via VA-API
  1871. // Reference: https://trac.ffmpeg.org/wiki/Hardware/VAAPI
  1872. if (isVaapiH264Encoder)
  1873. {
  1874. filters.Add("hwmap");
  1875. }
  1876. }
  1877. if (filters.Count > 0)
  1878. {
  1879. output += string.Format(
  1880. CultureInfo.InvariantCulture,
  1881. " -vf \"{0}\"",
  1882. string.Join(",", filters));
  1883. }
  1884. return output;
  1885. }
  1886. /// <summary>
  1887. /// Gets the number of threads.
  1888. /// </summary>
  1889. public int GetNumberOfThreads(EncodingJobInfo state, EncodingOptions encodingOptions, string outputVideoCodec)
  1890. {
  1891. if (string.Equals(outputVideoCodec, "libvpx", StringComparison.OrdinalIgnoreCase))
  1892. {
  1893. // per docs:
  1894. // -threads number of threads to use for encoding, can't be 0 [auto] with VP8
  1895. // (recommended value : number of real cores - 1)
  1896. return Math.Max(Environment.ProcessorCount - 1, 1);
  1897. }
  1898. var threads = state.BaseRequest.CpuCoreLimit ?? encodingOptions.EncodingThreadCount;
  1899. // Automatic
  1900. if (threads <= 0 || threads >= Environment.ProcessorCount)
  1901. {
  1902. return 0;
  1903. }
  1904. return threads;
  1905. }
  1906. public void TryStreamCopy(EncodingJobInfo state)
  1907. {
  1908. if (state.VideoStream != null && CanStreamCopyVideo(state, state.VideoStream))
  1909. {
  1910. state.OutputVideoCodec = "copy";
  1911. }
  1912. else
  1913. {
  1914. var user = state.User;
  1915. // If the user doesn't have access to transcoding, then force stream copy, regardless of whether it will be compatible or not
  1916. if (user != null && !user.HasPermission(PermissionKind.EnableVideoPlaybackTranscoding))
  1917. {
  1918. state.OutputVideoCodec = "copy";
  1919. }
  1920. }
  1921. if (state.AudioStream != null
  1922. && CanStreamCopyAudio(state, state.AudioStream, state.SupportedAudioCodecs))
  1923. {
  1924. state.OutputAudioCodec = "copy";
  1925. }
  1926. else
  1927. {
  1928. var user = state.User;
  1929. // If the user doesn't have access to transcoding, then force stream copy, regardless of whether it will be compatible or not
  1930. if (user != null && !user.HasPermission(PermissionKind.EnableAudioPlaybackTranscoding))
  1931. {
  1932. state.OutputAudioCodec = "copy";
  1933. }
  1934. }
  1935. }
  1936. public string GetProbeSizeArgument(int numInputFiles)
  1937. => numInputFiles > 1 ? "-probesize " + _configuration.GetFFmpegProbeSize() : string.Empty;
  1938. public string GetAnalyzeDurationArgument(int numInputFiles)
  1939. => numInputFiles > 1 ? "-analyzeduration " + _configuration.GetFFmpegAnalyzeDuration() : string.Empty;
  1940. public string GetInputModifier(EncodingJobInfo state, EncodingOptions encodingOptions)
  1941. {
  1942. var inputModifier = string.Empty;
  1943. var numInputFiles = state.PlayableStreamFileNames.Length > 0 ? state.PlayableStreamFileNames.Length : 1;
  1944. var probeSizeArgument = GetProbeSizeArgument(numInputFiles);
  1945. string analyzeDurationArgument;
  1946. if (state.MediaSource.AnalyzeDurationMs.HasValue)
  1947. {
  1948. analyzeDurationArgument = "-analyzeduration " + (state.MediaSource.AnalyzeDurationMs.Value * 1000).ToString(CultureInfo.InvariantCulture);
  1949. }
  1950. else
  1951. {
  1952. analyzeDurationArgument = GetAnalyzeDurationArgument(numInputFiles);
  1953. }
  1954. if (!string.IsNullOrEmpty(probeSizeArgument))
  1955. {
  1956. inputModifier += " " + probeSizeArgument;
  1957. }
  1958. if (!string.IsNullOrEmpty(analyzeDurationArgument))
  1959. {
  1960. inputModifier += " " + analyzeDurationArgument;
  1961. }
  1962. inputModifier = inputModifier.Trim();
  1963. var userAgentParam = GetUserAgentParam(state);
  1964. if (!string.IsNullOrEmpty(userAgentParam))
  1965. {
  1966. inputModifier += " " + userAgentParam;
  1967. }
  1968. inputModifier = inputModifier.Trim();
  1969. inputModifier += " " + GetFastSeekCommandLineParameter(state.BaseRequest);
  1970. inputModifier = inputModifier.Trim();
  1971. if (state.InputProtocol == MediaProtocol.Rtsp)
  1972. {
  1973. inputModifier += " -rtsp_transport tcp -rtsp_transport udp -rtsp_flags prefer_tcp";
  1974. }
  1975. if (!string.IsNullOrEmpty(state.InputAudioSync))
  1976. {
  1977. inputModifier += " -async " + state.InputAudioSync;
  1978. }
  1979. if (!string.IsNullOrEmpty(state.InputVideoSync))
  1980. {
  1981. inputModifier += " -vsync " + state.InputVideoSync;
  1982. }
  1983. if (state.ReadInputAtNativeFramerate && state.InputProtocol != MediaProtocol.Rtsp)
  1984. {
  1985. inputModifier += " -re";
  1986. }
  1987. var flags = new List<string>();
  1988. if (state.IgnoreInputDts)
  1989. {
  1990. flags.Add("+igndts");
  1991. }
  1992. if (state.IgnoreInputIndex)
  1993. {
  1994. flags.Add("+ignidx");
  1995. }
  1996. if (state.GenPtsInput || IsCopyCodec(state.OutputVideoCodec))
  1997. {
  1998. flags.Add("+genpts");
  1999. }
  2000. if (state.DiscardCorruptFramesInput)
  2001. {
  2002. flags.Add("+discardcorrupt");
  2003. }
  2004. if (state.EnableFastSeekInput)
  2005. {
  2006. flags.Add("+fastseek");
  2007. }
  2008. if (flags.Count > 0)
  2009. {
  2010. inputModifier += " -fflags " + string.Join(string.Empty, flags);
  2011. }
  2012. var videoDecoder = GetHardwareAcceleratedVideoDecoder(state, encodingOptions);
  2013. if (!string.IsNullOrEmpty(videoDecoder))
  2014. {
  2015. inputModifier += " " + videoDecoder;
  2016. if (!IsCopyCodec(state.OutputVideoCodec)
  2017. && (videoDecoder ?? string.Empty).IndexOf("cuvid", StringComparison.OrdinalIgnoreCase) != -1)
  2018. {
  2019. var videoStream = state.VideoStream;
  2020. var inputWidth = videoStream?.Width;
  2021. var inputHeight = videoStream?.Height;
  2022. var request = state.BaseRequest;
  2023. var (width, height) = GetFixedOutputSize(inputWidth, inputHeight, request.Width, request.Height, request.MaxWidth, request.MaxHeight);
  2024. if ((videoDecoder ?? string.Empty).IndexOf("cuvid", StringComparison.OrdinalIgnoreCase) != -1
  2025. && width.HasValue
  2026. && height.HasValue)
  2027. {
  2028. if (width.HasValue && height.HasValue)
  2029. {
  2030. inputModifier += string.Format(
  2031. CultureInfo.InvariantCulture,
  2032. " -resize {0}x{1}",
  2033. width.Value,
  2034. height.Value);
  2035. }
  2036. if (state.DeInterlace("h264", true))
  2037. {
  2038. inputModifier += " -deint 1";
  2039. }
  2040. }
  2041. }
  2042. }
  2043. if (state.IsVideoRequest)
  2044. {
  2045. var outputVideoCodec = GetVideoEncoder(state, encodingOptions);
  2046. // Important: If this is ever re-enabled, make sure not to use it with wtv because it breaks seeking
  2047. if (!string.Equals(state.InputContainer, "wtv", StringComparison.OrdinalIgnoreCase)
  2048. && state.TranscodingType != TranscodingJobType.Progressive
  2049. && !state.EnableBreakOnNonKeyFrames(outputVideoCodec)
  2050. && (state.BaseRequest.StartTimeTicks ?? 0) > 0)
  2051. {
  2052. inputModifier += " -noaccurate_seek";
  2053. }
  2054. if (!string.IsNullOrEmpty(state.InputContainer) && state.VideoType == VideoType.VideoFile && string.IsNullOrEmpty(encodingOptions.HardwareAccelerationType))
  2055. {
  2056. var inputFormat = GetInputFormat(state.InputContainer);
  2057. if (!string.IsNullOrEmpty(inputFormat))
  2058. {
  2059. inputModifier += " -f " + inputFormat;
  2060. }
  2061. }
  2062. }
  2063. if (state.MediaSource.RequiresLooping)
  2064. {
  2065. inputModifier += " -stream_loop -1 -reconnect_at_eof 1 -reconnect_streamed 1 -reconnect_delay_max 2";
  2066. }
  2067. return inputModifier;
  2068. }
  2069. public void AttachMediaSourceInfo(
  2070. EncodingJobInfo state,
  2071. MediaSourceInfo mediaSource,
  2072. string requestedUrl)
  2073. {
  2074. if (state == null)
  2075. {
  2076. throw new ArgumentNullException(nameof(state));
  2077. }
  2078. if (mediaSource == null)
  2079. {
  2080. throw new ArgumentNullException(nameof(mediaSource));
  2081. }
  2082. var path = mediaSource.Path;
  2083. var protocol = mediaSource.Protocol;
  2084. if (!string.IsNullOrEmpty(mediaSource.EncoderPath) && mediaSource.EncoderProtocol.HasValue)
  2085. {
  2086. path = mediaSource.EncoderPath;
  2087. protocol = mediaSource.EncoderProtocol.Value;
  2088. }
  2089. state.MediaPath = path;
  2090. state.InputProtocol = protocol;
  2091. state.InputContainer = mediaSource.Container;
  2092. state.RunTimeTicks = mediaSource.RunTimeTicks;
  2093. state.RemoteHttpHeaders = mediaSource.RequiredHttpHeaders;
  2094. state.IsoType = mediaSource.IsoType;
  2095. if (mediaSource.VideoType.HasValue)
  2096. {
  2097. state.VideoType = mediaSource.VideoType.Value;
  2098. if (mediaSource.VideoType.Value == VideoType.BluRay || mediaSource.VideoType.Value == VideoType.Dvd)
  2099. {
  2100. state.PlayableStreamFileNames = Video.QueryPlayableStreamFiles(state.MediaPath, mediaSource.VideoType.Value).Select(Path.GetFileName).ToArray();
  2101. }
  2102. else if (mediaSource.VideoType.Value == VideoType.Iso && state.IsoType == IsoType.BluRay)
  2103. {
  2104. state.PlayableStreamFileNames = Video.QueryPlayableStreamFiles(state.MediaPath, VideoType.BluRay).Select(Path.GetFileName).ToArray();
  2105. }
  2106. else if (mediaSource.VideoType.Value == VideoType.Iso && state.IsoType == IsoType.Dvd)
  2107. {
  2108. state.PlayableStreamFileNames = Video.QueryPlayableStreamFiles(state.MediaPath, VideoType.Dvd).Select(Path.GetFileName).ToArray();
  2109. }
  2110. else
  2111. {
  2112. state.PlayableStreamFileNames = Array.Empty<string>();
  2113. }
  2114. }
  2115. else
  2116. {
  2117. state.PlayableStreamFileNames = Array.Empty<string>();
  2118. }
  2119. if (mediaSource.Timestamp.HasValue)
  2120. {
  2121. state.InputTimestamp = mediaSource.Timestamp.Value;
  2122. }
  2123. state.RunTimeTicks = mediaSource.RunTimeTicks;
  2124. state.RemoteHttpHeaders = mediaSource.RequiredHttpHeaders;
  2125. state.ReadInputAtNativeFramerate = mediaSource.ReadAtNativeFramerate;
  2126. if (state.ReadInputAtNativeFramerate
  2127. || mediaSource.Protocol == MediaProtocol.File
  2128. && string.Equals(mediaSource.Container, "wtv", StringComparison.OrdinalIgnoreCase))
  2129. {
  2130. state.InputVideoSync = "-1";
  2131. state.InputAudioSync = "1";
  2132. }
  2133. if (string.Equals(mediaSource.Container, "wma", StringComparison.OrdinalIgnoreCase)
  2134. || string.Equals(mediaSource.Container, "asf", StringComparison.OrdinalIgnoreCase))
  2135. {
  2136. // Seeing some stuttering when transcoding wma to audio-only HLS
  2137. state.InputAudioSync = "1";
  2138. }
  2139. var mediaStreams = mediaSource.MediaStreams;
  2140. if (state.IsVideoRequest)
  2141. {
  2142. var videoRequest = state.BaseRequest;
  2143. if (string.IsNullOrEmpty(videoRequest.VideoCodec))
  2144. {
  2145. if (string.IsNullOrEmpty(requestedUrl))
  2146. {
  2147. requestedUrl = "test." + videoRequest.Container;
  2148. }
  2149. videoRequest.VideoCodec = InferVideoCodec(requestedUrl);
  2150. }
  2151. state.VideoStream = GetMediaStream(mediaStreams, videoRequest.VideoStreamIndex, MediaStreamType.Video);
  2152. state.SubtitleStream = GetMediaStream(mediaStreams, videoRequest.SubtitleStreamIndex, MediaStreamType.Subtitle, false);
  2153. state.SubtitleDeliveryMethod = videoRequest.SubtitleMethod;
  2154. state.AudioStream = GetMediaStream(mediaStreams, videoRequest.AudioStreamIndex, MediaStreamType.Audio);
  2155. if (state.SubtitleStream != null && !state.SubtitleStream.IsExternal)
  2156. {
  2157. state.InternalSubtitleStreamOffset = mediaStreams.Where(i => i.Type == MediaStreamType.Subtitle && !i.IsExternal).ToList().IndexOf(state.SubtitleStream);
  2158. }
  2159. EnforceResolutionLimit(state);
  2160. NormalizeSubtitleEmbed(state);
  2161. }
  2162. else
  2163. {
  2164. state.AudioStream = GetMediaStream(mediaStreams, null, MediaStreamType.Audio, true);
  2165. }
  2166. state.MediaSource = mediaSource;
  2167. var request = state.BaseRequest;
  2168. if (!string.IsNullOrWhiteSpace(request.AudioCodec))
  2169. {
  2170. var supportedAudioCodecsList = request.AudioCodec.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList();
  2171. ShiftAudioCodecsIfNeeded(supportedAudioCodecsList, state.AudioStream);
  2172. state.SupportedAudioCodecs = supportedAudioCodecsList.ToArray();
  2173. request.AudioCodec = state.SupportedAudioCodecs.FirstOrDefault(i => _mediaEncoder.CanEncodeToAudioCodec(i))
  2174. ?? state.SupportedAudioCodecs.FirstOrDefault();
  2175. }
  2176. }
  2177. private void ShiftAudioCodecsIfNeeded(List<string> audioCodecs, MediaStream audioStream)
  2178. {
  2179. // Nothing to do here
  2180. if (audioCodecs.Count < 2)
  2181. {
  2182. return;
  2183. }
  2184. var inputChannels = audioStream == null ? 6 : audioStream.Channels ?? 6;
  2185. if (inputChannels >= 6)
  2186. {
  2187. return;
  2188. }
  2189. // Transcoding to 2ch ac3 almost always causes a playback failure
  2190. // Keep it in the supported codecs list, but shift it to the end of the list so that if transcoding happens, another codec is used
  2191. var shiftAudioCodecs = new[] { "ac3", "eac3" };
  2192. if (audioCodecs.All(i => shiftAudioCodecs.Contains(i, StringComparer.OrdinalIgnoreCase)))
  2193. {
  2194. return;
  2195. }
  2196. while (shiftAudioCodecs.Contains(audioCodecs[0], StringComparer.OrdinalIgnoreCase))
  2197. {
  2198. var removed = shiftAudioCodecs[0];
  2199. audioCodecs.RemoveAt(0);
  2200. audioCodecs.Add(removed);
  2201. }
  2202. }
  2203. private void NormalizeSubtitleEmbed(EncodingJobInfo state)
  2204. {
  2205. if (state.SubtitleStream == null || state.SubtitleDeliveryMethod != SubtitleDeliveryMethod.Embed)
  2206. {
  2207. return;
  2208. }
  2209. // This is tricky to remux in, after converting to dvdsub it's not positioned correctly
  2210. // Therefore, let's just burn it in
  2211. if (string.Equals(state.SubtitleStream.Codec, "DVBSUB", StringComparison.OrdinalIgnoreCase))
  2212. {
  2213. state.SubtitleDeliveryMethod = SubtitleDeliveryMethod.Encode;
  2214. }
  2215. }
  2216. /// <summary>
  2217. /// Gets the ffmpeg option string for the hardware accelerated video decoder.
  2218. /// </summary>
  2219. /// <param name="state">The encoding job info.</param>
  2220. /// <param name="encodingOptions">The encoding options.</param>
  2221. /// <returns>The option string or null if none available.</returns>
  2222. protected string GetHardwareAcceleratedVideoDecoder(EncodingJobInfo state, EncodingOptions encodingOptions)
  2223. {
  2224. var videoStream = state.VideoStream;
  2225. if (videoStream == null)
  2226. {
  2227. return null;
  2228. }
  2229. var videoType = state.MediaSource.VideoType ?? VideoType.VideoFile;
  2230. // Only use alternative encoders for video files.
  2231. // When using concat with folder rips, if the mfx session fails to initialize, ffmpeg will be stuck retrying and will not exit gracefully
  2232. // Since transcoding of folder rips is expiremental anyway, it's not worth adding additional variables such as this.
  2233. if (videoType != VideoType.VideoFile)
  2234. {
  2235. return null;
  2236. }
  2237. if (IsCopyCodec(state.OutputVideoCodec))
  2238. {
  2239. return null;
  2240. }
  2241. if (!string.IsNullOrEmpty(videoStream.Codec) && !string.IsNullOrEmpty(encodingOptions.HardwareAccelerationType))
  2242. {
  2243. var isColorDepth10 = IsColorDepth10(state);
  2244. // Only hevc and vp9 formats have 10-bit hardware decoder support now.
  2245. if (isColorDepth10 && !(string.Equals(videoStream.Codec, "hevc", StringComparison.OrdinalIgnoreCase)
  2246. || string.Equals(videoStream.Codec, "h265", StringComparison.OrdinalIgnoreCase)
  2247. || string.Equals(videoStream.Codec, "vp9", StringComparison.OrdinalIgnoreCase)))
  2248. {
  2249. return null;
  2250. }
  2251. if (string.Equals(encodingOptions.HardwareAccelerationType, "qsv", StringComparison.OrdinalIgnoreCase))
  2252. {
  2253. switch (videoStream.Codec.ToLowerInvariant())
  2254. {
  2255. case "avc":
  2256. case "h264":
  2257. if (_mediaEncoder.SupportsDecoder("h264_qsv") && encodingOptions.HardwareDecodingCodecs.Contains("h264", StringComparer.OrdinalIgnoreCase))
  2258. {
  2259. // qsv decoder does not support 10-bit input
  2260. if ((videoStream.BitDepth ?? 8) > 8)
  2261. {
  2262. encodingOptions.HardwareDecodingCodecs = Array.Empty<string>();
  2263. return null;
  2264. }
  2265. return "-c:v h264_qsv";
  2266. }
  2267. break;
  2268. case "hevc":
  2269. case "h265":
  2270. if (_mediaEncoder.SupportsDecoder("hevc_qsv") && encodingOptions.HardwareDecodingCodecs.Contains("hevc", StringComparer.OrdinalIgnoreCase))
  2271. {
  2272. return (isColorDepth10 &&
  2273. !encodingOptions.EnableDecodingColorDepth10Hevc) ? null : "-c:v hevc_qsv";
  2274. }
  2275. break;
  2276. case "mpeg2video":
  2277. if (_mediaEncoder.SupportsDecoder("mpeg2_qsv") && encodingOptions.HardwareDecodingCodecs.Contains("mpeg2video", StringComparer.OrdinalIgnoreCase))
  2278. {
  2279. return "-c:v mpeg2_qsv";
  2280. }
  2281. break;
  2282. case "vc1":
  2283. if (_mediaEncoder.SupportsDecoder("vc1_qsv") && encodingOptions.HardwareDecodingCodecs.Contains("vc1", StringComparer.OrdinalIgnoreCase))
  2284. {
  2285. return "-c:v vc1_qsv";
  2286. }
  2287. break;
  2288. case "vp8":
  2289. if (_mediaEncoder.SupportsDecoder("vp8_qsv") && encodingOptions.HardwareDecodingCodecs.Contains("vp8", StringComparer.OrdinalIgnoreCase))
  2290. {
  2291. return "-c:v vp8_qsv";
  2292. }
  2293. break;
  2294. case "vp9":
  2295. if (_mediaEncoder.SupportsDecoder("vp9_qsv") && encodingOptions.HardwareDecodingCodecs.Contains("vp9", StringComparer.OrdinalIgnoreCase))
  2296. {
  2297. return (isColorDepth10 &&
  2298. !encodingOptions.EnableDecodingColorDepth10Vp9) ? null : "-c:v vp9_qsv";
  2299. }
  2300. break;
  2301. }
  2302. }
  2303. else if (string.Equals(encodingOptions.HardwareAccelerationType, "nvenc", StringComparison.OrdinalIgnoreCase))
  2304. {
  2305. switch (videoStream.Codec.ToLowerInvariant())
  2306. {
  2307. case "avc":
  2308. case "h264":
  2309. if (_mediaEncoder.SupportsDecoder("h264_cuvid") && encodingOptions.HardwareDecodingCodecs.Contains("h264", StringComparer.OrdinalIgnoreCase))
  2310. {
  2311. return "-c:v h264_cuvid";
  2312. }
  2313. break;
  2314. case "hevc":
  2315. case "h265":
  2316. if (_mediaEncoder.SupportsDecoder("hevc_cuvid") && encodingOptions.HardwareDecodingCodecs.Contains("hevc", StringComparer.OrdinalIgnoreCase))
  2317. {
  2318. return (isColorDepth10 &&
  2319. !encodingOptions.EnableDecodingColorDepth10Hevc) ? null : "-c:v hevc_cuvid";
  2320. }
  2321. break;
  2322. case "mpeg2video":
  2323. if (_mediaEncoder.SupportsDecoder("mpeg2_cuvid") && encodingOptions.HardwareDecodingCodecs.Contains("mpeg2video", StringComparer.OrdinalIgnoreCase))
  2324. {
  2325. return "-c:v mpeg2_cuvid";
  2326. }
  2327. break;
  2328. case "vc1":
  2329. if (_mediaEncoder.SupportsDecoder("vc1_cuvid") && encodingOptions.HardwareDecodingCodecs.Contains("vc1", StringComparer.OrdinalIgnoreCase))
  2330. {
  2331. return "-c:v vc1_cuvid";
  2332. }
  2333. break;
  2334. case "mpeg4":
  2335. if (_mediaEncoder.SupportsDecoder("mpeg4_cuvid") && encodingOptions.HardwareDecodingCodecs.Contains("mpeg4", StringComparer.OrdinalIgnoreCase))
  2336. {
  2337. return "-c:v mpeg4_cuvid";
  2338. }
  2339. break;
  2340. case "vp8":
  2341. if (_mediaEncoder.SupportsDecoder("vp8_cuvid") && encodingOptions.HardwareDecodingCodecs.Contains("vp8", StringComparer.OrdinalIgnoreCase))
  2342. {
  2343. return "-c:v vp8_cuvid";
  2344. }
  2345. break;
  2346. case "vp9":
  2347. if (_mediaEncoder.SupportsDecoder("vp9_cuvid") && encodingOptions.HardwareDecodingCodecs.Contains("vp9", StringComparer.OrdinalIgnoreCase))
  2348. {
  2349. return (isColorDepth10 &&
  2350. !encodingOptions.EnableDecodingColorDepth10Vp9) ? null : "-c:v vp9_cuvid";
  2351. }
  2352. break;
  2353. }
  2354. }
  2355. else if (string.Equals(encodingOptions.HardwareAccelerationType, "mediacodec", StringComparison.OrdinalIgnoreCase))
  2356. {
  2357. switch (videoStream.Codec.ToLowerInvariant())
  2358. {
  2359. case "avc":
  2360. case "h264":
  2361. if (_mediaEncoder.SupportsDecoder("h264_mediacodec") && encodingOptions.HardwareDecodingCodecs.Contains("h264", StringComparer.OrdinalIgnoreCase))
  2362. {
  2363. return "-c:v h264_mediacodec";
  2364. }
  2365. break;
  2366. case "hevc":
  2367. case "h265":
  2368. if (_mediaEncoder.SupportsDecoder("hevc_mediacodec") && encodingOptions.HardwareDecodingCodecs.Contains("hevc", StringComparer.OrdinalIgnoreCase))
  2369. {
  2370. return (isColorDepth10 &&
  2371. !encodingOptions.EnableDecodingColorDepth10Hevc) ? null : "-c:v hevc_mediacodec";
  2372. }
  2373. break;
  2374. case "mpeg2video":
  2375. if (_mediaEncoder.SupportsDecoder("mpeg2_mediacodec") && encodingOptions.HardwareDecodingCodecs.Contains("mpeg2video", StringComparer.OrdinalIgnoreCase))
  2376. {
  2377. return "-c:v mpeg2_mediacodec";
  2378. }
  2379. break;
  2380. case "mpeg4":
  2381. if (_mediaEncoder.SupportsDecoder("mpeg4_mediacodec") && encodingOptions.HardwareDecodingCodecs.Contains("mpeg4", StringComparer.OrdinalIgnoreCase))
  2382. {
  2383. return "-c:v mpeg4_mediacodec";
  2384. }
  2385. break;
  2386. case "vp8":
  2387. if (_mediaEncoder.SupportsDecoder("vp8_mediacodec") && encodingOptions.HardwareDecodingCodecs.Contains("vp8", StringComparer.OrdinalIgnoreCase))
  2388. {
  2389. return "-c:v vp8_mediacodec";
  2390. }
  2391. break;
  2392. case "vp9":
  2393. if (_mediaEncoder.SupportsDecoder("vp9_mediacodec") && encodingOptions.HardwareDecodingCodecs.Contains("vp9", StringComparer.OrdinalIgnoreCase))
  2394. {
  2395. return (isColorDepth10 &&
  2396. !encodingOptions.EnableDecodingColorDepth10Vp9) ? null : "-c:v vp9_mediacodec";
  2397. }
  2398. break;
  2399. }
  2400. }
  2401. else if (string.Equals(encodingOptions.HardwareAccelerationType, "omx", StringComparison.OrdinalIgnoreCase))
  2402. {
  2403. switch (videoStream.Codec.ToLowerInvariant())
  2404. {
  2405. case "avc":
  2406. case "h264":
  2407. if (_mediaEncoder.SupportsDecoder("h264_mmal") && encodingOptions.HardwareDecodingCodecs.Contains("h264", StringComparer.OrdinalIgnoreCase))
  2408. {
  2409. return "-c:v h264_mmal";
  2410. }
  2411. break;
  2412. case "mpeg2video":
  2413. if (_mediaEncoder.SupportsDecoder("mpeg2_mmal") && encodingOptions.HardwareDecodingCodecs.Contains("mpeg2video", StringComparer.OrdinalIgnoreCase))
  2414. {
  2415. return "-c:v mpeg2_mmal";
  2416. }
  2417. break;
  2418. case "mpeg4":
  2419. if (_mediaEncoder.SupportsDecoder("mpeg4_mmal") && encodingOptions.HardwareDecodingCodecs.Contains("mpeg4", StringComparer.OrdinalIgnoreCase))
  2420. {
  2421. return "-c:v mpeg4_mmal";
  2422. }
  2423. break;
  2424. case "vc1":
  2425. if (_mediaEncoder.SupportsDecoder("vc1_mmal") && encodingOptions.HardwareDecodingCodecs.Contains("vc1", StringComparer.OrdinalIgnoreCase))
  2426. {
  2427. return "-c:v vc1_mmal";
  2428. }
  2429. break;
  2430. }
  2431. }
  2432. else if (string.Equals(encodingOptions.HardwareAccelerationType, "amf", StringComparison.OrdinalIgnoreCase))
  2433. {
  2434. switch (videoStream.Codec.ToLowerInvariant())
  2435. {
  2436. case "avc":
  2437. case "h264":
  2438. return GetHwaccelType(state, encodingOptions, "h264");
  2439. case "hevc":
  2440. case "h265":
  2441. return (isColorDepth10 &&
  2442. !encodingOptions.EnableDecodingColorDepth10Hevc) ? null : GetHwaccelType(state, encodingOptions, "hevc");
  2443. case "mpeg2video":
  2444. return GetHwaccelType(state, encodingOptions, "mpeg2video");
  2445. case "vc1":
  2446. return GetHwaccelType(state, encodingOptions, "vc1");
  2447. case "mpeg4":
  2448. return GetHwaccelType(state, encodingOptions, "mpeg4");
  2449. case "vp9":
  2450. return (isColorDepth10 &&
  2451. !encodingOptions.EnableDecodingColorDepth10Vp9) ? null : GetHwaccelType(state, encodingOptions, "vp9");
  2452. }
  2453. }
  2454. else if (string.Equals(encodingOptions.HardwareAccelerationType, "vaapi", StringComparison.OrdinalIgnoreCase))
  2455. {
  2456. switch (videoStream.Codec.ToLowerInvariant())
  2457. {
  2458. case "avc":
  2459. case "h264":
  2460. return GetHwaccelType(state, encodingOptions, "h264");
  2461. case "hevc":
  2462. case "h265":
  2463. return (isColorDepth10 &&
  2464. !encodingOptions.EnableDecodingColorDepth10Hevc) ? null : GetHwaccelType(state, encodingOptions, "hevc");
  2465. case "mpeg2video":
  2466. return GetHwaccelType(state, encodingOptions, "mpeg2video");
  2467. case "vc1":
  2468. return GetHwaccelType(state, encodingOptions, "vc1");
  2469. case "vp8":
  2470. return GetHwaccelType(state, encodingOptions, "vp8");
  2471. case "vp9":
  2472. return (isColorDepth10 &&
  2473. !encodingOptions.EnableDecodingColorDepth10Vp9) ? null : GetHwaccelType(state, encodingOptions, "vp9");
  2474. }
  2475. }
  2476. else if (string.Equals(encodingOptions.HardwareAccelerationType, "videotoolbox", StringComparison.OrdinalIgnoreCase))
  2477. {
  2478. switch (videoStream.Codec.ToLowerInvariant())
  2479. {
  2480. case "avc":
  2481. case "h264":
  2482. if (_mediaEncoder.SupportsDecoder("h264_opencl") && encodingOptions.HardwareDecodingCodecs.Contains("h264", StringComparer.OrdinalIgnoreCase))
  2483. {
  2484. return "-c:v h264_opencl";
  2485. }
  2486. break;
  2487. case "hevc":
  2488. case "h265":
  2489. if (_mediaEncoder.SupportsDecoder("hevc_opencl") && encodingOptions.HardwareDecodingCodecs.Contains("h264", StringComparer.OrdinalIgnoreCase))
  2490. {
  2491. return (isColorDepth10 &&
  2492. !encodingOptions.EnableDecodingColorDepth10Hevc) ? null : "-c:v hevc_opencl";
  2493. }
  2494. break;
  2495. case "mpeg2video":
  2496. if (_mediaEncoder.SupportsDecoder("mpeg2_opencl") && encodingOptions.HardwareDecodingCodecs.Contains("mpeg2video", StringComparer.OrdinalIgnoreCase))
  2497. {
  2498. return "-c:v mpeg2_opencl";
  2499. }
  2500. break;
  2501. case "mpeg4":
  2502. if (_mediaEncoder.SupportsDecoder("mpeg4_opencl") && encodingOptions.HardwareDecodingCodecs.Contains("mpeg4", StringComparer.OrdinalIgnoreCase))
  2503. {
  2504. return "-c:v mpeg4_opencl";
  2505. }
  2506. break;
  2507. case "vc1":
  2508. if (_mediaEncoder.SupportsDecoder("vc1_opencl") && encodingOptions.HardwareDecodingCodecs.Contains("vc1", StringComparer.OrdinalIgnoreCase))
  2509. {
  2510. return "-c:v vc1_opencl";
  2511. }
  2512. break;
  2513. case "vp8":
  2514. if (_mediaEncoder.SupportsDecoder("vp8_opencl") && encodingOptions.HardwareDecodingCodecs.Contains("vc1", StringComparer.OrdinalIgnoreCase))
  2515. {
  2516. return "-c:v vp8_opencl";
  2517. }
  2518. break;
  2519. case "vp9":
  2520. if (_mediaEncoder.SupportsDecoder("vp9_opencl") && encodingOptions.HardwareDecodingCodecs.Contains("vc1", StringComparer.OrdinalIgnoreCase))
  2521. {
  2522. return (isColorDepth10 &&
  2523. !encodingOptions.EnableDecodingColorDepth10Vp9) ? null : "-c:v vp9_opencl";
  2524. }
  2525. break;
  2526. }
  2527. }
  2528. }
  2529. var whichCodec = videoStream.Codec.ToLowerInvariant();
  2530. switch (whichCodec)
  2531. {
  2532. case "avc":
  2533. whichCodec = "h264";
  2534. break;
  2535. case "h265":
  2536. whichCodec = "hevc";
  2537. break;
  2538. }
  2539. // Avoid a second attempt if no hardware acceleration is being used
  2540. encodingOptions.HardwareDecodingCodecs = encodingOptions.HardwareDecodingCodecs.Where(val => val != whichCodec).ToArray();
  2541. // leave blank so ffmpeg will decide
  2542. return null;
  2543. }
  2544. /// <summary>
  2545. /// Gets a hwaccel type to use as a hardware decoder(dxva/vaapi) depending on the system
  2546. /// </summary>
  2547. public string GetHwaccelType(EncodingJobInfo state, EncodingOptions options, string videoCodec)
  2548. {
  2549. var isWindows = RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
  2550. var isLinux = RuntimeInformation.IsOSPlatform(OSPlatform.Linux);
  2551. var isWindows8orLater = Environment.OSVersion.Version.Major > 6 || (Environment.OSVersion.Version.Major == 6 && Environment.OSVersion.Version.Minor > 1);
  2552. var isDxvaSupported = _mediaEncoder.SupportsHwaccel("dxva2") || _mediaEncoder.SupportsHwaccel("d3d11va");
  2553. if ((isDxvaSupported || IsVaapiSupported(state)) && options.HardwareDecodingCodecs.Contains(videoCodec, StringComparer.OrdinalIgnoreCase))
  2554. {
  2555. if (isLinux)
  2556. {
  2557. return "-hwaccel vaapi";
  2558. }
  2559. if (isWindows && isWindows8orLater)
  2560. {
  2561. return "-hwaccel d3d11va";
  2562. }
  2563. if (isWindows && !isWindows8orLater)
  2564. {
  2565. return "-hwaccel dxva2";
  2566. }
  2567. }
  2568. return null;
  2569. }
  2570. public string GetSubtitleEmbedArguments(EncodingJobInfo state)
  2571. {
  2572. if (state.SubtitleStream == null || state.SubtitleDeliveryMethod != SubtitleDeliveryMethod.Embed)
  2573. {
  2574. return string.Empty;
  2575. }
  2576. var format = state.SupportedSubtitleCodecs.FirstOrDefault();
  2577. string codec;
  2578. if (string.IsNullOrEmpty(format) || string.Equals(format, state.SubtitleStream.Codec, StringComparison.OrdinalIgnoreCase))
  2579. {
  2580. codec = "copy";
  2581. }
  2582. else
  2583. {
  2584. codec = format;
  2585. }
  2586. return " -codec:s:0 " + codec + " -disposition:s:0 default";
  2587. }
  2588. public string GetProgressiveVideoFullCommandLine(EncodingJobInfo state, EncodingOptions encodingOptions, string outputPath, string defaultPreset)
  2589. {
  2590. // Get the output codec name
  2591. var videoCodec = GetVideoEncoder(state, encodingOptions);
  2592. var format = string.Empty;
  2593. var keyFrame = string.Empty;
  2594. if (string.Equals(Path.GetExtension(outputPath), ".mp4", StringComparison.OrdinalIgnoreCase)
  2595. && state.BaseRequest.Context == EncodingContext.Streaming)
  2596. {
  2597. // Comparison: https://github.com/jansmolders86/mediacenterjs/blob/master/lib/transcoding/desktop.js
  2598. format = " -f mp4 -movflags frag_keyframe+empty_moov";
  2599. }
  2600. var threads = GetNumberOfThreads(state, encodingOptions, videoCodec);
  2601. var inputModifier = GetInputModifier(state, encodingOptions);
  2602. return string.Format(
  2603. CultureInfo.InvariantCulture,
  2604. "{0} {1}{2} {3} {4} -map_metadata -1 -map_chapters -1 -threads {5} {6}{7}{8} -y \"{9}\"",
  2605. inputModifier,
  2606. GetInputArgument(state, encodingOptions),
  2607. keyFrame,
  2608. GetMapArgs(state),
  2609. GetProgressiveVideoArguments(state, encodingOptions, videoCodec, defaultPreset),
  2610. threads,
  2611. GetProgressiveVideoAudioArguments(state, encodingOptions),
  2612. GetSubtitleEmbedArguments(state),
  2613. format,
  2614. outputPath).Trim();
  2615. }
  2616. public string GetOutputFFlags(EncodingJobInfo state)
  2617. {
  2618. var flags = new List<string>();
  2619. if (state.GenPtsOutput)
  2620. {
  2621. flags.Add("+genpts");
  2622. }
  2623. if (flags.Count > 0)
  2624. {
  2625. return " -fflags " + string.Join("", flags);
  2626. }
  2627. return string.Empty;
  2628. }
  2629. public string GetProgressiveVideoArguments(EncodingJobInfo state, EncodingOptions encodingOptions, string videoCodec, string defaultPreset)
  2630. {
  2631. var args = "-codec:v:0 " + videoCodec;
  2632. if (state.BaseRequest.EnableMpegtsM2TsMode)
  2633. {
  2634. args += " -mpegts_m2ts_mode 1";
  2635. }
  2636. if (IsCopyCodec(videoCodec))
  2637. {
  2638. if (state.VideoStream != null
  2639. && string.Equals(state.OutputContainer, "ts", StringComparison.OrdinalIgnoreCase)
  2640. && !string.Equals(state.VideoStream.NalLengthSize, "0", StringComparison.OrdinalIgnoreCase))
  2641. {
  2642. string bitStreamArgs = GetBitStreamArgs(state.VideoStream);
  2643. if (!string.IsNullOrEmpty(bitStreamArgs))
  2644. {
  2645. args += " " + bitStreamArgs;
  2646. }
  2647. }
  2648. if (state.RunTimeTicks.HasValue && state.BaseRequest.CopyTimestamps)
  2649. {
  2650. args += " -copyts -avoid_negative_ts disabled -start_at_zero";
  2651. }
  2652. if (!state.RunTimeTicks.HasValue)
  2653. {
  2654. args += " -fflags +genpts";
  2655. }
  2656. }
  2657. else
  2658. {
  2659. var keyFrameArg = string.Format(
  2660. CultureInfo.InvariantCulture,
  2661. " -force_key_frames \"expr:gte(t,n_forced*{0})\"",
  2662. 5);
  2663. args += keyFrameArg;
  2664. var hasGraphicalSubs = state.SubtitleStream != null && !state.SubtitleStream.IsTextSubtitleStream && state.SubtitleDeliveryMethod == SubtitleDeliveryMethod.Encode;
  2665. var hasCopyTs = false;
  2666. // Add resolution params, if specified
  2667. if (!hasGraphicalSubs)
  2668. {
  2669. var outputSizeParam = GetOutputSizeParam(state, encodingOptions, videoCodec);
  2670. args += outputSizeParam;
  2671. hasCopyTs = outputSizeParam.IndexOf("copyts", StringComparison.OrdinalIgnoreCase) != -1;
  2672. }
  2673. // This is for graphical subs
  2674. if (hasGraphicalSubs)
  2675. {
  2676. var graphicalSubtitleParam = GetGraphicalSubtitleParam(state, encodingOptions, videoCodec);
  2677. args += graphicalSubtitleParam;
  2678. hasCopyTs = graphicalSubtitleParam.IndexOf("copyts", StringComparison.OrdinalIgnoreCase) != -1;
  2679. }
  2680. if (state.RunTimeTicks.HasValue && state.BaseRequest.CopyTimestamps)
  2681. {
  2682. if (!hasCopyTs)
  2683. {
  2684. args += " -copyts";
  2685. }
  2686. args += " -avoid_negative_ts disabled";
  2687. if (!(state.SubtitleStream != null && state.SubtitleStream.IsExternal && !state.SubtitleStream.IsTextSubtitleStream))
  2688. {
  2689. args += " -start_at_zero";
  2690. }
  2691. }
  2692. var qualityParam = GetVideoQualityParam(state, videoCodec, encodingOptions, defaultPreset);
  2693. if (!string.IsNullOrEmpty(qualityParam))
  2694. {
  2695. args += " " + qualityParam.Trim();
  2696. }
  2697. }
  2698. if (!string.IsNullOrEmpty(state.OutputVideoSync))
  2699. {
  2700. args += " -vsync " + state.OutputVideoSync;
  2701. }
  2702. args += GetOutputFFlags(state);
  2703. return args;
  2704. }
  2705. public string GetProgressiveVideoAudioArguments(EncodingJobInfo state, EncodingOptions encodingOptions)
  2706. {
  2707. // If the video doesn't have an audio stream, return a default.
  2708. if (state.AudioStream == null && state.VideoStream != null)
  2709. {
  2710. return string.Empty;
  2711. }
  2712. // Get the output codec name
  2713. var codec = GetAudioEncoder(state);
  2714. var args = "-codec:a:0 " + codec;
  2715. if (IsCopyCodec(codec))
  2716. {
  2717. return args;
  2718. }
  2719. // Add the number of audio channels
  2720. var channels = state.OutputAudioChannels;
  2721. if (channels.HasValue)
  2722. {
  2723. args += " -ac " + channels.Value;
  2724. }
  2725. var bitrate = state.OutputAudioBitrate;
  2726. if (bitrate.HasValue)
  2727. {
  2728. args += " -ab " + bitrate.Value.ToString(_usCulture);
  2729. }
  2730. if (state.OutputAudioSampleRate.HasValue)
  2731. {
  2732. args += " -ar " + state.OutputAudioSampleRate.Value.ToString(_usCulture);
  2733. }
  2734. args += " " + GetAudioFilterParam(state, encodingOptions, false);
  2735. return args;
  2736. }
  2737. public string GetProgressiveAudioFullCommandLine(EncodingJobInfo state, EncodingOptions encodingOptions, string outputPath)
  2738. {
  2739. var audioTranscodeParams = new List<string>();
  2740. var bitrate = state.OutputAudioBitrate;
  2741. if (bitrate.HasValue)
  2742. {
  2743. audioTranscodeParams.Add("-ab " + bitrate.Value.ToString(_usCulture));
  2744. }
  2745. if (state.OutputAudioChannels.HasValue)
  2746. {
  2747. audioTranscodeParams.Add("-ac " + state.OutputAudioChannels.Value.ToString(_usCulture));
  2748. }
  2749. // opus will fail on 44100
  2750. if (!string.Equals(state.OutputAudioCodec, "opus", StringComparison.OrdinalIgnoreCase))
  2751. {
  2752. if (state.OutputAudioSampleRate.HasValue)
  2753. {
  2754. audioTranscodeParams.Add("-ar " + state.OutputAudioSampleRate.Value.ToString(_usCulture));
  2755. }
  2756. }
  2757. var threads = GetNumberOfThreads(state, encodingOptions, null);
  2758. var inputModifier = GetInputModifier(state, encodingOptions);
  2759. return string.Format(
  2760. CultureInfo.InvariantCulture,
  2761. "{0} {1}{7}{8} -threads {2}{3} {4} -id3v2_version 3 -write_id3v1 1{6} -y \"{5}\"",
  2762. inputModifier,
  2763. GetInputArgument(state, encodingOptions),
  2764. threads,
  2765. " -vn",
  2766. string.Join(" ", audioTranscodeParams),
  2767. outputPath,
  2768. string.Empty,
  2769. string.Empty,
  2770. string.Empty).Trim();
  2771. }
  2772. public static bool IsCopyCodec(string codec)
  2773. {
  2774. return string.Equals(codec, "copy", StringComparison.OrdinalIgnoreCase);
  2775. }
  2776. public static bool IsColorDepth10(EncodingJobInfo state)
  2777. {
  2778. var result = false;
  2779. var videoStream = state.VideoStream;
  2780. if (videoStream != null)
  2781. {
  2782. if (!string.IsNullOrEmpty(videoStream.PixelFormat))
  2783. {
  2784. result = videoStream.PixelFormat.Contains("p10", StringComparison.OrdinalIgnoreCase);
  2785. if (result)
  2786. {
  2787. return true;
  2788. }
  2789. }
  2790. if (!string.IsNullOrEmpty(videoStream.Profile))
  2791. {
  2792. result = videoStream.Profile.Contains("Main 10", StringComparison.OrdinalIgnoreCase)
  2793. || videoStream.Profile.Contains("High 10", StringComparison.OrdinalIgnoreCase)
  2794. || videoStream.Profile.Contains("Profile 2", StringComparison.OrdinalIgnoreCase);
  2795. if (result)
  2796. {
  2797. return true;
  2798. }
  2799. }
  2800. result = (videoStream.BitDepth ?? 8) == 10;
  2801. if (result)
  2802. {
  2803. return true;
  2804. }
  2805. }
  2806. return result;
  2807. }
  2808. }
  2809. }