EncodingHelper.cs 217 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341
  1. #nullable disable
  2. #pragma warning disable CS1591
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Globalization;
  6. using System.IO;
  7. using System.Linq;
  8. using System.Text;
  9. using System.Text.RegularExpressions;
  10. using System.Threading;
  11. using Jellyfin.Data.Enums;
  12. using MediaBrowser.Model.Configuration;
  13. using MediaBrowser.Model.Dlna;
  14. using MediaBrowser.Model.Dto;
  15. using MediaBrowser.Model.Entities;
  16. using MediaBrowser.Model.MediaInfo;
  17. namespace MediaBrowser.Controller.MediaEncoding
  18. {
  19. public class EncodingHelper
  20. {
  21. private readonly IMediaEncoder _mediaEncoder;
  22. private readonly ISubtitleEncoder _subtitleEncoder;
  23. private static readonly string[] _videoProfilesH264 = new[]
  24. {
  25. "ConstrainedBaseline",
  26. "Baseline",
  27. "Extended",
  28. "Main",
  29. "High",
  30. "ProgressiveHigh",
  31. "ConstrainedHigh",
  32. "High10"
  33. };
  34. private static readonly string[] _videoProfilesH265 = new[]
  35. {
  36. "Main",
  37. "Main10"
  38. };
  39. private static readonly string _qsvAlias = "qs";
  40. private static readonly string _vaapiAlias = "va";
  41. private static readonly string _d3d11vaAlias = "dx11";
  42. private static readonly string _videotoolboxAlias = "vt";
  43. private static readonly string _openclAlias = "ocl";
  44. private static readonly string _cudaAlias = "cu";
  45. public EncodingHelper(
  46. IMediaEncoder mediaEncoder,
  47. ISubtitleEncoder subtitleEncoder)
  48. {
  49. _mediaEncoder = mediaEncoder;
  50. _subtitleEncoder = subtitleEncoder;
  51. }
  52. public string GetH264Encoder(EncodingJobInfo state, EncodingOptions encodingOptions)
  53. => GetH264OrH265Encoder("libx264", "h264", state, encodingOptions);
  54. public string GetH265Encoder(EncodingJobInfo state, EncodingOptions encodingOptions)
  55. => GetH264OrH265Encoder("libx265", "hevc", state, encodingOptions);
  56. private string GetH264OrH265Encoder(string defaultEncoder, string hwEncoder, EncodingJobInfo state, EncodingOptions encodingOptions)
  57. {
  58. // Only use alternative encoders for video files.
  59. // When using concat with folder rips, if the mfx session fails to initialize, ffmpeg will be stuck retrying and will not exit gracefully
  60. // Since transcoding of folder rips is experimental anyway, it's not worth adding additional variables such as this.
  61. if (state.VideoType == VideoType.VideoFile)
  62. {
  63. var hwType = encodingOptions.HardwareAccelerationType;
  64. var codecMap = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
  65. {
  66. { "amf", hwEncoder + "_amf" },
  67. { "nvenc", hwEncoder + "_nvenc" },
  68. { "qsv", hwEncoder + "_qsv" },
  69. { "vaapi", hwEncoder + "_vaapi" },
  70. { "videotoolbox", hwEncoder + "_videotoolbox" },
  71. { "v4l2m2m", hwEncoder + "_v4l2m2m" },
  72. { "omx", hwEncoder + "_omx" },
  73. };
  74. if (!string.IsNullOrEmpty(hwType)
  75. && encodingOptions.EnableHardwareEncoding
  76. && codecMap.ContainsKey(hwType))
  77. {
  78. var preferredEncoder = codecMap[hwType];
  79. if (_mediaEncoder.SupportsEncoder(preferredEncoder))
  80. {
  81. return preferredEncoder;
  82. }
  83. }
  84. }
  85. return defaultEncoder;
  86. }
  87. private bool IsVaapiSupported(EncodingJobInfo state)
  88. {
  89. // vaapi will throw an error with this input
  90. // [vaapi @ 0x7faed8000960] No VAAPI support for codec mpeg4 profile -99.
  91. if (string.Equals(state.VideoStream?.Codec, "mpeg4", StringComparison.OrdinalIgnoreCase))
  92. {
  93. return false;
  94. }
  95. return _mediaEncoder.SupportsHwaccel("vaapi");
  96. }
  97. private bool IsVaapiFullSupported()
  98. {
  99. return _mediaEncoder.SupportsHwaccel("vaapi")
  100. && _mediaEncoder.SupportsFilter("scale_vaapi")
  101. && _mediaEncoder.SupportsFilter("deinterlace_vaapi")
  102. && _mediaEncoder.SupportsFilter("tonemap_vaapi")
  103. && _mediaEncoder.SupportsFilterWithOption(FilterOptionType.OverlayVaapiFrameSync)
  104. && _mediaEncoder.SupportsFilter("hwupload_vaapi");
  105. }
  106. private bool IsOpenclFullSupported()
  107. {
  108. return _mediaEncoder.SupportsHwaccel("opencl")
  109. && _mediaEncoder.SupportsFilter("scale_opencl")
  110. && _mediaEncoder.SupportsFilterWithOption(FilterOptionType.TonemapOpenclBt2390)
  111. && _mediaEncoder.SupportsFilterWithOption(FilterOptionType.OverlayOpenclFrameSync);
  112. }
  113. private bool IsCudaFullSupported()
  114. {
  115. return _mediaEncoder.SupportsHwaccel("cuda")
  116. && _mediaEncoder.SupportsFilterWithOption(FilterOptionType.ScaleCudaFormat)
  117. && _mediaEncoder.SupportsFilter("yadif_cuda")
  118. && _mediaEncoder.SupportsFilterWithOption(FilterOptionType.TonemapCudaName)
  119. && _mediaEncoder.SupportsFilter("overlay_cuda")
  120. && _mediaEncoder.SupportsFilter("hwupload_cuda");
  121. }
  122. private bool IsHwTonemapAvailable(EncodingJobInfo state, EncodingOptions options)
  123. {
  124. if (state.VideoStream == null)
  125. {
  126. return false;
  127. }
  128. return options.EnableTonemapping
  129. && (string.Equals(state.VideoStream.ColorTransfer, "smpte2084", StringComparison.OrdinalIgnoreCase)
  130. || string.Equals(state.VideoStream.ColorTransfer, "arib-std-b67", StringComparison.OrdinalIgnoreCase))
  131. && GetVideoColorBitDepth(state) == 10;
  132. }
  133. private bool IsVaapiVppTonemapAvailable(EncodingJobInfo state, EncodingOptions options)
  134. {
  135. if (state.VideoStream == null)
  136. {
  137. return false;
  138. }
  139. // Native VPP tonemapping may come to QSV in the future.
  140. return options.EnableVppTonemapping
  141. && string.Equals(state.VideoStream.ColorTransfer, "smpte2084", StringComparison.OrdinalIgnoreCase)
  142. && GetVideoColorBitDepth(state) == 10;
  143. }
  144. /// <summary>
  145. /// Gets the name of the output video codec.
  146. /// </summary>
  147. /// <param name="state">Encording state.</param>
  148. /// <param name="encodingOptions">Encoding options.</param>
  149. /// <returns>Encoder string.</returns>
  150. public string GetVideoEncoder(EncodingJobInfo state, EncodingOptions encodingOptions)
  151. {
  152. var codec = state.OutputVideoCodec;
  153. if (!string.IsNullOrEmpty(codec))
  154. {
  155. if (string.Equals(codec, "h265", StringComparison.OrdinalIgnoreCase)
  156. || string.Equals(codec, "hevc", StringComparison.OrdinalIgnoreCase))
  157. {
  158. return GetH265Encoder(state, encodingOptions);
  159. }
  160. if (string.Equals(codec, "h264", StringComparison.OrdinalIgnoreCase))
  161. {
  162. return GetH264Encoder(state, encodingOptions);
  163. }
  164. if (string.Equals(codec, "vp8", StringComparison.OrdinalIgnoreCase)
  165. || string.Equals(codec, "vpx", StringComparison.OrdinalIgnoreCase))
  166. {
  167. return "libvpx";
  168. }
  169. if (string.Equals(codec, "vp9", StringComparison.OrdinalIgnoreCase))
  170. {
  171. return "libvpx-vp9";
  172. }
  173. if (string.Equals(codec, "wmv", StringComparison.OrdinalIgnoreCase))
  174. {
  175. return "wmv2";
  176. }
  177. if (string.Equals(codec, "theora", StringComparison.OrdinalIgnoreCase))
  178. {
  179. return "libtheora";
  180. }
  181. return codec.ToLowerInvariant();
  182. }
  183. return "copy";
  184. }
  185. /// <summary>
  186. /// Gets the user agent param.
  187. /// </summary>
  188. /// <param name="state">The state.</param>
  189. /// <returns>System.String.</returns>
  190. public string GetUserAgentParam(EncodingJobInfo state)
  191. {
  192. if (state.RemoteHttpHeaders.TryGetValue("User-Agent", out string useragent))
  193. {
  194. return "-user_agent \"" + useragent + "\"";
  195. }
  196. return string.Empty;
  197. }
  198. public static string GetInputFormat(string container)
  199. {
  200. if (string.IsNullOrEmpty(container))
  201. {
  202. return null;
  203. }
  204. container = container.Replace("mkv", "matroska", StringComparison.OrdinalIgnoreCase);
  205. if (string.Equals(container, "ts", StringComparison.OrdinalIgnoreCase))
  206. {
  207. return "mpegts";
  208. }
  209. // For these need to find out the ffmpeg names
  210. if (string.Equals(container, "m2ts", StringComparison.OrdinalIgnoreCase))
  211. {
  212. return null;
  213. }
  214. if (string.Equals(container, "wmv", StringComparison.OrdinalIgnoreCase))
  215. {
  216. return null;
  217. }
  218. if (string.Equals(container, "mts", StringComparison.OrdinalIgnoreCase))
  219. {
  220. return null;
  221. }
  222. if (string.Equals(container, "vob", StringComparison.OrdinalIgnoreCase))
  223. {
  224. return null;
  225. }
  226. if (string.Equals(container, "mpg", StringComparison.OrdinalIgnoreCase))
  227. {
  228. return null;
  229. }
  230. if (string.Equals(container, "mpeg", StringComparison.OrdinalIgnoreCase))
  231. {
  232. return null;
  233. }
  234. if (string.Equals(container, "rec", StringComparison.OrdinalIgnoreCase))
  235. {
  236. return null;
  237. }
  238. if (string.Equals(container, "dvr-ms", StringComparison.OrdinalIgnoreCase))
  239. {
  240. return null;
  241. }
  242. if (string.Equals(container, "ogm", StringComparison.OrdinalIgnoreCase))
  243. {
  244. return null;
  245. }
  246. if (string.Equals(container, "divx", StringComparison.OrdinalIgnoreCase))
  247. {
  248. return null;
  249. }
  250. if (string.Equals(container, "tp", StringComparison.OrdinalIgnoreCase))
  251. {
  252. return null;
  253. }
  254. if (string.Equals(container, "rmvb", StringComparison.OrdinalIgnoreCase))
  255. {
  256. return null;
  257. }
  258. if (string.Equals(container, "rtp", StringComparison.OrdinalIgnoreCase))
  259. {
  260. return null;
  261. }
  262. // Seeing reported failures here, not sure yet if this is related to specifying input format
  263. if (string.Equals(container, "m4v", StringComparison.OrdinalIgnoreCase))
  264. {
  265. return null;
  266. }
  267. // obviously don't do this for strm files
  268. if (string.Equals(container, "strm", StringComparison.OrdinalIgnoreCase))
  269. {
  270. return null;
  271. }
  272. // ISO files don't have an ffmpeg format
  273. if (string.Equals(container, "iso", StringComparison.OrdinalIgnoreCase))
  274. {
  275. return null;
  276. }
  277. return container;
  278. }
  279. /// <summary>
  280. /// Gets decoder from a codec.
  281. /// </summary>
  282. /// <param name="codec">Codec to use.</param>
  283. /// <returns>Decoder string.</returns>
  284. public string GetDecoderFromCodec(string codec)
  285. {
  286. // For these need to find out the ffmpeg names
  287. if (string.Equals(codec, "mp2", StringComparison.OrdinalIgnoreCase))
  288. {
  289. return null;
  290. }
  291. if (string.Equals(codec, "aac_latm", StringComparison.OrdinalIgnoreCase))
  292. {
  293. return null;
  294. }
  295. if (string.Equals(codec, "eac3", StringComparison.OrdinalIgnoreCase))
  296. {
  297. return null;
  298. }
  299. if (_mediaEncoder.SupportsDecoder(codec))
  300. {
  301. return codec;
  302. }
  303. return null;
  304. }
  305. /// <summary>
  306. /// Infers the audio codec based on the url.
  307. /// </summary>
  308. /// <param name="container">Container to use.</param>
  309. /// <returns>Codec string.</returns>
  310. public string InferAudioCodec(string container)
  311. {
  312. var ext = "." + (container ?? string.Empty);
  313. if (string.Equals(ext, ".mp3", StringComparison.OrdinalIgnoreCase))
  314. {
  315. return "mp3";
  316. }
  317. if (string.Equals(ext, ".aac", StringComparison.OrdinalIgnoreCase))
  318. {
  319. return "aac";
  320. }
  321. if (string.Equals(ext, ".wma", StringComparison.OrdinalIgnoreCase))
  322. {
  323. return "wma";
  324. }
  325. if (string.Equals(ext, ".ogg", StringComparison.OrdinalIgnoreCase))
  326. {
  327. return "vorbis";
  328. }
  329. if (string.Equals(ext, ".oga", StringComparison.OrdinalIgnoreCase))
  330. {
  331. return "vorbis";
  332. }
  333. if (string.Equals(ext, ".ogv", StringComparison.OrdinalIgnoreCase))
  334. {
  335. return "vorbis";
  336. }
  337. if (string.Equals(ext, ".webm", StringComparison.OrdinalIgnoreCase))
  338. {
  339. return "vorbis";
  340. }
  341. if (string.Equals(ext, ".webma", StringComparison.OrdinalIgnoreCase))
  342. {
  343. return "vorbis";
  344. }
  345. return "copy";
  346. }
  347. /// <summary>
  348. /// Infers the video codec.
  349. /// </summary>
  350. /// <param name="url">The URL.</param>
  351. /// <returns>System.Nullable{VideoCodecs}.</returns>
  352. public string InferVideoCodec(string url)
  353. {
  354. var ext = Path.GetExtension(url);
  355. if (string.Equals(ext, ".asf", StringComparison.OrdinalIgnoreCase))
  356. {
  357. return "wmv";
  358. }
  359. if (string.Equals(ext, ".webm", StringComparison.OrdinalIgnoreCase))
  360. {
  361. // TODO: this may not always mean VP8, as the codec ages
  362. return "vp8";
  363. }
  364. if (string.Equals(ext, ".ogg", StringComparison.OrdinalIgnoreCase) || string.Equals(ext, ".ogv", StringComparison.OrdinalIgnoreCase))
  365. {
  366. return "theora";
  367. }
  368. if (string.Equals(ext, ".m3u8", StringComparison.OrdinalIgnoreCase) || string.Equals(ext, ".ts", StringComparison.OrdinalIgnoreCase))
  369. {
  370. return "h264";
  371. }
  372. return "copy";
  373. }
  374. public int GetVideoProfileScore(string videoCodec, string videoProfile)
  375. {
  376. // strip spaces because they may be stripped out on the query string
  377. string profile = videoProfile.Replace(" ", string.Empty, StringComparison.Ordinal);
  378. if (string.Equals("h264", videoCodec, StringComparison.OrdinalIgnoreCase))
  379. {
  380. return Array.FindIndex(_videoProfilesH264, x => string.Equals(x, profile, StringComparison.OrdinalIgnoreCase));
  381. }
  382. else if (string.Equals("hevc", videoCodec, StringComparison.OrdinalIgnoreCase))
  383. {
  384. return Array.FindIndex(_videoProfilesH265, x => string.Equals(x, profile, StringComparison.OrdinalIgnoreCase));
  385. }
  386. return -1;
  387. }
  388. public string GetInputPathArgument(EncodingJobInfo state)
  389. {
  390. var mediaPath = state.MediaPath ?? string.Empty;
  391. return _mediaEncoder.GetInputArgument(mediaPath, state.MediaSource);
  392. }
  393. /// <summary>
  394. /// Gets the audio encoder.
  395. /// </summary>
  396. /// <param name="state">The state.</param>
  397. /// <returns>System.String.</returns>
  398. public string GetAudioEncoder(EncodingJobInfo state)
  399. {
  400. var codec = state.OutputAudioCodec;
  401. if (string.Equals(codec, "aac", StringComparison.OrdinalIgnoreCase))
  402. {
  403. // Use libfdk_aac for better audio quality if using custom build of FFmpeg which has fdk_aac support
  404. if (_mediaEncoder.SupportsEncoder("libfdk_aac"))
  405. {
  406. return "libfdk_aac";
  407. }
  408. return "aac";
  409. }
  410. if (string.Equals(codec, "mp3", StringComparison.OrdinalIgnoreCase))
  411. {
  412. return "libmp3lame";
  413. }
  414. if (string.Equals(codec, "vorbis", StringComparison.OrdinalIgnoreCase))
  415. {
  416. return "libvorbis";
  417. }
  418. if (string.Equals(codec, "wma", StringComparison.OrdinalIgnoreCase))
  419. {
  420. return "wmav2";
  421. }
  422. if (string.Equals(codec, "opus", StringComparison.OrdinalIgnoreCase))
  423. {
  424. return "libopus";
  425. }
  426. if (string.Equals(codec, "flac", StringComparison.OrdinalIgnoreCase))
  427. {
  428. // flac is experimental in mp4 muxer
  429. return "flac -strict -2";
  430. }
  431. return codec.ToLowerInvariant();
  432. }
  433. public string GetVideoToolboxDeviceArgs(string alias)
  434. {
  435. alias ??= _videotoolboxAlias;
  436. // device selection in vt is not supported.
  437. return " -init_hw_device videotoolbox=" + alias;
  438. }
  439. public string GetCudaDeviceArgs(int deviceIndex, string alias)
  440. {
  441. alias ??= _cudaAlias;
  442. deviceIndex = deviceIndex >= 0
  443. ? deviceIndex
  444. : 0;
  445. return string.Format(
  446. CultureInfo.InvariantCulture,
  447. " -init_hw_device cuda={0}:{1}",
  448. alias, deviceIndex);
  449. }
  450. public string GetOpenclDeviceArgs(int deviceIndex, string deviceVendorName, string srcDeviceAlias, string alias)
  451. {
  452. alias ??= _openclAlias;
  453. deviceIndex = deviceIndex >= 0
  454. ? deviceIndex
  455. : 0;
  456. var vendorOpts = !string.IsNullOrEmpty(deviceVendorName)
  457. ? (":." + deviceIndex + ",device_vendor=\"" + deviceVendorName + "\"")
  458. : ":0.0";
  459. var options = !string.IsNullOrEmpty(srcDeviceAlias)
  460. ? ("@" + srcDeviceAlias)
  461. : vendorOpts;
  462. return string.Format(
  463. CultureInfo.InvariantCulture,
  464. " -init_hw_device opencl={0}{1}",
  465. alias, options);
  466. }
  467. public string GetD3d11vaDeviceArgs(int deviceIndex, string deviceVendorId, string alias)
  468. {
  469. alias ??= _d3d11vaAlias;
  470. deviceIndex = deviceIndex >= 0 ? deviceIndex : 0;
  471. var options = !string.IsNullOrEmpty(deviceVendorId)
  472. ? (",vendor=" + deviceVendorId)
  473. : Convert.ToString(deviceIndex, CultureInfo.InvariantCulture);
  474. return string.Format(
  475. CultureInfo.InvariantCulture,
  476. " -init_hw_device d3d11va={0}:{1}",
  477. alias, options);
  478. }
  479. public string GetVaapiDeviceArgs(string renderNodePath, string kernelDriver, string driver, string alias)
  480. {
  481. alias ??= _vaapiAlias;
  482. renderNodePath = renderNodePath ?? "/dev/dri/renderD128";
  483. var options = (!string.IsNullOrEmpty(kernelDriver) && !string.IsNullOrEmpty(driver))
  484. ? (",kernel_driver=" + kernelDriver + ",driver=" + driver)
  485. : renderNodePath;
  486. return string.Format(
  487. CultureInfo.InvariantCulture,
  488. " -init_hw_device vaapi={0}:{1}",
  489. alias, options);
  490. }
  491. public string GetQsvDeviceArgs(string alias)
  492. {
  493. var arg = " -init_hw_device qsv=" + (alias ?? _qsvAlias);
  494. var args = new StringBuilder();
  495. var isWindows = OperatingSystem.IsWindows();
  496. var isLinux = OperatingSystem.IsLinux();
  497. if (isLinux)
  498. {
  499. // derive qsv from vaapi device
  500. string srcAlias = _vaapiAlias;
  501. args.Append(GetVaapiDeviceArgs(null, "i915", "iHD", srcAlias))
  502. .Append(arg + "@" + srcAlias);
  503. }
  504. else if (isWindows)
  505. {
  506. // derive qsv from d3d11va device
  507. string srcAlias = _d3d11vaAlias;
  508. args.Append(GetD3d11vaDeviceArgs(0, "0x8086", srcAlias))
  509. .Append(arg + "@" + srcAlias);
  510. }
  511. else
  512. {
  513. return null;
  514. }
  515. return args.ToString();
  516. }
  517. public string GetFilterHwDeviceArgs(string alias)
  518. {
  519. return !string.IsNullOrEmpty(alias)
  520. ? (" -filter_hw_device " + alias)
  521. : string.Empty;
  522. }
  523. public string GetGraphicalSubCanvasSize(EncodingJobInfo state)
  524. {
  525. if (state.SubtitleStream != null
  526. && state.SubtitleDeliveryMethod == SubtitleDeliveryMethod.Encode
  527. && !state.SubtitleStream.IsTextSubtitleStream)
  528. {
  529. var inW = state.VideoStream?.Width;
  530. var inH = state.VideoStream?.Height;
  531. var reqW = state.BaseRequest.Width;
  532. var reqH = state.BaseRequest.Height;
  533. var reqMaxW = state.BaseRequest.MaxWidth;
  534. var reqMaxH = state.BaseRequest.MaxHeight;
  535. // setup a relative small canvas_size for overlay_qsv to reduce transfer overhead
  536. var (overlayW, overlayH) = GetFixedOutputSize(inW, inH, reqW, reqH, reqMaxW, 1080);
  537. if (overlayW.HasValue && overlayH.HasValue)
  538. {
  539. return string.Format(
  540. CultureInfo.InvariantCulture,
  541. " -canvas_size {0}x{1}",
  542. overlayW.Value,
  543. overlayH.Value);
  544. }
  545. }
  546. return string.Empty;
  547. }
  548. /// <summary>
  549. /// Gets the input video hwaccel argument.
  550. /// </summary>
  551. /// <param name="state">Encoding state.</param>
  552. /// <param name="options">Encoding options.</param>
  553. /// <returns>Input video hwaccel arguments.</returns>
  554. public string GetInputVideoHwaccelArgs(EncodingJobInfo state, EncodingOptions options)
  555. {
  556. if (!state.IsVideoRequest)
  557. {
  558. return null;
  559. }
  560. var vidEncoder = GetVideoEncoder(state, options) ?? string.Empty;
  561. if (IsCopyCodec(vidEncoder))
  562. {
  563. return null;
  564. }
  565. var args = new StringBuilder();
  566. var isWindows = OperatingSystem.IsWindows();
  567. var isLinux = OperatingSystem.IsLinux();
  568. var isMacOS = OperatingSystem.IsMacOS();
  569. var optHwaccelType = options.HardwareAccelerationType;
  570. var vidDecoder = GetHardwareVideoDecoder(state, options) ?? string.Empty;
  571. #pragma warning disable CA1508 // Defaults to string.Empty
  572. var isSwVidDecoder = string.IsNullOrEmpty(vidDecoder);
  573. #pragma warning restore CA1508
  574. var isHwTonemapAvailable = IsHwTonemapAvailable(state, options);
  575. if (string.Equals(optHwaccelType, "vaapi", StringComparison.OrdinalIgnoreCase))
  576. {
  577. if (!isLinux || !_mediaEncoder.SupportsHwaccel("vaapi"))
  578. {
  579. return string.Empty;
  580. }
  581. var isVaapiDecoder = vidDecoder.Contains("vaapi", StringComparison.OrdinalIgnoreCase);
  582. var isVaapiEncoder = vidEncoder.Contains("vaapi", StringComparison.OrdinalIgnoreCase);
  583. if (!isVaapiDecoder && !isVaapiEncoder)
  584. {
  585. return string.Empty;
  586. }
  587. var vaArgs = GetVaapiDeviceArgs(options.VaapiDevice, null, null, _vaapiAlias);
  588. var filterDevArgs = GetFilterHwDeviceArgs(_vaapiAlias);
  589. if (isHwTonemapAvailable && IsOpenclFullSupported())
  590. {
  591. if (_mediaEncoder.IsVaapiDeviceInteliHD() || _mediaEncoder.IsVaapiDeviceInteli965())
  592. {
  593. if (!isVaapiDecoder)
  594. {
  595. vaArgs += GetOpenclDeviceArgs(0, null, _vaapiAlias, _openclAlias);
  596. filterDevArgs = GetFilterHwDeviceArgs(_openclAlias);
  597. }
  598. }
  599. else if (_mediaEncoder.IsVaapiDeviceAmd())
  600. {
  601. vaArgs += GetOpenclDeviceArgs(0, "Advanced Micro Devices", null, _openclAlias);
  602. filterDevArgs = GetFilterHwDeviceArgs(_openclAlias);
  603. }
  604. else
  605. {
  606. vaArgs += GetOpenclDeviceArgs(0, null, null, _openclAlias);
  607. filterDevArgs = GetFilterHwDeviceArgs(_openclAlias);
  608. }
  609. }
  610. args.Append(vaArgs)
  611. .Append(filterDevArgs);
  612. }
  613. else if (string.Equals(optHwaccelType, "qsv", StringComparison.OrdinalIgnoreCase))
  614. {
  615. if ((!isLinux && !isWindows) || !_mediaEncoder.SupportsHwaccel("qsv"))
  616. {
  617. return string.Empty;
  618. }
  619. var isD3d11vaDecoder = vidDecoder.Contains("d3d11va", StringComparison.OrdinalIgnoreCase);
  620. var isVaapiDecoder = vidDecoder.Contains("vaapi", StringComparison.OrdinalIgnoreCase);
  621. var isQsvDecoder = vidDecoder.Contains("qsv", StringComparison.OrdinalIgnoreCase);
  622. var isQsvEncoder = vidEncoder.Contains("qsv", StringComparison.OrdinalIgnoreCase);
  623. var isHwDecoder = isQsvDecoder || isVaapiDecoder || isD3d11vaDecoder;
  624. if (!isHwDecoder && !isQsvEncoder)
  625. {
  626. return string.Empty;
  627. }
  628. var qsvArgs = GetQsvDeviceArgs(_qsvAlias);
  629. var filterDevArgs = GetFilterHwDeviceArgs(_qsvAlias);
  630. // child device used by qsv.
  631. if (_mediaEncoder.SupportsHwaccel("vaapi") || _mediaEncoder.SupportsHwaccel("d3d11va"))
  632. {
  633. if (isHwTonemapAvailable && IsOpenclFullSupported())
  634. {
  635. var srcAlias = isLinux ? _vaapiAlias : _d3d11vaAlias;
  636. qsvArgs += GetOpenclDeviceArgs(0, null, srcAlias, _openclAlias);
  637. if (!isHwDecoder)
  638. {
  639. filterDevArgs = GetFilterHwDeviceArgs(_openclAlias);
  640. }
  641. }
  642. }
  643. args.Append(qsvArgs)
  644. .Append(filterDevArgs);
  645. }
  646. else if (string.Equals(optHwaccelType, "nvenc", StringComparison.OrdinalIgnoreCase))
  647. {
  648. if ((!isLinux && !isWindows) || !IsCudaFullSupported())
  649. {
  650. return string.Empty;
  651. }
  652. var isCuvidDecoder = vidDecoder.Contains("cuvid", StringComparison.OrdinalIgnoreCase);
  653. var isNvdecDecoder = vidDecoder.Contains("cuda", StringComparison.OrdinalIgnoreCase);
  654. var isNvencEncoder = vidEncoder.Contains("nvenc", StringComparison.OrdinalIgnoreCase);
  655. var isHwDecoder = isNvdecDecoder || isCuvidDecoder;
  656. if (!isHwDecoder && !isNvencEncoder)
  657. {
  658. return string.Empty;
  659. }
  660. var cuArgs = GetCudaDeviceArgs(0, _cudaAlias);
  661. var filterDevArgs = GetFilterHwDeviceArgs(_cudaAlias);
  662. // workaround for "No decoder surfaces left" error,
  663. // but will increase vram usage. https://trac.ffmpeg.org/ticket/7562
  664. var extraHwFramesArgs = " -extra_hw_frames 3";
  665. args.Append(cuArgs)
  666. .Append(filterDevArgs)
  667. .Append(extraHwFramesArgs);
  668. }
  669. else if (string.Equals(optHwaccelType, "amf", StringComparison.OrdinalIgnoreCase))
  670. {
  671. if (!isWindows || !_mediaEncoder.SupportsHwaccel("d3d11va"))
  672. {
  673. return string.Empty;
  674. }
  675. var isD3d11vaDecoder = vidDecoder.Contains("d3d11va", StringComparison.OrdinalIgnoreCase);
  676. var isAmfEncoder = vidEncoder.Contains("amf", StringComparison.OrdinalIgnoreCase);
  677. if (!isD3d11vaDecoder && !isAmfEncoder)
  678. {
  679. return string.Empty;
  680. }
  681. // no dxva video processor hw filter.
  682. var dx11Args = GetD3d11vaDeviceArgs(0, "0x1002", _d3d11vaAlias);
  683. var filterDevArgs = string.Empty;
  684. if (IsOpenclFullSupported())
  685. {
  686. dx11Args += GetOpenclDeviceArgs(0, null, _d3d11vaAlias, _openclAlias);
  687. filterDevArgs = GetFilterHwDeviceArgs(_openclAlias);
  688. }
  689. args.Append(dx11Args)
  690. .Append(filterDevArgs);
  691. }
  692. else if (string.Equals(optHwaccelType, "videotoolbox", StringComparison.OrdinalIgnoreCase))
  693. {
  694. if (!isMacOS || !_mediaEncoder.SupportsHwaccel("videotoolbox"))
  695. {
  696. return string.Empty;
  697. }
  698. var isVideotoolboxDecoder = vidDecoder.Contains("videotoolbox", StringComparison.OrdinalIgnoreCase);
  699. var isVideotoolboxEncoder = vidEncoder.Contains("videotoolbox", StringComparison.OrdinalIgnoreCase);
  700. if (!isVideotoolboxDecoder && !isVideotoolboxEncoder)
  701. {
  702. return string.Empty;
  703. }
  704. // no videotoolbox hw filter.
  705. var vtArgs = GetVideoToolboxDeviceArgs(_videotoolboxAlias);
  706. args.Append(vtArgs);
  707. }
  708. if (!string.IsNullOrEmpty(vidDecoder))
  709. {
  710. args.Append(vidDecoder);
  711. }
  712. // hw transpose filters should be added manually.
  713. args.Append(" -autorotate 0");
  714. return args.ToString().Trim();
  715. }
  716. /// <summary>
  717. /// Gets the input argument.
  718. /// </summary>
  719. /// <param name="state">Encoding state.</param>
  720. /// <param name="options">Encoding options.</param>
  721. /// <returns>Input arguments.</returns>
  722. public string GetInputArgument(EncodingJobInfo state, EncodingOptions options)
  723. {
  724. var arg = new StringBuilder();
  725. var inputVidHwaccelArgs = GetInputVideoHwaccelArgs(state, options);
  726. if (!string.IsNullOrEmpty(inputVidHwaccelArgs))
  727. {
  728. arg.Append(inputVidHwaccelArgs);
  729. }
  730. var canvasArgs = GetGraphicalSubCanvasSize(state);
  731. if (!string.IsNullOrEmpty(canvasArgs))
  732. {
  733. arg.Append(canvasArgs);
  734. }
  735. arg.Append(" -i ")
  736. .Append(GetInputPathArgument(state));
  737. // sub2video for external graphical subtitles
  738. if (state.SubtitleStream != null
  739. && state.SubtitleDeliveryMethod == SubtitleDeliveryMethod.Encode
  740. && !state.SubtitleStream.IsTextSubtitleStream
  741. && state.SubtitleStream.IsExternal)
  742. {
  743. var subtitlePath = state.SubtitleStream.Path;
  744. if (string.Equals(Path.GetExtension(subtitlePath), ".sub", StringComparison.OrdinalIgnoreCase))
  745. {
  746. var idxFile = Path.ChangeExtension(subtitlePath, ".idx");
  747. if (File.Exists(idxFile))
  748. {
  749. subtitlePath = idxFile;
  750. }
  751. }
  752. // Also seek the external subtitles stream.
  753. var seekSubParam = GetFastSeekCommandLineParameter(state, options);
  754. if (!string.IsNullOrEmpty(seekSubParam))
  755. {
  756. arg.Append(' ').Append(seekSubParam);
  757. }
  758. if (!string.IsNullOrEmpty(canvasArgs))
  759. {
  760. arg.Append(canvasArgs);
  761. }
  762. arg.Append(" -i file:\"").Append(subtitlePath).Append('\"');
  763. }
  764. return arg.ToString();
  765. }
  766. /// <summary>
  767. /// Determines whether the specified stream is H264.
  768. /// </summary>
  769. /// <param name="stream">The stream.</param>
  770. /// <returns><c>true</c> if the specified stream is H264; otherwise, <c>false</c>.</returns>
  771. public static bool IsH264(MediaStream stream)
  772. {
  773. var codec = stream.Codec ?? string.Empty;
  774. return codec.IndexOf("264", StringComparison.OrdinalIgnoreCase) != -1
  775. || codec.IndexOf("avc", StringComparison.OrdinalIgnoreCase) != -1;
  776. }
  777. public static bool IsH265(MediaStream stream)
  778. {
  779. var codec = stream.Codec ?? string.Empty;
  780. return codec.IndexOf("265", StringComparison.OrdinalIgnoreCase) != -1
  781. || codec.IndexOf("hevc", StringComparison.OrdinalIgnoreCase) != -1;
  782. }
  783. public static bool IsAAC(MediaStream stream)
  784. {
  785. var codec = stream.Codec ?? string.Empty;
  786. return codec.IndexOf("aac", StringComparison.OrdinalIgnoreCase) != -1;
  787. }
  788. public static string GetBitStreamArgs(MediaStream stream)
  789. {
  790. // TODO This is auto inserted into the mpegts mux so it might not be needed.
  791. // https://www.ffmpeg.org/ffmpeg-bitstream-filters.html#h264_005fmp4toannexb
  792. if (IsH264(stream))
  793. {
  794. return "-bsf:v h264_mp4toannexb";
  795. }
  796. else if (IsH265(stream))
  797. {
  798. return "-bsf:v hevc_mp4toannexb";
  799. }
  800. else if (IsAAC(stream))
  801. {
  802. // Convert adts header(mpegts) to asc header(mp4).
  803. return "-bsf:a aac_adtstoasc";
  804. }
  805. else
  806. {
  807. return null;
  808. }
  809. }
  810. public static string GetAudioBitStreamArguments(EncodingJobInfo state, string segmentContainer, string mediaSourceContainer)
  811. {
  812. var bitStreamArgs = string.Empty;
  813. var segmentFormat = GetSegmentFileExtension(segmentContainer).TrimStart('.');
  814. // Apply aac_adtstoasc bitstream filter when media source is in mpegts.
  815. if (string.Equals(segmentFormat, "mp4", StringComparison.OrdinalIgnoreCase)
  816. && (string.Equals(mediaSourceContainer, "mpegts", StringComparison.OrdinalIgnoreCase)
  817. || string.Equals(mediaSourceContainer, "hls", StringComparison.OrdinalIgnoreCase)))
  818. {
  819. bitStreamArgs = GetBitStreamArgs(state.AudioStream);
  820. bitStreamArgs = string.IsNullOrEmpty(bitStreamArgs) ? string.Empty : " " + bitStreamArgs;
  821. }
  822. return bitStreamArgs;
  823. }
  824. public static string GetSegmentFileExtension(string segmentContainer)
  825. {
  826. if (!string.IsNullOrWhiteSpace(segmentContainer))
  827. {
  828. return "." + segmentContainer;
  829. }
  830. return ".ts";
  831. }
  832. public string GetVideoBitrateParam(EncodingJobInfo state, string videoCodec)
  833. {
  834. if (state.OutputVideoBitrate == null)
  835. {
  836. return string.Empty;
  837. }
  838. int bitrate = state.OutputVideoBitrate.Value;
  839. // Currently use the same buffer size for all encoders
  840. int bufsize = bitrate * 2;
  841. if (string.Equals(videoCodec, "libvpx", StringComparison.OrdinalIgnoreCase)
  842. || string.Equals(videoCodec, "libvpx-vp9", StringComparison.OrdinalIgnoreCase))
  843. {
  844. // When crf is used with vpx, b:v becomes a max rate
  845. // https://trac.ffmpeg.org/wiki/Encode/VP8
  846. // https://trac.ffmpeg.org/wiki/Encode/VP9
  847. return FormattableString.Invariant($" -maxrate:v {bitrate} -bufsize:v {bufsize} -b:v {bitrate}");
  848. }
  849. if (string.Equals(videoCodec, "msmpeg4", StringComparison.OrdinalIgnoreCase))
  850. {
  851. return FormattableString.Invariant($" -b:v {bitrate}");
  852. }
  853. if (string.Equals(videoCodec, "libx264", StringComparison.OrdinalIgnoreCase)
  854. || string.Equals(videoCodec, "libx265", StringComparison.OrdinalIgnoreCase))
  855. {
  856. return FormattableString.Invariant($" -maxrate {bitrate} -bufsize {bufsize}");
  857. }
  858. if (string.Equals(videoCodec, "h264_amf", StringComparison.OrdinalIgnoreCase)
  859. || string.Equals(videoCodec, "hevc_amf", StringComparison.OrdinalIgnoreCase))
  860. {
  861. return FormattableString.Invariant($" -qmin 18 -qmax 32 -b:v {bitrate} -maxrate {bitrate} -bufsize {bufsize}");
  862. }
  863. if (string.Equals(videoCodec, "h264_vaapi", StringComparison.OrdinalIgnoreCase)
  864. || string.Equals(videoCodec, "hevc_vaapi", StringComparison.OrdinalIgnoreCase))
  865. {
  866. // VBR in i965 driver may result in pixelated output.
  867. if (_mediaEncoder.IsVaapiDeviceInteli965())
  868. {
  869. return FormattableString.Invariant($" -rc_mode CBR -b:v {bitrate} -maxrate {bitrate} -bufsize {bufsize}");
  870. }
  871. else
  872. {
  873. return FormattableString.Invariant($" -rc_mode VBR -b:v {bitrate} -maxrate {bitrate} -bufsize {bufsize}");
  874. }
  875. }
  876. return FormattableString.Invariant($" -b:v {bitrate} -maxrate {bitrate} -bufsize {bufsize}");
  877. }
  878. public static string NormalizeTranscodingLevel(EncodingJobInfo state, string level)
  879. {
  880. if (double.TryParse(level, NumberStyles.Any, CultureInfo.InvariantCulture, out double requestLevel))
  881. {
  882. if (string.Equals(state.ActualOutputVideoCodec, "hevc", StringComparison.OrdinalIgnoreCase)
  883. || string.Equals(state.ActualOutputVideoCodec, "h265", StringComparison.OrdinalIgnoreCase))
  884. {
  885. // Transcode to level 5.0 and lower for maximum compatibility.
  886. // Level 5.0 is suitable for up to 4k 30fps hevc encoding, otherwise let the encoder to handle it.
  887. // https://en.wikipedia.org/wiki/High_Efficiency_Video_Coding_tiers_and_levels
  888. // MaxLumaSampleRate = 3840*2160*30 = 248832000 < 267386880.
  889. if (requestLevel >= 150)
  890. {
  891. return "150";
  892. }
  893. }
  894. else if (string.Equals(state.ActualOutputVideoCodec, "h264", StringComparison.OrdinalIgnoreCase))
  895. {
  896. // Clients may direct play higher than level 41, but there's no reason to transcode higher.
  897. if (requestLevel >= 41)
  898. {
  899. return "41";
  900. }
  901. }
  902. }
  903. return level;
  904. }
  905. /// <summary>
  906. /// Gets the text subtitle param.
  907. /// </summary>
  908. /// <param name="state">The state.</param>
  909. /// <param name="enableAlpha">Enable alpha processing.</param>
  910. /// <param name="enableSub2video">Enable sub2video mode.</param>
  911. /// <returns>System.String.</returns>
  912. public string GetTextSubtitlesFilter(EncodingJobInfo state, bool enableAlpha, bool enableSub2video)
  913. {
  914. var seconds = Math.Round(TimeSpan.FromTicks(state.StartTimeTicks ?? 0).TotalSeconds);
  915. // hls always copies timestamps
  916. var setPtsParam = state.CopyTimestamps || state.TranscodingType != TranscodingJobType.Progressive
  917. ? string.Empty
  918. : string.Format(CultureInfo.InvariantCulture, ",setpts=PTS -{0}/TB", seconds);
  919. var alphaParam = enableAlpha ? (":alpha=" + Convert.ToInt32(enableAlpha)) : string.Empty;
  920. var sub2videoParam = enableSub2video ? (":sub2video=" + Convert.ToInt32(enableSub2video)) : string.Empty;
  921. // TODO
  922. // var fallbackFontPath = Path.Combine(_appPaths.ProgramDataPath, "fonts", "DroidSansFallback.ttf");
  923. // string fallbackFontParam = string.Empty;
  924. // if (!File.Exists(fallbackFontPath))
  925. // {
  926. // _fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(fallbackFontPath));
  927. // using (var stream = _assemblyInfo.GetManifestResourceStream(GetType(), GetType().Namespace + ".DroidSansFallback.ttf"))
  928. // {
  929. // using (var fileStream = new FileStream(fallbackFontPath, FileMode.Create, FileAccess.Write, FileShare.Read))
  930. // {
  931. // stream.CopyTo(fileStream);
  932. // }
  933. // }
  934. // }
  935. // fallbackFontParam = string.Format(CultureInfo.InvariantCulture, ":force_style='FontName=Droid Sans Fallback':fontsdir='{0}'", _mediaEncoder.EscapeSubtitleFilterPath(_fileSystem.GetDirectoryName(fallbackFontPath)));
  936. if (state.SubtitleStream.IsExternal)
  937. {
  938. var subtitlePath = state.SubtitleStream.Path;
  939. var charsetParam = string.Empty;
  940. if (!string.IsNullOrEmpty(state.SubtitleStream.Language))
  941. {
  942. var charenc = _subtitleEncoder.GetSubtitleFileCharacterSet(
  943. subtitlePath,
  944. state.SubtitleStream.Language,
  945. state.MediaSource.Protocol,
  946. CancellationToken.None).GetAwaiter().GetResult();
  947. if (!string.IsNullOrEmpty(charenc))
  948. {
  949. charsetParam = ":charenc=" + charenc;
  950. }
  951. }
  952. // TODO: Perhaps also use original_size=1920x800 ??
  953. return string.Format(
  954. CultureInfo.InvariantCulture,
  955. "subtitles=f='{0}'{1}{2}{3}{4}",
  956. _mediaEncoder.EscapeSubtitleFilterPath(subtitlePath),
  957. charsetParam,
  958. alphaParam,
  959. sub2videoParam,
  960. // fallbackFontParam,
  961. setPtsParam);
  962. }
  963. var mediaPath = state.MediaPath ?? string.Empty;
  964. return string.Format(
  965. CultureInfo.InvariantCulture,
  966. "subtitles='{0}:si={1}{2}{3}'{4}",
  967. _mediaEncoder.EscapeSubtitleFilterPath(mediaPath),
  968. state.InternalSubtitleStreamOffset.ToString(CultureInfo.InvariantCulture),
  969. alphaParam,
  970. sub2videoParam,
  971. // fallbackFontParam,
  972. setPtsParam);
  973. }
  974. public double? GetFramerateParam(EncodingJobInfo state)
  975. {
  976. var request = state.BaseRequest;
  977. if (request.Framerate.HasValue)
  978. {
  979. return request.Framerate.Value;
  980. }
  981. var maxrate = request.MaxFramerate;
  982. if (maxrate.HasValue && state.VideoStream != null)
  983. {
  984. var contentRate = state.VideoStream.AverageFrameRate ?? state.VideoStream.RealFrameRate;
  985. if (contentRate.HasValue && contentRate.Value > maxrate.Value)
  986. {
  987. return maxrate;
  988. }
  989. }
  990. return null;
  991. }
  992. public string GetHlsVideoKeyFrameArguments(
  993. EncodingJobInfo state,
  994. string codec,
  995. int segmentLength,
  996. bool isEventPlaylist,
  997. int? startNumber)
  998. {
  999. var args = string.Empty;
  1000. var gopArg = string.Empty;
  1001. var keyFrameArg = string.Empty;
  1002. if (isEventPlaylist)
  1003. {
  1004. keyFrameArg = string.Format(
  1005. CultureInfo.InvariantCulture,
  1006. " -force_key_frames:0 \"expr:gte(t,n_forced*{0})\"",
  1007. segmentLength);
  1008. }
  1009. else if (startNumber.HasValue)
  1010. {
  1011. keyFrameArg = string.Format(
  1012. CultureInfo.InvariantCulture,
  1013. " -force_key_frames:0 \"expr:gte(t,{0}+n_forced*{1})\"",
  1014. startNumber.Value * segmentLength,
  1015. segmentLength);
  1016. }
  1017. var framerate = state.VideoStream?.RealFrameRate;
  1018. if (framerate.HasValue)
  1019. {
  1020. // This is to make sure keyframe interval is limited to our segment,
  1021. // as forcing keyframes is not enough.
  1022. // Example: we encoded half of desired length, then codec detected
  1023. // scene cut and inserted a keyframe; next forced keyframe would
  1024. // be created outside of segment, which breaks seeking.
  1025. // -sc_threshold 0 is used to prevent the hardware encoder from post processing to break the set keyframe.
  1026. gopArg = string.Format(
  1027. CultureInfo.InvariantCulture,
  1028. " -g:v:0 {0} -keyint_min:v:0 {0} -sc_threshold:v:0 0",
  1029. Math.Ceiling(segmentLength * framerate.Value));
  1030. }
  1031. // Unable to force key frames using these encoders, set key frames by GOP.
  1032. if (string.Equals(codec, "h264_qsv", StringComparison.OrdinalIgnoreCase)
  1033. || string.Equals(codec, "h264_nvenc", StringComparison.OrdinalIgnoreCase)
  1034. || string.Equals(codec, "h264_amf", StringComparison.OrdinalIgnoreCase)
  1035. || string.Equals(codec, "hevc_qsv", StringComparison.OrdinalIgnoreCase)
  1036. || string.Equals(codec, "hevc_nvenc", StringComparison.OrdinalIgnoreCase)
  1037. || string.Equals(codec, "hevc_amf", StringComparison.OrdinalIgnoreCase))
  1038. {
  1039. args += gopArg;
  1040. }
  1041. else if (string.Equals(codec, "libx264", StringComparison.OrdinalIgnoreCase)
  1042. || string.Equals(codec, "libx265", StringComparison.OrdinalIgnoreCase)
  1043. || string.Equals(codec, "h264_vaapi", StringComparison.OrdinalIgnoreCase)
  1044. || string.Equals(codec, "hevc_vaapi", StringComparison.OrdinalIgnoreCase))
  1045. {
  1046. args += keyFrameArg;
  1047. }
  1048. else
  1049. {
  1050. args += keyFrameArg + gopArg;
  1051. }
  1052. return args;
  1053. }
  1054. /// <summary>
  1055. /// Gets the video bitrate to specify on the command line.
  1056. /// </summary>
  1057. /// <param name="state">Encoding state.</param>
  1058. /// <param name="videoEncoder">Video encoder to use.</param>
  1059. /// <param name="encodingOptions">Encoding options.</param>
  1060. /// <param name="defaultPreset">Default present to use for encoding.</param>
  1061. /// <returns>Video bitrate.</returns>
  1062. public string GetVideoQualityParam(EncodingJobInfo state, string videoEncoder, EncodingOptions encodingOptions, string defaultPreset)
  1063. {
  1064. var param = string.Empty;
  1065. // Tutorials: Enable Intel GuC / HuC firmware loading for Low Power Encoding.
  1066. // https://01.org/linuxgraphics/downloads/firmware
  1067. // https://wiki.archlinux.org/title/intel_graphics#Enable_GuC_/_HuC_firmware_loading
  1068. // Intel Low Power Encoding can save unnecessary CPU-GPU synchronization,
  1069. // which will reduce overhead in performance intensive tasks such as 4k transcoding and tonemapping.
  1070. var intelLowPowerHwEncoding = false;
  1071. if (string.Equals(encodingOptions.HardwareAccelerationType, "vaapi", StringComparison.OrdinalIgnoreCase))
  1072. {
  1073. var isIntelVaapiDriver = _mediaEncoder.IsVaapiDeviceInteliHD() || _mediaEncoder.IsVaapiDeviceInteli965();
  1074. if (string.Equals(videoEncoder, "h264_vaapi", StringComparison.OrdinalIgnoreCase))
  1075. {
  1076. intelLowPowerHwEncoding = encodingOptions.EnableIntelLowPowerH264HwEncoder && isIntelVaapiDriver;
  1077. }
  1078. else if (string.Equals(videoEncoder, "hevc_vaapi", StringComparison.OrdinalIgnoreCase))
  1079. {
  1080. intelLowPowerHwEncoding = encodingOptions.EnableIntelLowPowerHevcHwEncoder && isIntelVaapiDriver;
  1081. }
  1082. }
  1083. else if (string.Equals(encodingOptions.HardwareAccelerationType, "qsv", StringComparison.OrdinalIgnoreCase))
  1084. {
  1085. if (string.Equals(videoEncoder, "h264_qsv", StringComparison.OrdinalIgnoreCase))
  1086. {
  1087. intelLowPowerHwEncoding = encodingOptions.EnableIntelLowPowerH264HwEncoder;
  1088. }
  1089. else if (string.Equals(videoEncoder, "hevc_qsv", StringComparison.OrdinalIgnoreCase))
  1090. {
  1091. intelLowPowerHwEncoding = encodingOptions.EnableIntelLowPowerHevcHwEncoder;
  1092. }
  1093. }
  1094. if (intelLowPowerHwEncoding)
  1095. {
  1096. param += " -low_power 1";
  1097. }
  1098. if (string.Equals(videoEncoder, "h264_v4l2m2m", StringComparison.OrdinalIgnoreCase))
  1099. {
  1100. param += " -pix_fmt nv21";
  1101. }
  1102. var isVc1 = string.Equals(state.VideoStream.Codec ?? string.Empty, "vc1", StringComparison.OrdinalIgnoreCase);
  1103. var isLibX265 = string.Equals(videoEncoder, "libx265", StringComparison.OrdinalIgnoreCase);
  1104. if (string.Equals(videoEncoder, "libx264", StringComparison.OrdinalIgnoreCase) || isLibX265)
  1105. {
  1106. if (!string.IsNullOrEmpty(encodingOptions.EncoderPreset))
  1107. {
  1108. param += " -preset " + encodingOptions.EncoderPreset;
  1109. }
  1110. else
  1111. {
  1112. param += " -preset " + defaultPreset;
  1113. }
  1114. int encodeCrf = encodingOptions.H264Crf;
  1115. if (isLibX265)
  1116. {
  1117. encodeCrf = encodingOptions.H265Crf;
  1118. }
  1119. if (encodeCrf >= 0 && encodeCrf <= 51)
  1120. {
  1121. param += " -crf " + encodeCrf.ToString(CultureInfo.InvariantCulture);
  1122. }
  1123. else
  1124. {
  1125. string defaultCrf = "23";
  1126. if (isLibX265)
  1127. {
  1128. defaultCrf = "28";
  1129. }
  1130. param += " -crf " + defaultCrf;
  1131. }
  1132. }
  1133. else if (string.Equals(videoEncoder, "h264_qsv", StringComparison.OrdinalIgnoreCase) // h264 (h264_qsv)
  1134. || string.Equals(videoEncoder, "hevc_qsv", StringComparison.OrdinalIgnoreCase)) // hevc (hevc_qsv)
  1135. {
  1136. string[] valid_h264_qsv = { "veryslow", "slower", "slow", "medium", "fast", "faster", "veryfast" };
  1137. if (valid_h264_qsv.Contains(encodingOptions.EncoderPreset, StringComparer.OrdinalIgnoreCase))
  1138. {
  1139. param += " -preset " + encodingOptions.EncoderPreset;
  1140. }
  1141. else
  1142. {
  1143. param += " -preset 7";
  1144. }
  1145. param += " -look_ahead 0";
  1146. }
  1147. else if (string.Equals(videoEncoder, "h264_nvenc", StringComparison.OrdinalIgnoreCase) // h264 (h264_nvenc)
  1148. || string.Equals(videoEncoder, "hevc_nvenc", StringComparison.OrdinalIgnoreCase)) // hevc (hevc_nvenc)
  1149. {
  1150. switch (encodingOptions.EncoderPreset)
  1151. {
  1152. case "veryslow":
  1153. param += " -preset slow"; // lossless is only supported on maxwell and newer(2014+)
  1154. break;
  1155. case "slow":
  1156. case "slower":
  1157. param += " -preset slow";
  1158. break;
  1159. case "medium":
  1160. param += " -preset medium";
  1161. break;
  1162. case "fast":
  1163. case "faster":
  1164. case "veryfast":
  1165. case "superfast":
  1166. case "ultrafast":
  1167. param += " -preset fast";
  1168. break;
  1169. default:
  1170. param += " -preset default";
  1171. break;
  1172. }
  1173. }
  1174. else if (string.Equals(videoEncoder, "h264_amf", StringComparison.OrdinalIgnoreCase) // h264 (h264_amf)
  1175. || string.Equals(videoEncoder, "hevc_amf", StringComparison.OrdinalIgnoreCase)) // hevc (hevc_amf)
  1176. {
  1177. switch (encodingOptions.EncoderPreset)
  1178. {
  1179. case "veryslow":
  1180. case "slow":
  1181. case "slower":
  1182. param += " -quality quality";
  1183. break;
  1184. case "medium":
  1185. param += " -quality balanced";
  1186. break;
  1187. case "fast":
  1188. case "faster":
  1189. case "veryfast":
  1190. case "superfast":
  1191. case "ultrafast":
  1192. param += " -quality speed";
  1193. break;
  1194. default:
  1195. param += " -quality speed";
  1196. break;
  1197. }
  1198. if (string.Equals(videoEncoder, "hevc_amf", StringComparison.OrdinalIgnoreCase))
  1199. {
  1200. param += " -header_insertion_mode gop -gops_per_idr 1";
  1201. }
  1202. }
  1203. else if (string.Equals(videoEncoder, "libvpx", StringComparison.OrdinalIgnoreCase)) // vp8
  1204. {
  1205. // Values 0-3, 0 being highest quality but slower
  1206. var profileScore = 0;
  1207. string crf;
  1208. var qmin = "0";
  1209. var qmax = "50";
  1210. crf = "10";
  1211. if (isVc1)
  1212. {
  1213. profileScore++;
  1214. }
  1215. // Max of 2
  1216. profileScore = Math.Min(profileScore, 2);
  1217. // http://www.webmproject.org/docs/encoder-parameters/
  1218. param += string.Format(
  1219. CultureInfo.InvariantCulture,
  1220. " -speed 16 -quality good -profile:v {0} -slices 8 -crf {1} -qmin {2} -qmax {3}",
  1221. profileScore.ToString(CultureInfo.InvariantCulture),
  1222. crf,
  1223. qmin,
  1224. qmax);
  1225. }
  1226. else if (string.Equals(videoEncoder, "libvpx-vp9", StringComparison.OrdinalIgnoreCase)) // vp9
  1227. {
  1228. // When `-deadline` is set to `good` or `best`, `-cpu-used` ranges from 0-5.
  1229. // When `-deadline` is set to `realtime`, `-cpu-used` ranges from 0-15.
  1230. // Resources:
  1231. // * https://trac.ffmpeg.org/wiki/Encode/VP9
  1232. // * https://superuser.com/questions/1586934
  1233. // * https://developers.google.com/media/vp9
  1234. param += encodingOptions.EncoderPreset switch
  1235. {
  1236. "veryslow" => " -deadline best -cpu-used 0",
  1237. "slower" => " -deadline best -cpu-used 2",
  1238. "slow" => " -deadline best -cpu-used 3",
  1239. "medium" => " -deadline good -cpu-used 0",
  1240. "fast" => " -deadline good -cpu-used 1",
  1241. "faster" => " -deadline good -cpu-used 2",
  1242. "veryfast" => " -deadline good -cpu-used 3",
  1243. "superfast" => " -deadline good -cpu-used 4",
  1244. "ultrafast" => " -deadline good -cpu-used 5",
  1245. _ => " -deadline good -cpu-used 1"
  1246. };
  1247. // TODO: until VP9 gets its own CRF setting, base CRF on H.265.
  1248. int h265Crf = encodingOptions.H265Crf;
  1249. int defaultVp9Crf = 31;
  1250. if (h265Crf >= 0 && h265Crf <= 51)
  1251. {
  1252. // This conversion factor is chosen to match the default CRF for H.265 to the
  1253. // recommended 1080p CRF from Google. The factor also maps the logarithmic CRF
  1254. // scale of x265 [0, 51] to that of VP9 [0, 63] relatively well.
  1255. // Resources:
  1256. // * https://developers.google.com/media/vp9/settings/vod
  1257. const float H265ToVp9CrfConversionFactor = 1.12F;
  1258. var vp9Crf = Convert.ToInt32(h265Crf * H265ToVp9CrfConversionFactor);
  1259. // Encoder allows for CRF values in the range [0, 63].
  1260. vp9Crf = Math.Clamp(vp9Crf, 0, 63);
  1261. param += FormattableString.Invariant($" -crf {vp9Crf}");
  1262. }
  1263. else
  1264. {
  1265. param += FormattableString.Invariant($" -crf {defaultVp9Crf}");
  1266. }
  1267. param += " -row-mt 1 -profile 1";
  1268. }
  1269. else if (string.Equals(videoEncoder, "mpeg4", StringComparison.OrdinalIgnoreCase))
  1270. {
  1271. param += " -mbd rd -flags +mv4+aic -trellis 2 -cmp 2 -subcmp 2 -bf 2";
  1272. }
  1273. else if (string.Equals(videoEncoder, "wmv2", StringComparison.OrdinalIgnoreCase)) // asf/wmv
  1274. {
  1275. param += " -qmin 2";
  1276. }
  1277. else if (string.Equals(videoEncoder, "msmpeg4", StringComparison.OrdinalIgnoreCase))
  1278. {
  1279. param += " -mbd 2";
  1280. }
  1281. param += GetVideoBitrateParam(state, videoEncoder);
  1282. var framerate = GetFramerateParam(state);
  1283. if (framerate.HasValue)
  1284. {
  1285. param += string.Format(CultureInfo.InvariantCulture, " -r {0}", framerate.Value.ToString(CultureInfo.InvariantCulture));
  1286. }
  1287. var targetVideoCodec = state.ActualOutputVideoCodec;
  1288. if (string.Equals(targetVideoCodec, "h265", StringComparison.OrdinalIgnoreCase)
  1289. || string.Equals(targetVideoCodec, "hevc", StringComparison.OrdinalIgnoreCase))
  1290. {
  1291. targetVideoCodec = "hevc";
  1292. }
  1293. var profile = state.GetRequestedProfiles(targetVideoCodec).FirstOrDefault() ?? string.Empty;
  1294. profile = Regex.Replace(profile, @"\s+", string.Empty);
  1295. // We only transcode to HEVC 8-bit for now, force Main Profile.
  1296. if (profile.Contains("main10", StringComparison.OrdinalIgnoreCase)
  1297. || profile.Contains("mainstill", StringComparison.OrdinalIgnoreCase))
  1298. {
  1299. profile = "main";
  1300. }
  1301. // Extended Profile is not supported by any known h264 encoders, force Main Profile.
  1302. if (profile.Contains("extended", StringComparison.OrdinalIgnoreCase))
  1303. {
  1304. profile = "main";
  1305. }
  1306. // Only libx264 support encoding H264 High 10 Profile, otherwise force High Profile.
  1307. if (!string.Equals(videoEncoder, "libx264", StringComparison.OrdinalIgnoreCase)
  1308. && profile.Contains("high10", StringComparison.OrdinalIgnoreCase))
  1309. {
  1310. profile = "high";
  1311. }
  1312. // h264_vaapi does not support Baseline profile, force Constrained Baseline in this case,
  1313. // which is compatible (and ugly).
  1314. if (string.Equals(videoEncoder, "h264_vaapi", StringComparison.OrdinalIgnoreCase)
  1315. && profile.Contains("baseline", StringComparison.OrdinalIgnoreCase))
  1316. {
  1317. profile = "constrained_baseline";
  1318. }
  1319. // libx264, h264_qsv and h264_nvenc does not support Constrained Baseline profile, force Baseline in this case.
  1320. if ((string.Equals(videoEncoder, "libx264", StringComparison.OrdinalIgnoreCase)
  1321. || string.Equals(videoEncoder, "h264_qsv", StringComparison.OrdinalIgnoreCase)
  1322. || string.Equals(videoEncoder, "h264_nvenc", StringComparison.OrdinalIgnoreCase))
  1323. && profile.Contains("baseline", StringComparison.OrdinalIgnoreCase))
  1324. {
  1325. profile = "baseline";
  1326. }
  1327. // libx264, h264_qsv, h264_nvenc and h264_vaapi does not support Constrained High profile, force High in this case.
  1328. if ((string.Equals(videoEncoder, "libx264", StringComparison.OrdinalIgnoreCase)
  1329. || string.Equals(videoEncoder, "h264_qsv", StringComparison.OrdinalIgnoreCase)
  1330. || string.Equals(videoEncoder, "h264_nvenc", StringComparison.OrdinalIgnoreCase)
  1331. || string.Equals(videoEncoder, "h264_vaapi", StringComparison.OrdinalIgnoreCase))
  1332. && profile.Contains("high", StringComparison.OrdinalIgnoreCase))
  1333. {
  1334. profile = "high";
  1335. }
  1336. if (string.Equals(videoEncoder, "h264_amf", StringComparison.OrdinalIgnoreCase)
  1337. && profile.Contains("baseline", StringComparison.OrdinalIgnoreCase))
  1338. {
  1339. profile = "constrained_baseline";
  1340. }
  1341. if (string.Equals(videoEncoder, "h264_amf", StringComparison.OrdinalIgnoreCase)
  1342. && profile.Contains("constrainedhigh", StringComparison.OrdinalIgnoreCase))
  1343. {
  1344. profile = "constrained_high";
  1345. }
  1346. if (!string.IsNullOrEmpty(profile))
  1347. {
  1348. if (!string.Equals(videoEncoder, "h264_omx", StringComparison.OrdinalIgnoreCase)
  1349. && !string.Equals(videoEncoder, "h264_v4l2m2m", StringComparison.OrdinalIgnoreCase))
  1350. {
  1351. // not supported by h264_omx
  1352. param += " -profile:v:0 " + profile;
  1353. }
  1354. }
  1355. var level = state.GetRequestedLevel(targetVideoCodec);
  1356. if (!string.IsNullOrEmpty(level))
  1357. {
  1358. level = NormalizeTranscodingLevel(state, level);
  1359. // libx264, QSV, AMF can adjust the given level to match the output.
  1360. if (string.Equals(videoEncoder, "h264_qsv", StringComparison.OrdinalIgnoreCase)
  1361. || string.Equals(videoEncoder, "libx264", StringComparison.OrdinalIgnoreCase))
  1362. {
  1363. param += " -level " + level;
  1364. }
  1365. else if (string.Equals(videoEncoder, "hevc_qsv", StringComparison.OrdinalIgnoreCase))
  1366. {
  1367. // hevc_qsv use -level 51 instead of -level 153.
  1368. if (double.TryParse(level, NumberStyles.Any, CultureInfo.InvariantCulture, out double hevcLevel))
  1369. {
  1370. param += " -level " + (hevcLevel / 3);
  1371. }
  1372. }
  1373. else if (string.Equals(videoEncoder, "h264_amf", StringComparison.OrdinalIgnoreCase)
  1374. || string.Equals(videoEncoder, "hevc_amf", StringComparison.OrdinalIgnoreCase))
  1375. {
  1376. param += " -level " + level;
  1377. }
  1378. else if (string.Equals(videoEncoder, "h264_nvenc", StringComparison.OrdinalIgnoreCase)
  1379. || string.Equals(videoEncoder, "hevc_nvenc", StringComparison.OrdinalIgnoreCase))
  1380. {
  1381. // level option may cause NVENC to fail.
  1382. // NVENC cannot adjust the given level, just throw an error.
  1383. }
  1384. else if (string.Equals(videoEncoder, "h264_vaapi", StringComparison.OrdinalIgnoreCase)
  1385. || string.Equals(videoEncoder, "hevc_vaapi", StringComparison.OrdinalIgnoreCase))
  1386. {
  1387. // level option may cause corrupted frames on AMD VAAPI.
  1388. }
  1389. else if (!string.Equals(videoEncoder, "h264_omx", StringComparison.OrdinalIgnoreCase)
  1390. || !string.Equals(videoEncoder, "libx265", StringComparison.OrdinalIgnoreCase))
  1391. {
  1392. param += " -level " + level;
  1393. }
  1394. }
  1395. if (string.Equals(videoEncoder, "libx264", StringComparison.OrdinalIgnoreCase))
  1396. {
  1397. param += " -x264opts:0 subme=0:me_range=4:rc_lookahead=10:me=dia:no_chroma_me:8x8dct=0:partitions=none";
  1398. }
  1399. if (string.Equals(videoEncoder, "libx265", StringComparison.OrdinalIgnoreCase))
  1400. {
  1401. // libx265 only accept level option in -x265-params.
  1402. // level option may cause libx265 to fail.
  1403. // libx265 cannot adjust the given level, just throw an error.
  1404. // TODO: set fine tuned params.
  1405. param += " -x265-params:0 no-info=1";
  1406. }
  1407. return param;
  1408. }
  1409. public bool CanStreamCopyVideo(EncodingJobInfo state, MediaStream videoStream)
  1410. {
  1411. var request = state.BaseRequest;
  1412. if (!request.AllowVideoStreamCopy)
  1413. {
  1414. return false;
  1415. }
  1416. if (videoStream.IsInterlaced
  1417. && state.DeInterlace(videoStream.Codec, false))
  1418. {
  1419. return false;
  1420. }
  1421. if (videoStream.IsAnamorphic ?? false)
  1422. {
  1423. if (request.RequireNonAnamorphic)
  1424. {
  1425. return false;
  1426. }
  1427. }
  1428. // Can't stream copy if we're burning in subtitles
  1429. if (request.SubtitleStreamIndex.HasValue
  1430. && state.SubtitleDeliveryMethod == SubtitleDeliveryMethod.Encode)
  1431. {
  1432. return false;
  1433. }
  1434. if (string.Equals("h264", videoStream.Codec, StringComparison.OrdinalIgnoreCase)
  1435. && videoStream.IsAVC.HasValue
  1436. && !videoStream.IsAVC.Value
  1437. && request.RequireAvc)
  1438. {
  1439. return false;
  1440. }
  1441. // Source and target codecs must match
  1442. if (string.IsNullOrEmpty(videoStream.Codec)
  1443. || !state.SupportedVideoCodecs.Contains(videoStream.Codec, StringComparer.OrdinalIgnoreCase))
  1444. {
  1445. return false;
  1446. }
  1447. var requestedProfiles = state.GetRequestedProfiles(videoStream.Codec);
  1448. // If client is requesting a specific video profile, it must match the source
  1449. if (requestedProfiles.Length > 0)
  1450. {
  1451. if (string.IsNullOrEmpty(videoStream.Profile))
  1452. {
  1453. // return false;
  1454. }
  1455. var requestedProfile = requestedProfiles[0];
  1456. // strip spaces because they may be stripped out on the query string as well
  1457. if (!string.IsNullOrEmpty(videoStream.Profile)
  1458. && !requestedProfiles.Contains(videoStream.Profile.Replace(" ", string.Empty, StringComparison.Ordinal), StringComparer.OrdinalIgnoreCase))
  1459. {
  1460. var currentScore = GetVideoProfileScore(videoStream.Codec, videoStream.Profile);
  1461. var requestedScore = GetVideoProfileScore(videoStream.Codec, requestedProfile);
  1462. if (currentScore == -1 || currentScore > requestedScore)
  1463. {
  1464. return false;
  1465. }
  1466. }
  1467. }
  1468. // Video width must fall within requested value
  1469. if (request.MaxWidth.HasValue
  1470. && (!videoStream.Width.HasValue || videoStream.Width.Value > request.MaxWidth.Value))
  1471. {
  1472. return false;
  1473. }
  1474. // Video height must fall within requested value
  1475. if (request.MaxHeight.HasValue
  1476. && (!videoStream.Height.HasValue || videoStream.Height.Value > request.MaxHeight.Value))
  1477. {
  1478. return false;
  1479. }
  1480. // Video framerate must fall within requested value
  1481. var requestedFramerate = request.MaxFramerate ?? request.Framerate;
  1482. if (requestedFramerate.HasValue)
  1483. {
  1484. var videoFrameRate = videoStream.AverageFrameRate ?? videoStream.RealFrameRate;
  1485. if (!videoFrameRate.HasValue || videoFrameRate.Value > requestedFramerate.Value)
  1486. {
  1487. return false;
  1488. }
  1489. }
  1490. // Video bitrate must fall within requested value
  1491. if (request.VideoBitRate.HasValue
  1492. && (!videoStream.BitRate.HasValue || videoStream.BitRate.Value > request.VideoBitRate.Value))
  1493. {
  1494. return false;
  1495. }
  1496. var maxBitDepth = state.GetRequestedVideoBitDepth(videoStream.Codec);
  1497. if (maxBitDepth.HasValue)
  1498. {
  1499. if (videoStream.BitDepth.HasValue && videoStream.BitDepth.Value > maxBitDepth.Value)
  1500. {
  1501. return false;
  1502. }
  1503. }
  1504. var maxRefFrames = state.GetRequestedMaxRefFrames(videoStream.Codec);
  1505. if (maxRefFrames.HasValue
  1506. && videoStream.RefFrames.HasValue && videoStream.RefFrames.Value > maxRefFrames.Value)
  1507. {
  1508. return false;
  1509. }
  1510. // If a specific level was requested, the source must match or be less than
  1511. var level = state.GetRequestedLevel(videoStream.Codec);
  1512. if (!string.IsNullOrEmpty(level)
  1513. && double.TryParse(level, NumberStyles.Any, CultureInfo.InvariantCulture, out var requestLevel))
  1514. {
  1515. if (!videoStream.Level.HasValue)
  1516. {
  1517. // return false;
  1518. }
  1519. if (videoStream.Level.HasValue && videoStream.Level.Value > requestLevel)
  1520. {
  1521. return false;
  1522. }
  1523. }
  1524. if (string.Equals(state.InputContainer, "avi", StringComparison.OrdinalIgnoreCase)
  1525. && string.Equals(videoStream.Codec, "h264", StringComparison.OrdinalIgnoreCase)
  1526. && !(videoStream.IsAVC ?? false))
  1527. {
  1528. // see Coach S01E01 - Kelly and the Professor(0).avi
  1529. return false;
  1530. }
  1531. return request.EnableAutoStreamCopy;
  1532. }
  1533. public bool CanStreamCopyAudio(EncodingJobInfo state, MediaStream audioStream, IEnumerable<string> supportedAudioCodecs)
  1534. {
  1535. var request = state.BaseRequest;
  1536. if (!request.AllowAudioStreamCopy)
  1537. {
  1538. return false;
  1539. }
  1540. var maxBitDepth = state.GetRequestedAudioBitDepth(audioStream.Codec);
  1541. if (maxBitDepth.HasValue
  1542. && audioStream.BitDepth.HasValue
  1543. && audioStream.BitDepth.Value > maxBitDepth.Value)
  1544. {
  1545. return false;
  1546. }
  1547. // Source and target codecs must match
  1548. if (string.IsNullOrEmpty(audioStream.Codec)
  1549. || !supportedAudioCodecs.Contains(audioStream.Codec, StringComparer.OrdinalIgnoreCase))
  1550. {
  1551. return false;
  1552. }
  1553. // Channels must fall within requested value
  1554. var channels = state.GetRequestedAudioChannels(audioStream.Codec);
  1555. if (channels.HasValue)
  1556. {
  1557. if (!audioStream.Channels.HasValue || audioStream.Channels.Value <= 0)
  1558. {
  1559. return false;
  1560. }
  1561. if (audioStream.Channels.Value > channels.Value)
  1562. {
  1563. return false;
  1564. }
  1565. }
  1566. // Sample rate must fall within requested value
  1567. if (request.AudioSampleRate.HasValue)
  1568. {
  1569. if (!audioStream.SampleRate.HasValue || audioStream.SampleRate.Value <= 0)
  1570. {
  1571. return false;
  1572. }
  1573. if (audioStream.SampleRate.Value > request.AudioSampleRate.Value)
  1574. {
  1575. return false;
  1576. }
  1577. }
  1578. // Video bitrate must fall within requested value
  1579. if (request.AudioBitRate.HasValue)
  1580. {
  1581. if (!audioStream.BitRate.HasValue || audioStream.BitRate.Value <= 0)
  1582. {
  1583. return false;
  1584. }
  1585. if (audioStream.BitRate.Value > request.AudioBitRate.Value)
  1586. {
  1587. return false;
  1588. }
  1589. }
  1590. return request.EnableAutoStreamCopy;
  1591. }
  1592. public int? GetVideoBitrateParamValue(BaseEncodingJobOptions request, MediaStream videoStream, string outputVideoCodec)
  1593. {
  1594. var bitrate = request.VideoBitRate;
  1595. if (videoStream != null)
  1596. {
  1597. var isUpscaling = request.Height.HasValue
  1598. && videoStream.Height.HasValue
  1599. && request.Height.Value > videoStream.Height.Value
  1600. && request.Width.HasValue
  1601. && videoStream.Width.HasValue
  1602. && request.Width.Value > videoStream.Width.Value;
  1603. // Don't allow bitrate increases unless upscaling
  1604. if (!isUpscaling && bitrate.HasValue && videoStream.BitRate.HasValue)
  1605. {
  1606. bitrate = GetMinBitrate(videoStream.BitRate.Value, bitrate.Value);
  1607. }
  1608. if (bitrate.HasValue)
  1609. {
  1610. var inputVideoCodec = videoStream.Codec;
  1611. bitrate = ScaleBitrate(bitrate.Value, inputVideoCodec, outputVideoCodec);
  1612. // If a max bitrate was requested, don't let the scaled bitrate exceed it
  1613. if (request.VideoBitRate.HasValue)
  1614. {
  1615. bitrate = Math.Min(bitrate.Value, request.VideoBitRate.Value);
  1616. }
  1617. }
  1618. }
  1619. return bitrate;
  1620. }
  1621. private int GetMinBitrate(int sourceBitrate, int requestedBitrate)
  1622. {
  1623. // these values were chosen from testing to improve low bitrate streams
  1624. if (sourceBitrate <= 2000000)
  1625. {
  1626. sourceBitrate = Convert.ToInt32(sourceBitrate * 2.5);
  1627. }
  1628. else if (sourceBitrate <= 3000000)
  1629. {
  1630. sourceBitrate *= 2;
  1631. }
  1632. var bitrate = Math.Min(sourceBitrate, requestedBitrate);
  1633. return bitrate;
  1634. }
  1635. private static double GetVideoBitrateScaleFactor(string codec)
  1636. {
  1637. if (string.Equals(codec, "h265", StringComparison.OrdinalIgnoreCase)
  1638. || string.Equals(codec, "hevc", StringComparison.OrdinalIgnoreCase)
  1639. || string.Equals(codec, "vp9", StringComparison.OrdinalIgnoreCase)
  1640. || string.Equals(codec, "av1", StringComparison.OrdinalIgnoreCase))
  1641. {
  1642. return .6;
  1643. }
  1644. return 1;
  1645. }
  1646. private static int ScaleBitrate(int bitrate, string inputVideoCodec, string outputVideoCodec)
  1647. {
  1648. var inputScaleFactor = GetVideoBitrateScaleFactor(inputVideoCodec);
  1649. var outputScaleFactor = GetVideoBitrateScaleFactor(outputVideoCodec);
  1650. var scaleFactor = outputScaleFactor / inputScaleFactor;
  1651. if (bitrate <= 500000)
  1652. {
  1653. scaleFactor = Math.Max(scaleFactor, 4);
  1654. }
  1655. else if (bitrate <= 1000000)
  1656. {
  1657. scaleFactor = Math.Max(scaleFactor, 3);
  1658. }
  1659. else if (bitrate <= 2000000)
  1660. {
  1661. scaleFactor = Math.Max(scaleFactor, 2.5);
  1662. }
  1663. else if (bitrate <= 3000000)
  1664. {
  1665. scaleFactor = Math.Max(scaleFactor, 2);
  1666. }
  1667. return Convert.ToInt32(scaleFactor * bitrate);
  1668. }
  1669. public int? GetAudioBitrateParam(BaseEncodingJobOptions request, MediaStream audioStream)
  1670. {
  1671. return GetAudioBitrateParam(request.AudioBitRate, request.AudioCodec, audioStream);
  1672. }
  1673. public int? GetAudioBitrateParam(int? audioBitRate, string audioCodec, MediaStream audioStream)
  1674. {
  1675. if (audioStream == null)
  1676. {
  1677. return null;
  1678. }
  1679. if (audioBitRate.HasValue && string.IsNullOrEmpty(audioCodec))
  1680. {
  1681. return Math.Min(384000, audioBitRate.Value);
  1682. }
  1683. if (audioBitRate.HasValue && !string.IsNullOrEmpty(audioCodec))
  1684. {
  1685. if (string.Equals(audioCodec, "aac", StringComparison.OrdinalIgnoreCase)
  1686. || string.Equals(audioCodec, "mp3", StringComparison.OrdinalIgnoreCase)
  1687. || string.Equals(audioCodec, "ac3", StringComparison.OrdinalIgnoreCase)
  1688. || string.Equals(audioCodec, "eac3", StringComparison.OrdinalIgnoreCase))
  1689. {
  1690. if ((audioStream.Channels ?? 0) >= 6)
  1691. {
  1692. return Math.Min(640000, audioBitRate.Value);
  1693. }
  1694. return Math.Min(384000, audioBitRate.Value);
  1695. }
  1696. if (string.Equals(audioCodec, "flac", StringComparison.OrdinalIgnoreCase)
  1697. || string.Equals(audioCodec, "alac", StringComparison.OrdinalIgnoreCase))
  1698. {
  1699. if ((audioStream.Channels ?? 0) >= 6)
  1700. {
  1701. return Math.Min(3584000, audioBitRate.Value);
  1702. }
  1703. return Math.Min(1536000, audioBitRate.Value);
  1704. }
  1705. }
  1706. // Empty bitrate area is not allow on iOS
  1707. // Default audio bitrate to 128K if it is not being requested
  1708. // https://ffmpeg.org/ffmpeg-codecs.html#toc-Codec-Options
  1709. return 128000;
  1710. }
  1711. public string GetAudioFilterParam(EncodingJobInfo state, EncodingOptions encodingOptions)
  1712. {
  1713. var channels = state.OutputAudioChannels;
  1714. var filters = new List<string>();
  1715. // Boost volume to 200% when downsampling from 6ch to 2ch
  1716. if (channels.HasValue
  1717. && channels.Value <= 2
  1718. && state.AudioStream != null
  1719. && state.AudioStream.Channels.HasValue
  1720. && state.AudioStream.Channels.Value > 5
  1721. && !encodingOptions.DownMixAudioBoost.Equals(1))
  1722. {
  1723. filters.Add("volume=" + encodingOptions.DownMixAudioBoost.ToString(CultureInfo.InvariantCulture));
  1724. }
  1725. var isCopyingTimestamps = state.CopyTimestamps || state.TranscodingType != TranscodingJobType.Progressive;
  1726. if (state.SubtitleStream != null && state.SubtitleStream.IsTextSubtitleStream && state.SubtitleDeliveryMethod == SubtitleDeliveryMethod.Encode && !isCopyingTimestamps)
  1727. {
  1728. var seconds = TimeSpan.FromTicks(state.StartTimeTicks ?? 0).TotalSeconds;
  1729. filters.Add(
  1730. string.Format(
  1731. CultureInfo.InvariantCulture,
  1732. "asetpts=PTS-{0}/TB",
  1733. Math.Round(seconds)));
  1734. }
  1735. if (filters.Count > 0)
  1736. {
  1737. return " -af \"" + string.Join(',', filters) + "\"";
  1738. }
  1739. return string.Empty;
  1740. }
  1741. /// <summary>
  1742. /// Gets the number of audio channels to specify on the command line.
  1743. /// </summary>
  1744. /// <param name="state">The state.</param>
  1745. /// <param name="audioStream">The audio stream.</param>
  1746. /// <param name="outputAudioCodec">The output audio codec.</param>
  1747. /// <returns>System.Nullable{System.Int32}.</returns>
  1748. public int? GetNumAudioChannelsParam(EncodingJobInfo state, MediaStream audioStream, string outputAudioCodec)
  1749. {
  1750. if (audioStream == null)
  1751. {
  1752. return null;
  1753. }
  1754. var request = state.BaseRequest;
  1755. var inputChannels = audioStream.Channels;
  1756. if (inputChannels <= 0)
  1757. {
  1758. inputChannels = null;
  1759. }
  1760. var codec = outputAudioCodec ?? string.Empty;
  1761. int? transcoderChannelLimit;
  1762. if (codec.IndexOf("wma", StringComparison.OrdinalIgnoreCase) != -1)
  1763. {
  1764. // wmav2 currently only supports two channel output
  1765. transcoderChannelLimit = 2;
  1766. }
  1767. else if (codec.IndexOf("mp3", StringComparison.OrdinalIgnoreCase) != -1)
  1768. {
  1769. // libmp3lame currently only supports two channel output
  1770. transcoderChannelLimit = 2;
  1771. }
  1772. else if (codec.IndexOf("aac", StringComparison.OrdinalIgnoreCase) != -1)
  1773. {
  1774. // aac is able to handle 8ch(7.1 layout)
  1775. transcoderChannelLimit = 8;
  1776. }
  1777. else
  1778. {
  1779. // If we don't have any media info then limit it to 6 to prevent encoding errors due to asking for too many channels
  1780. transcoderChannelLimit = 6;
  1781. }
  1782. var isTranscodingAudio = !IsCopyCodec(codec);
  1783. int? resultChannels = state.GetRequestedAudioChannels(codec);
  1784. if (isTranscodingAudio)
  1785. {
  1786. resultChannels = GetMinValue(request.TranscodingMaxAudioChannels, resultChannels);
  1787. }
  1788. if (inputChannels.HasValue)
  1789. {
  1790. resultChannels = resultChannels.HasValue
  1791. ? Math.Min(resultChannels.Value, inputChannels.Value)
  1792. : inputChannels.Value;
  1793. }
  1794. if (isTranscodingAudio && transcoderChannelLimit.HasValue)
  1795. {
  1796. resultChannels = resultChannels.HasValue
  1797. ? Math.Min(resultChannels.Value, transcoderChannelLimit.Value)
  1798. : transcoderChannelLimit.Value;
  1799. }
  1800. // Avoid transcoding to audio channels other than 1ch, 2ch, 6ch (5.1 layout) and 8ch (7.1 layout).
  1801. // https://developer.apple.com/documentation/http_live_streaming/hls_authoring_specification_for_apple_devices
  1802. if (isTranscodingAudio
  1803. && state.TranscodingType != TranscodingJobType.Progressive
  1804. && resultChannels.HasValue
  1805. && ((resultChannels.Value > 2 && resultChannels.Value < 6) || resultChannels.Value == 7))
  1806. {
  1807. resultChannels = 2;
  1808. }
  1809. return resultChannels;
  1810. }
  1811. private int? GetMinValue(int? val1, int? val2)
  1812. {
  1813. if (!val1.HasValue)
  1814. {
  1815. return val2;
  1816. }
  1817. if (!val2.HasValue)
  1818. {
  1819. return val1;
  1820. }
  1821. return Math.Min(val1.Value, val2.Value);
  1822. }
  1823. /// <summary>
  1824. /// Enforces the resolution limit.
  1825. /// </summary>
  1826. /// <param name="state">The state.</param>
  1827. public void EnforceResolutionLimit(EncodingJobInfo state)
  1828. {
  1829. var videoRequest = state.BaseRequest;
  1830. // Switch the incoming params to be ceilings rather than fixed values
  1831. videoRequest.MaxWidth = videoRequest.MaxWidth ?? videoRequest.Width;
  1832. videoRequest.MaxHeight = videoRequest.MaxHeight ?? videoRequest.Height;
  1833. videoRequest.Width = null;
  1834. videoRequest.Height = null;
  1835. }
  1836. /// <summary>
  1837. /// Gets the fast seek command line parameter.
  1838. /// </summary>
  1839. /// <param name="state">The state.</param>
  1840. /// <param name="options">The options.</param>
  1841. /// <returns>System.String.</returns>
  1842. /// <value>The fast seek command line parameter.</value>
  1843. public string GetFastSeekCommandLineParameter(EncodingJobInfo state, EncodingOptions options)
  1844. {
  1845. var time = state.BaseRequest.StartTimeTicks ?? 0;
  1846. var seekParam = string.Empty;
  1847. if (time > 0)
  1848. {
  1849. seekParam += string.Format(CultureInfo.InvariantCulture, "-ss {0}", _mediaEncoder.GetTimeParameter(time));
  1850. if (state.IsVideoRequest)
  1851. {
  1852. var outputVideoCodec = GetVideoEncoder(state, options);
  1853. // Important: If this is ever re-enabled, make sure not to use it with wtv because it breaks seeking
  1854. if (!string.Equals(state.InputContainer, "wtv", StringComparison.OrdinalIgnoreCase)
  1855. && state.TranscodingType != TranscodingJobType.Progressive
  1856. && !state.EnableBreakOnNonKeyFrames(outputVideoCodec)
  1857. && (state.BaseRequest.StartTimeTicks ?? 0) > 0)
  1858. {
  1859. seekParam += " -noaccurate_seek";
  1860. }
  1861. }
  1862. }
  1863. return seekParam;
  1864. }
  1865. /// <summary>
  1866. /// Gets the map args.
  1867. /// </summary>
  1868. /// <param name="state">The state.</param>
  1869. /// <returns>System.String.</returns>
  1870. public string GetMapArgs(EncodingJobInfo state)
  1871. {
  1872. // If we don't have known media info
  1873. // If input is video, use -sn to drop subtitles
  1874. // Otherwise just return empty
  1875. if (state.VideoStream == null && state.AudioStream == null)
  1876. {
  1877. return state.IsInputVideo ? "-sn" : string.Empty;
  1878. }
  1879. // We have media info, but we don't know the stream indexes
  1880. if (state.VideoStream != null && state.VideoStream.Index == -1)
  1881. {
  1882. return "-sn";
  1883. }
  1884. // We have media info, but we don't know the stream indexes
  1885. if (state.AudioStream != null && state.AudioStream.Index == -1)
  1886. {
  1887. return state.IsInputVideo ? "-sn" : string.Empty;
  1888. }
  1889. var args = string.Empty;
  1890. if (state.VideoStream != null)
  1891. {
  1892. args += string.Format(
  1893. CultureInfo.InvariantCulture,
  1894. "-map 0:{0}",
  1895. state.VideoStream.Index);
  1896. }
  1897. else
  1898. {
  1899. // No known video stream
  1900. args += "-vn";
  1901. }
  1902. if (state.AudioStream != null)
  1903. {
  1904. args += string.Format(
  1905. CultureInfo.InvariantCulture,
  1906. " -map 0:{0}",
  1907. state.AudioStream.Index);
  1908. }
  1909. else
  1910. {
  1911. args += " -map -0:a";
  1912. }
  1913. var subtitleMethod = state.SubtitleDeliveryMethod;
  1914. if (state.SubtitleStream == null || subtitleMethod == SubtitleDeliveryMethod.Hls)
  1915. {
  1916. args += " -map -0:s";
  1917. }
  1918. else if (subtitleMethod == SubtitleDeliveryMethod.Embed)
  1919. {
  1920. args += string.Format(
  1921. CultureInfo.InvariantCulture,
  1922. " -map 0:{0}",
  1923. state.SubtitleStream.Index);
  1924. }
  1925. else if (state.SubtitleStream.IsExternal && !state.SubtitleStream.IsTextSubtitleStream)
  1926. {
  1927. args += " -map 1:0 -sn";
  1928. }
  1929. return args;
  1930. }
  1931. /// <summary>
  1932. /// Determines which stream will be used for playback.
  1933. /// </summary>
  1934. /// <param name="allStream">All stream.</param>
  1935. /// <param name="desiredIndex">Index of the desired.</param>
  1936. /// <param name="type">The type.</param>
  1937. /// <param name="returnFirstIfNoIndex">if set to <c>true</c> [return first if no index].</param>
  1938. /// <returns>MediaStream.</returns>
  1939. public MediaStream GetMediaStream(IEnumerable<MediaStream> allStream, int? desiredIndex, MediaStreamType type, bool returnFirstIfNoIndex = true)
  1940. {
  1941. var streams = allStream.Where(s => s.Type == type).OrderBy(i => i.Index).ToList();
  1942. if (desiredIndex.HasValue)
  1943. {
  1944. var stream = streams.FirstOrDefault(s => s.Index == desiredIndex.Value);
  1945. if (stream != null)
  1946. {
  1947. return stream;
  1948. }
  1949. }
  1950. if (returnFirstIfNoIndex && type == MediaStreamType.Audio)
  1951. {
  1952. return streams.FirstOrDefault(i => i.Channels.HasValue && i.Channels.Value > 0) ??
  1953. streams.FirstOrDefault();
  1954. }
  1955. // Just return the first one
  1956. return returnFirstIfNoIndex ? streams.FirstOrDefault() : null;
  1957. }
  1958. public static (int? width, int? height) GetFixedOutputSize(
  1959. int? videoWidth,
  1960. int? videoHeight,
  1961. int? requestedWidth,
  1962. int? requestedHeight,
  1963. int? requestedMaxWidth,
  1964. int? requestedMaxHeight)
  1965. {
  1966. if (!videoWidth.HasValue && !requestedWidth.HasValue)
  1967. {
  1968. return (null, null);
  1969. }
  1970. if (!videoHeight.HasValue && !requestedHeight.HasValue)
  1971. {
  1972. return (null, null);
  1973. }
  1974. decimal inputWidth = Convert.ToDecimal(videoWidth ?? requestedWidth, CultureInfo.InvariantCulture);
  1975. decimal inputHeight = Convert.ToDecimal(videoHeight ?? requestedHeight, CultureInfo.InvariantCulture);
  1976. decimal outputWidth = requestedWidth.HasValue ? Convert.ToDecimal(requestedWidth.Value) : inputWidth;
  1977. decimal outputHeight = requestedHeight.HasValue ? Convert.ToDecimal(requestedHeight.Value) : inputHeight;
  1978. decimal maximumWidth = requestedMaxWidth.HasValue ? Convert.ToDecimal(requestedMaxWidth.Value) : outputWidth;
  1979. decimal maximumHeight = requestedMaxHeight.HasValue ? Convert.ToDecimal(requestedMaxHeight.Value) : outputHeight;
  1980. if (outputWidth > maximumWidth || outputHeight > maximumHeight)
  1981. {
  1982. var scale = Math.Min(maximumWidth / outputWidth, maximumHeight / outputHeight);
  1983. outputWidth = Math.Min(maximumWidth, Math.Truncate(outputWidth * scale));
  1984. outputHeight = Math.Min(maximumHeight, Math.Truncate(outputHeight * scale));
  1985. }
  1986. outputWidth = 2 * Math.Truncate(outputWidth / 2);
  1987. outputHeight = 2 * Math.Truncate(outputHeight / 2);
  1988. return (Convert.ToInt32(outputWidth), Convert.ToInt32(outputHeight));
  1989. }
  1990. public static string GetHwScaleFilter(
  1991. string hwScaleSuffix,
  1992. string videoFormat,
  1993. int? videoWidth,
  1994. int? videoHeight,
  1995. int? requestedWidth,
  1996. int? requestedHeight,
  1997. int? requestedMaxWidth,
  1998. int? requestedMaxHeight)
  1999. {
  2000. var (outWidth, outHeight) = GetFixedOutputSize(videoWidth, videoHeight,
  2001. requestedWidth, requestedHeight,
  2002. requestedMaxWidth, requestedMaxHeight);
  2003. var isFormatFixed = !string.IsNullOrEmpty(videoFormat);
  2004. var isSizeFixed = !videoWidth.HasValue
  2005. || outWidth.Value != videoWidth.Value
  2006. || !videoHeight.HasValue
  2007. || outHeight.Value != videoHeight.Value;
  2008. var arg1 = isSizeFixed ? ("=w=" + outWidth.Value + ":h=" + outHeight.Value) : string.Empty;
  2009. var arg2 = isFormatFixed ? ("format=" + videoFormat) : string.Empty;
  2010. if (isFormatFixed)
  2011. {
  2012. arg2 = (isSizeFixed ? ':' : '=') + arg2;
  2013. }
  2014. if (!string.IsNullOrEmpty(hwScaleSuffix) && (isSizeFixed || isFormatFixed))
  2015. {
  2016. return string.Format(
  2017. CultureInfo.InvariantCulture,
  2018. "scale_{0}{1}{2}",
  2019. hwScaleSuffix,
  2020. arg1,
  2021. arg2);
  2022. }
  2023. return string.Empty;
  2024. }
  2025. public static string GetCustomSwScaleFilter(
  2026. int? videoWidth,
  2027. int? videoHeight,
  2028. int? requestedWidth,
  2029. int? requestedHeight,
  2030. int? requestedMaxWidth,
  2031. int? requestedMaxHeight)
  2032. {
  2033. var (outWidth, outHeight) = GetFixedOutputSize(videoWidth, videoHeight,
  2034. requestedWidth, requestedHeight,
  2035. requestedMaxWidth, requestedMaxHeight);
  2036. if (outWidth.HasValue && outHeight.HasValue)
  2037. {
  2038. return string.Format(
  2039. CultureInfo.InvariantCulture,
  2040. "scale=s={0}x{1}:flags=fast_bilinear",
  2041. outWidth.Value,
  2042. outHeight.Value);
  2043. }
  2044. return string.Empty;
  2045. }
  2046. public static string GetAlphaSrcFilter(
  2047. EncodingJobInfo state,
  2048. int? videoWidth,
  2049. int? videoHeight,
  2050. int? requestedWidth,
  2051. int? requestedHeight,
  2052. int? requestedMaxWidth,
  2053. int? requestedMaxHeight,
  2054. int? framerate)
  2055. {
  2056. var reqTicks = state.BaseRequest.StartTimeTicks ?? 0;
  2057. var startTime = TimeSpan.FromTicks(reqTicks).ToString(@"hh\\\:mm\\\:ss\\\.fff", CultureInfo.InvariantCulture);
  2058. var (outWidth, outHeight) = GetFixedOutputSize(videoWidth, videoHeight,
  2059. requestedWidth, requestedHeight,
  2060. requestedMaxWidth, requestedMaxHeight);
  2061. if (outWidth.HasValue && outHeight.HasValue)
  2062. {
  2063. return string.Format(
  2064. CultureInfo.InvariantCulture,
  2065. "alphasrc=s={0}x{1}:r={2}:start='{3}'",
  2066. outWidth.Value,
  2067. outHeight.Value,
  2068. framerate ?? 10,
  2069. reqTicks > 0 ? startTime : 0);
  2070. }
  2071. return string.Empty;
  2072. }
  2073. public static List<string> GetSwScaleFilter(
  2074. EncodingJobInfo state,
  2075. EncodingOptions options,
  2076. string videoEncoder,
  2077. int? videoWidth,
  2078. int? videoHeight,
  2079. Video3DFormat? threedFormat,
  2080. int? requestedWidth,
  2081. int? requestedHeight,
  2082. int? requestedMaxWidth,
  2083. int? requestedMaxHeight)
  2084. {
  2085. var filters = new List<string>();
  2086. var isV4l2 = string.Equals(videoEncoder, "h264_v4l2m2m", StringComparison.OrdinalIgnoreCase);
  2087. var scaleVal = isV4l2 ? 64 : 2;
  2088. // If fixed dimensions were supplied
  2089. if (requestedWidth.HasValue && requestedHeight.HasValue)
  2090. {
  2091. if (isV4l2)
  2092. {
  2093. var widthParam = requestedWidth.Value.ToString(CultureInfo.InvariantCulture);
  2094. var heightParam = requestedHeight.Value.ToString(CultureInfo.InvariantCulture);
  2095. filters.Add(
  2096. string.Format(
  2097. CultureInfo.InvariantCulture,
  2098. "scale=trunc({0}/64)*64:trunc({1}/2)*2",
  2099. widthParam,
  2100. heightParam));
  2101. }
  2102. else
  2103. {
  2104. filters.Add(GetFixedSwScaleFilter(threedFormat, requestedWidth.Value, requestedHeight.Value));
  2105. }
  2106. }
  2107. // 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
  2108. else if (requestedMaxWidth.HasValue && requestedMaxHeight.HasValue)
  2109. {
  2110. var maxWidthParam = requestedMaxWidth.Value.ToString(CultureInfo.InvariantCulture);
  2111. var maxHeightParam = requestedMaxHeight.Value.ToString(CultureInfo.InvariantCulture);
  2112. filters.Add(
  2113. string.Format(
  2114. CultureInfo.InvariantCulture,
  2115. "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",
  2116. maxWidthParam,
  2117. maxHeightParam,
  2118. scaleVal));
  2119. }
  2120. // If a fixed width was requested
  2121. else if (requestedWidth.HasValue)
  2122. {
  2123. if (threedFormat.HasValue)
  2124. {
  2125. // This method can handle 0 being passed in for the requested height
  2126. filters.Add(GetFixedSwScaleFilter(threedFormat, requestedWidth.Value, 0));
  2127. }
  2128. else
  2129. {
  2130. var widthParam = requestedWidth.Value.ToString(CultureInfo.InvariantCulture);
  2131. filters.Add(
  2132. string.Format(
  2133. CultureInfo.InvariantCulture,
  2134. "scale={0}:trunc(ow/a/2)*2",
  2135. widthParam));
  2136. }
  2137. }
  2138. // If a fixed height was requested
  2139. else if (requestedHeight.HasValue)
  2140. {
  2141. var heightParam = requestedHeight.Value.ToString(CultureInfo.InvariantCulture);
  2142. filters.Add(
  2143. string.Format(
  2144. CultureInfo.InvariantCulture,
  2145. "scale=trunc(oh*a/{1})*{1}:{0}",
  2146. heightParam,
  2147. scaleVal));
  2148. }
  2149. // If a max width was requested
  2150. else if (requestedMaxWidth.HasValue)
  2151. {
  2152. var maxWidthParam = requestedMaxWidth.Value.ToString(CultureInfo.InvariantCulture);
  2153. filters.Add(
  2154. string.Format(
  2155. CultureInfo.InvariantCulture,
  2156. "scale=trunc(min(max(iw\\,ih*dar)\\,{0})/{1})*{1}:trunc(ow/dar/2)*2",
  2157. maxWidthParam,
  2158. scaleVal));
  2159. }
  2160. // If a max height was requested
  2161. else if (requestedMaxHeight.HasValue)
  2162. {
  2163. var maxHeightParam = requestedMaxHeight.Value.ToString(CultureInfo.InvariantCulture);
  2164. filters.Add(
  2165. string.Format(
  2166. CultureInfo.InvariantCulture,
  2167. "scale=trunc(oh*a/{1})*{1}:min(max(iw/dar\\,ih)\\,{0})",
  2168. maxHeightParam,
  2169. scaleVal));
  2170. }
  2171. return filters;
  2172. }
  2173. private static string GetFixedSwScaleFilter(Video3DFormat? threedFormat, int requestedWidth, int requestedHeight)
  2174. {
  2175. var widthParam = requestedWidth.ToString(CultureInfo.InvariantCulture);
  2176. var heightParam = requestedHeight.ToString(CultureInfo.InvariantCulture);
  2177. string filter = null;
  2178. if (threedFormat.HasValue)
  2179. {
  2180. switch (threedFormat.Value)
  2181. {
  2182. case Video3DFormat.HalfSideBySide:
  2183. 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";
  2184. // 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.
  2185. break;
  2186. case Video3DFormat.FullSideBySide:
  2187. 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";
  2188. // fsbs crop width in half,set the display aspect,crop out any black bars we may have made the scale width to requestedWidth.
  2189. break;
  2190. case Video3DFormat.HalfTopAndBottom:
  2191. 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";
  2192. // 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
  2193. break;
  2194. case Video3DFormat.FullTopAndBottom:
  2195. 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";
  2196. // ftab crop height in half, set the display aspect,crop out any black bars we may have made the scale width to requestedWidth
  2197. break;
  2198. default:
  2199. break;
  2200. }
  2201. }
  2202. // default
  2203. if (filter == null)
  2204. {
  2205. if (requestedHeight > 0)
  2206. {
  2207. filter = "scale=trunc({0}/2)*2:trunc({1}/2)*2";
  2208. }
  2209. else
  2210. {
  2211. filter = "scale={0}:trunc({0}/dar/2)*2";
  2212. }
  2213. }
  2214. return string.Format(CultureInfo.InvariantCulture, filter, widthParam, heightParam);
  2215. }
  2216. public static string GetSwDeinterlaceFilter(EncodingJobInfo state, EncodingOptions options)
  2217. {
  2218. var doubleRateDeint = options.DeinterlaceDoubleRate && (state.VideoStream?.AverageFrameRate ?? 60) <= 30;
  2219. if (string.Equals(options.DeinterlaceMethod, "bwdif", StringComparison.OrdinalIgnoreCase))
  2220. {
  2221. return string.Format(
  2222. CultureInfo.InvariantCulture,
  2223. "bwdif={0}:-1:0",
  2224. doubleRateDeint ? "1" : "0");
  2225. }
  2226. else
  2227. {
  2228. return string.Format(
  2229. CultureInfo.InvariantCulture,
  2230. "yadif={0}:-1:0",
  2231. doubleRateDeint ? "1" : "0");
  2232. }
  2233. }
  2234. public static string GetHwDeinterlaceFilter(EncodingJobInfo state, EncodingOptions options, string hwDeintSuffix)
  2235. {
  2236. var doubleRateDeint = options.DeinterlaceDoubleRate && (state.VideoStream?.AverageFrameRate ?? 60) <= 30;
  2237. if (hwDeintSuffix.Contains("cuda", StringComparison.OrdinalIgnoreCase))
  2238. {
  2239. return string.Format(
  2240. CultureInfo.InvariantCulture,
  2241. "yadif_cuda={0}:-1:0",
  2242. doubleRateDeint ? "1" : "0");
  2243. }
  2244. else if (hwDeintSuffix.Contains("vaapi", StringComparison.OrdinalIgnoreCase))
  2245. {
  2246. return string.Format(
  2247. CultureInfo.InvariantCulture,
  2248. "deinterlace_vaapi=rate={0}",
  2249. doubleRateDeint ? "field" : "frame");
  2250. }
  2251. else if (hwDeintSuffix.Contains("qsv", StringComparison.OrdinalIgnoreCase))
  2252. {
  2253. return "deinterlace_qsv=mode=2";
  2254. }
  2255. return string.Empty;
  2256. }
  2257. public static string GetHwTonemapFilter(EncodingOptions options, string hwTonemapSuffix, string videoFormat)
  2258. {
  2259. if (string.IsNullOrEmpty(hwTonemapSuffix))
  2260. {
  2261. return string.Empty;
  2262. }
  2263. var args = "tonemap_{0}=format={1}:p=bt709:t=bt709:m=bt709";
  2264. if (!hwTonemapSuffix.Contains("vaapi", StringComparison.OrdinalIgnoreCase))
  2265. {
  2266. args += ":tonemap={2}:peak={3}:desat={4}";
  2267. if (options.TonemappingParam != 0)
  2268. {
  2269. args += ":param={5}";
  2270. }
  2271. if (!string.Equals(options.TonemappingRange, "auto", StringComparison.OrdinalIgnoreCase))
  2272. {
  2273. args += ":range={6}";
  2274. }
  2275. }
  2276. return string.Format(
  2277. CultureInfo.InvariantCulture,
  2278. args,
  2279. hwTonemapSuffix,
  2280. videoFormat ?? "nv12",
  2281. options.TonemappingAlgorithm,
  2282. options.TonemappingPeak,
  2283. options.TonemappingDesat,
  2284. options.TonemappingParam,
  2285. options.TonemappingRange);
  2286. }
  2287. /// <summary>
  2288. /// Gets the parameter of software filter chain.
  2289. /// </summary>
  2290. /// <param name="state">Encoding state.</param>
  2291. /// <param name="options">Encoding options.</param>
  2292. /// <param name="vidEncoder">Video encoder to use.</param>
  2293. /// <returns>The tuple contains three lists: main, sub and overlay filters</returns>
  2294. public Tuple<List<string>, List<string>, List<string>> GetSwVidFilterChain(
  2295. EncodingJobInfo state,
  2296. EncodingOptions options,
  2297. string vidEncoder)
  2298. {
  2299. var inW = state.VideoStream?.Width;
  2300. var inH = state.VideoStream?.Height;
  2301. var reqW = state.BaseRequest.Width;
  2302. var reqH = state.BaseRequest.Height;
  2303. var reqMaxW = state.BaseRequest.MaxWidth;
  2304. var reqMaxH = state.BaseRequest.MaxHeight;
  2305. var threeDFormat = state.MediaSource.Video3DFormat;
  2306. var vidDecoder = GetHardwareVideoDecoder(state, options) ?? string.Empty;
  2307. var isSwDecoder = string.IsNullOrEmpty(vidDecoder);
  2308. var isVaapiEncoder = vidEncoder.Contains("vaapi", StringComparison.OrdinalIgnoreCase);
  2309. var doDeintH264 = state.DeInterlace("h264", true) || state.DeInterlace("avc", true);
  2310. var doDeintHevc = state.DeInterlace("h265", true) || state.DeInterlace("hevc", true);
  2311. var doDeintH2645 = doDeintH264 || doDeintHevc;
  2312. var hasSubs = state.SubtitleStream != null && state.SubtitleDeliveryMethod == SubtitleDeliveryMethod.Encode;
  2313. var hasTextSubs = hasSubs && state.SubtitleStream.IsTextSubtitleStream;
  2314. var hasGraphicalSubs = hasSubs && !state.SubtitleStream.IsTextSubtitleStream;
  2315. /* Make main filters for video stream */
  2316. var mainFilters = new List<string>();
  2317. mainFilters.Add(GetOverwriteColorPropertiesParam(state, false));
  2318. // INPUT sw surface(memory/copy-back from vram)
  2319. var outFormat = isSwDecoder ? "yuv420p" : "nv12";
  2320. var swScaleFilter = GetSwScaleFilter(state, options, vidEncoder, inW, inH, threeDFormat, reqW, reqH, reqMaxW, reqMaxH);
  2321. if (isVaapiEncoder)
  2322. {
  2323. outFormat = "nv12";
  2324. }
  2325. // sw scale
  2326. mainFilters.AddRange(swScaleFilter);
  2327. mainFilters.Add("format=" + outFormat);
  2328. if (doDeintH2645)
  2329. {
  2330. var deintFilter = GetSwDeinterlaceFilter(state, options);
  2331. // sw deint
  2332. mainFilters.Add(deintFilter);
  2333. }
  2334. // sw tonemap <= TODO: finsh the fast tonemap filter
  2335. // OUTPUT yuv420p/nv12 surface(memory)
  2336. /* Make sub and overlay filters for subtitle stream */
  2337. var subFilters = new List<string>();
  2338. var overlayFilters = new List<string>();
  2339. if (hasTextSubs)
  2340. {
  2341. // subtitles=f='*.ass':alpha=0
  2342. var textSubtitlesFilter = GetTextSubtitlesFilter(state, false, false);
  2343. mainFilters.Add(textSubtitlesFilter);
  2344. }
  2345. else if (hasGraphicalSubs)
  2346. {
  2347. // [0:s]scale=s=1280x720
  2348. var subSwScaleFilter = GetCustomSwScaleFilter(inW, inH, reqW, reqH, reqMaxW, reqMaxH);
  2349. subFilters.Add(subSwScaleFilter);
  2350. overlayFilters.Add("overlay=eof_action=endall:shortest=1:repeatlast=0");
  2351. }
  2352. return new Tuple<List<string>, List<string>, List<string>>(mainFilters, subFilters, overlayFilters);
  2353. }
  2354. /// <summary>
  2355. /// Gets the parameter of Nvidia NVENC filter chain.
  2356. /// </summary>
  2357. /// <param name="state">Encoding state.</param>
  2358. /// <param name="options">Encoding options.</param>
  2359. /// <param name="vidEncoder">Video encoder to use.</param>
  2360. /// <returns>The tuple contains three lists: main, sub and overlay filters</returns>
  2361. public Tuple<List<string>, List<string>, List<string>> GetNvidiaVidFilterChain(
  2362. EncodingJobInfo state,
  2363. EncodingOptions options,
  2364. string vidEncoder)
  2365. {
  2366. if (!string.Equals(options.HardwareAccelerationType, "nvenc", StringComparison.OrdinalIgnoreCase))
  2367. {
  2368. return new Tuple<List<string>, List<string>, List<string>>(null, null, null);
  2369. }
  2370. var vidDecoder = GetHardwareVideoDecoder(state, options) ?? string.Empty;
  2371. var isSwDecoder = string.IsNullOrEmpty(vidDecoder);
  2372. var isSwEncoder = !vidEncoder.Contains("nvenc", StringComparison.OrdinalIgnoreCase);
  2373. // legacy cuvid(resize/deint/sw) pipeline(copy-back)
  2374. if ((isSwDecoder && isSwEncoder)
  2375. || !IsCudaFullSupported()
  2376. || !options.EnableEnhancedNvdecDecoder
  2377. || !_mediaEncoder.SupportsFilter("alphasrc"))
  2378. {
  2379. return GetSwVidFilterChain(state, options, vidEncoder);
  2380. }
  2381. // prefered nvdec + cuda filters + nvenc pipeline
  2382. return GetNvidiaVidFiltersPrefered(state, options, vidDecoder, vidEncoder);
  2383. }
  2384. public Tuple<List<string>, List<string>, List<string>> GetNvidiaVidFiltersPrefered(
  2385. EncodingJobInfo state,
  2386. EncodingOptions options,
  2387. string vidDecoder,
  2388. string vidEncoder)
  2389. {
  2390. var inW = state.VideoStream?.Width;
  2391. var inH = state.VideoStream?.Height;
  2392. var reqW = state.BaseRequest.Width;
  2393. var reqH = state.BaseRequest.Height;
  2394. var reqMaxW = state.BaseRequest.MaxWidth;
  2395. var reqMaxH = state.BaseRequest.MaxHeight;
  2396. var threeDFormat = state.MediaSource.Video3DFormat;
  2397. var isNvdecDecoder = vidDecoder.Contains("cuda", StringComparison.OrdinalIgnoreCase);
  2398. var isNvencEncoder = vidEncoder.Contains("nvenc", StringComparison.OrdinalIgnoreCase);
  2399. var isSwDecoder = string.IsNullOrEmpty(vidDecoder);
  2400. var isSwEncoder = !isNvencEncoder;
  2401. var isCuInCuOut = isNvdecDecoder && isNvencEncoder;
  2402. var doubleRateDeint = options.DeinterlaceDoubleRate && (state.VideoStream?.AverageFrameRate ?? 60) <= 30;
  2403. var doDeintH264 = state.DeInterlace("h264", true) || state.DeInterlace("avc", true);
  2404. var doDeintHevc = state.DeInterlace("h265", true) || state.DeInterlace("hevc", true);
  2405. var doDeintH2645 = doDeintH264 || doDeintHevc;
  2406. var doCuTonemap = IsHwTonemapAvailable(state, options);
  2407. var hasSubs = state.SubtitleStream != null && state.SubtitleDeliveryMethod == SubtitleDeliveryMethod.Encode;
  2408. var hasTextSubs = hasSubs && state.SubtitleStream.IsTextSubtitleStream;
  2409. var hasGraphicalSubs = hasSubs && !state.SubtitleStream.IsTextSubtitleStream;
  2410. var hasAssSubs = hasSubs
  2411. && (string.Equals(state.SubtitleStream.Codec, "ass", StringComparison.OrdinalIgnoreCase)
  2412. || string.Equals(state.SubtitleStream.Codec, "ssa", StringComparison.OrdinalIgnoreCase));
  2413. /* Make main filters for video stream */
  2414. var mainFilters = new List<string>();
  2415. mainFilters.Add(GetOverwriteColorPropertiesParam(state, doCuTonemap));
  2416. if (isSwDecoder)
  2417. {
  2418. // INPUT sw surface(memory)
  2419. var outFormat = doCuTonemap ? "yuv420p10" : "yuv420p";
  2420. var swScaleFilter = GetSwScaleFilter(state, options, vidEncoder, inW, inH, threeDFormat, reqW, reqH, reqMaxW, reqMaxH);
  2421. // sw scale
  2422. mainFilters.AddRange(swScaleFilter);
  2423. mainFilters.Add("format=" + outFormat);
  2424. // sw deint
  2425. if (doDeintH2645)
  2426. {
  2427. var swDeintFilter = GetSwDeinterlaceFilter(state, options);
  2428. mainFilters.Add(swDeintFilter);
  2429. }
  2430. // sw => hw
  2431. if (doCuTonemap)
  2432. {
  2433. mainFilters.Add("hwupload");
  2434. }
  2435. }
  2436. if (isNvdecDecoder)
  2437. {
  2438. // INPUT cuda surface(vram)
  2439. var outFormat = doCuTonemap ? string.Empty : "yuv420p";
  2440. var hwScaleFilter = GetHwScaleFilter("cuda", outFormat, inW, inH, reqW, reqH, reqMaxW, reqMaxH);
  2441. // hw scale
  2442. mainFilters.Add(hwScaleFilter);
  2443. // hw deint
  2444. if (doDeintH2645)
  2445. {
  2446. var deintFilter = GetHwDeinterlaceFilter(state, options, "cuda");
  2447. mainFilters.Add(deintFilter);
  2448. }
  2449. }
  2450. // hw tonemap
  2451. if (doCuTonemap)
  2452. {
  2453. var tonemapFilter = GetHwTonemapFilter(options, "cuda", "yuv420p");
  2454. mainFilters.Add(tonemapFilter);
  2455. }
  2456. var memoryOutput = false;
  2457. var isUploadForOclTonemap = isSwDecoder && doCuTonemap;
  2458. if ((isNvdecDecoder && isSwEncoder) || isUploadForOclTonemap)
  2459. {
  2460. memoryOutput = true;
  2461. // OUTPUT yuv420p surface(memory)
  2462. mainFilters.Add("hwdownload");
  2463. mainFilters.Add("format=yuv420p");
  2464. }
  2465. // OUTPUT yuv420p surface(memory)
  2466. if (isSwDecoder && isNvencEncoder)
  2467. {
  2468. memoryOutput = true;
  2469. }
  2470. if (memoryOutput)
  2471. {
  2472. // text subtitles
  2473. if (hasTextSubs)
  2474. {
  2475. var textSubtitlesFilter = GetTextSubtitlesFilter(state, false, false);
  2476. mainFilters.Add(textSubtitlesFilter);
  2477. }
  2478. }
  2479. // OUTPUT cuda(yuv420p) surface(vram)
  2480. /* Make sub and overlay filters for subtitle stream */
  2481. var subFilters = new List<string>();
  2482. var overlayFilters = new List<string>();
  2483. if (isCuInCuOut)
  2484. {
  2485. if (hasSubs)
  2486. {
  2487. if (hasGraphicalSubs)
  2488. {
  2489. // scale=s=1280x720,format=yuva420p,hwupload
  2490. var subSwScaleFilter = GetCustomSwScaleFilter(inW, inH, reqW, reqH, reqMaxW, reqMaxH);
  2491. subFilters.Add(subSwScaleFilter);
  2492. subFilters.Add("format=yuva420p");
  2493. }
  2494. else if (hasTextSubs)
  2495. {
  2496. // alphasrc=s=1280x720:r=10:start=0,format=yuva420p,subtitles,hwupload
  2497. var alphaSrcFilter = GetAlphaSrcFilter(state, inW, inH, reqW, reqH, reqMaxW, reqMaxH, hasAssSubs ? 10 : 5);
  2498. var subTextSubtitlesFilter = GetTextSubtitlesFilter(state, true, true);
  2499. subFilters.Add(alphaSrcFilter);
  2500. subFilters.Add("format=yuva420p");
  2501. subFilters.Add(subTextSubtitlesFilter);
  2502. }
  2503. subFilters.Add("hwupload");
  2504. overlayFilters.Add("overlay_cuda=eof_action=endall:shortest=1:repeatlast=0");
  2505. }
  2506. }
  2507. else
  2508. {
  2509. if (hasGraphicalSubs)
  2510. {
  2511. var subSwScaleFilter = GetCustomSwScaleFilter(inW, inH, reqW, reqH, reqMaxW, reqMaxH);
  2512. subFilters.Add(subSwScaleFilter);
  2513. overlayFilters.Add("overlay=eof_action=endall:shortest=1:repeatlast=0");
  2514. }
  2515. }
  2516. return new Tuple<List<string>, List<string>, List<string>>(mainFilters, subFilters, overlayFilters);
  2517. }
  2518. /// <summary>
  2519. /// Gets the parameter of AMD AMF filter chain.
  2520. /// </summary>
  2521. /// <param name="state">Encoding state.</param>
  2522. /// <param name="options">Encoding options.</param>
  2523. /// <param name="vidEncoder">Video encoder to use.</param>
  2524. /// <returns>The tuple contains three lists: main, sub and overlay filters</returns>
  2525. public Tuple<List<string>, List<string>, List<string>> GetAmdVidFilterChain(
  2526. EncodingJobInfo state,
  2527. EncodingOptions options,
  2528. string vidEncoder)
  2529. {
  2530. if (!string.Equals(options.HardwareAccelerationType, "amf", StringComparison.OrdinalIgnoreCase))
  2531. {
  2532. return new Tuple<List<string>, List<string>, List<string>>(null, null, null);
  2533. }
  2534. var isWindows = OperatingSystem.IsWindows();
  2535. var vidDecoder = GetHardwareVideoDecoder(state, options) ?? string.Empty;
  2536. var isSwDecoder = string.IsNullOrEmpty(vidDecoder);
  2537. var isSwEncoder = !vidEncoder.Contains("amf", StringComparison.OrdinalIgnoreCase);
  2538. var isAmfDx11OclSupported = isWindows && _mediaEncoder.SupportsHwaccel("d3d11va") && IsOpenclFullSupported();
  2539. // legacy d3d11va pipeline(copy-back)
  2540. if ((isSwDecoder && isSwEncoder)
  2541. || !isAmfDx11OclSupported
  2542. || !_mediaEncoder.SupportsFilter("alphasrc"))
  2543. {
  2544. return GetSwVidFilterChain(state, options, vidEncoder);
  2545. }
  2546. // prefered d3d11va + opencl filters + amf pipeline
  2547. return GetAmdDx11VidFiltersPrefered(state, options, vidDecoder, vidEncoder);
  2548. }
  2549. public Tuple<List<string>, List<string>, List<string>> GetAmdDx11VidFiltersPrefered(
  2550. EncodingJobInfo state,
  2551. EncodingOptions options,
  2552. string vidDecoder,
  2553. string vidEncoder)
  2554. {
  2555. var inW = state.VideoStream?.Width;
  2556. var inH = state.VideoStream?.Height;
  2557. var reqW = state.BaseRequest.Width;
  2558. var reqH = state.BaseRequest.Height;
  2559. var reqMaxW = state.BaseRequest.MaxWidth;
  2560. var reqMaxH = state.BaseRequest.MaxHeight;
  2561. var threeDFormat = state.MediaSource.Video3DFormat;
  2562. var isD3d11vaDecoder = vidDecoder.Contains("d3d11va", StringComparison.OrdinalIgnoreCase);
  2563. var isAmfEncoder = vidEncoder.Contains("amf", StringComparison.OrdinalIgnoreCase);
  2564. var isSwDecoder = string.IsNullOrEmpty(vidDecoder);
  2565. var isSwEncoder = !isAmfEncoder;
  2566. var isDxInDxOut = isD3d11vaDecoder && isAmfEncoder;
  2567. var doDeintH264 = state.DeInterlace("h264", true) || state.DeInterlace("avc", true);
  2568. var doDeintHevc = state.DeInterlace("h265", true) || state.DeInterlace("hevc", true);
  2569. var doDeintH2645 = doDeintH264 || doDeintHevc;
  2570. var doOclTonemap = IsHwTonemapAvailable(state, options);
  2571. var hasSubs = state.SubtitleStream != null && state.SubtitleDeliveryMethod == SubtitleDeliveryMethod.Encode;
  2572. var hasTextSubs = hasSubs && state.SubtitleStream.IsTextSubtitleStream;
  2573. var hasGraphicalSubs = hasSubs && !state.SubtitleStream.IsTextSubtitleStream;
  2574. var hasAssSubs = hasSubs
  2575. && (string.Equals(state.SubtitleStream.Codec, "ass", StringComparison.OrdinalIgnoreCase)
  2576. || string.Equals(state.SubtitleStream.Codec, "ssa", StringComparison.OrdinalIgnoreCase));
  2577. /* Make main filters for video stream */
  2578. var mainFilters = new List<string>();
  2579. mainFilters.Add(GetOverwriteColorPropertiesParam(state, doOclTonemap));
  2580. if (isSwDecoder)
  2581. {
  2582. // INPUT sw surface(memory)
  2583. var outFormat = doOclTonemap ? "yuv420p10" : "yuv420p";
  2584. var swScaleFilter = GetSwScaleFilter(state, options, vidEncoder, inW, inH, threeDFormat, reqW, reqH, reqMaxW, reqMaxH);
  2585. // sw scale
  2586. mainFilters.AddRange(swScaleFilter);
  2587. mainFilters.Add("format=" + outFormat);
  2588. // sw deint
  2589. if (doDeintH2645)
  2590. {
  2591. var swDeintFilter = GetSwDeinterlaceFilter(state, options);
  2592. mainFilters.Add(swDeintFilter);
  2593. }
  2594. // keep video at memory except ocl tonemap,
  2595. // since the overhead caused by hwupload >>> using sw filter.
  2596. // sw => hw
  2597. if (doOclTonemap)
  2598. {
  2599. mainFilters.Add("hwupload");
  2600. }
  2601. }
  2602. if (isD3d11vaDecoder)
  2603. {
  2604. // INPUT d3d11 surface(vram)
  2605. // map from d3d11va to opencl via d3d11-opencl interop.
  2606. mainFilters.Add("hwmap=derive_device=opencl");
  2607. var outFormat = doOclTonemap ? string.Empty : "nv12";
  2608. var hwScaleFilter = GetHwScaleFilter("opencl", outFormat, inW, inH, reqW, reqH, reqMaxW, reqMaxH);
  2609. // hw scale
  2610. mainFilters.Add(hwScaleFilter);
  2611. // hw deint <= TODO: finsh the 'yadif_opencl' filter
  2612. }
  2613. // hw tonemap
  2614. if (doOclTonemap)
  2615. {
  2616. var tonemapFilter = GetHwTonemapFilter(options, "opencl", "nv12");
  2617. mainFilters.Add(tonemapFilter);
  2618. }
  2619. var memoryOutput = false;
  2620. var isUploadForOclTonemap = isSwDecoder && doOclTonemap;
  2621. if ((isD3d11vaDecoder && isSwEncoder) || isUploadForOclTonemap)
  2622. {
  2623. memoryOutput = true;
  2624. // OUTPUT nv12 surface(memory)
  2625. // prefer hwmap to hwdownload on opencl.
  2626. var hwTransferFilter = hasGraphicalSubs ? "hwdownload" : "hwmap";
  2627. mainFilters.Add(hwTransferFilter);
  2628. mainFilters.Add("format=nv12");
  2629. }
  2630. // OUTPUT yuv420p surface
  2631. if (isSwDecoder && isAmfEncoder)
  2632. {
  2633. memoryOutput = true;
  2634. }
  2635. if (memoryOutput)
  2636. {
  2637. // text subtitles
  2638. if (hasTextSubs)
  2639. {
  2640. var textSubtitlesFilter = GetTextSubtitlesFilter(state, false, false);
  2641. mainFilters.Add(textSubtitlesFilter);
  2642. }
  2643. }
  2644. if (isDxInDxOut && !hasSubs)
  2645. {
  2646. // OUTPUT d3d11(nv12) surface(vram)
  2647. // reverse-mapping via d3d11-opencl interop.
  2648. mainFilters.Add("hwmap=derive_device=d3d11va:reverse=1");
  2649. mainFilters.Add("format=d3d11");
  2650. }
  2651. /* Make sub and overlay filters for subtitle stream */
  2652. var subFilters = new List<string>();
  2653. var overlayFilters = new List<string>();
  2654. if (isDxInDxOut)
  2655. {
  2656. if (hasSubs)
  2657. {
  2658. if (hasGraphicalSubs)
  2659. {
  2660. // scale=s=1280x720,format=yuva420p,hwupload
  2661. var subSwScaleFilter = GetCustomSwScaleFilter(inW, inH, reqW, reqH, reqMaxW, reqMaxH);
  2662. subFilters.Add(subSwScaleFilter);
  2663. subFilters.Add("format=yuva420p");
  2664. }
  2665. else if (hasTextSubs)
  2666. {
  2667. // alphasrc=s=1280x720:r=10:start=0,format=yuva420p,subtitles,hwupload
  2668. var alphaSrcFilter = GetAlphaSrcFilter(state, inW, inH, reqW, reqH, reqMaxW, reqMaxH, hasAssSubs ? 10 : 5);
  2669. var subTextSubtitlesFilter = GetTextSubtitlesFilter(state, true, true);
  2670. subFilters.Add(alphaSrcFilter);
  2671. subFilters.Add("format=yuva420p");
  2672. subFilters.Add(subTextSubtitlesFilter);
  2673. }
  2674. subFilters.Add("hwupload");
  2675. overlayFilters.Add("overlay_opencl=eof_action=endall:shortest=1:repeatlast=0");
  2676. overlayFilters.Add("hwmap=derive_device=d3d11va:reverse=1");
  2677. overlayFilters.Add("format=d3d11");
  2678. }
  2679. }
  2680. else if (memoryOutput)
  2681. {
  2682. if (hasGraphicalSubs)
  2683. {
  2684. var subSwScaleFilter = GetCustomSwScaleFilter(inW, inH, reqW, reqH, reqMaxW, reqMaxH);
  2685. subFilters.Add(subSwScaleFilter);
  2686. overlayFilters.Add("overlay=eof_action=endall:shortest=1:repeatlast=0");
  2687. }
  2688. }
  2689. return new Tuple<List<string>, List<string>, List<string>>(mainFilters, subFilters, overlayFilters);
  2690. }
  2691. /// <summary>
  2692. /// Gets the parameter of Intel QSV filter chain.
  2693. /// </summary>
  2694. /// <param name="state">Encoding state.</param>
  2695. /// <param name="options">Encoding options.</param>
  2696. /// <param name="vidEncoder">Video encoder to use.</param>
  2697. /// <returns>The tuple contains three lists: main, sub and overlay filters</returns>
  2698. public Tuple<List<string>, List<string>, List<string>> GetIntelVidFilterChain(
  2699. EncodingJobInfo state,
  2700. EncodingOptions options,
  2701. string vidEncoder)
  2702. {
  2703. if (!string.Equals(options.HardwareAccelerationType, "qsv", StringComparison.OrdinalIgnoreCase))
  2704. {
  2705. return new Tuple<List<string>, List<string>, List<string>>(null, null, null);
  2706. }
  2707. var isWindows = OperatingSystem.IsWindows();
  2708. var isLinux = OperatingSystem.IsLinux();
  2709. var vidDecoder = GetHardwareVideoDecoder(state, options) ?? string.Empty;
  2710. var isSwDecoder = string.IsNullOrEmpty(vidDecoder);
  2711. var isSwEncoder = !vidEncoder.Contains("qsv", StringComparison.OrdinalIgnoreCase);
  2712. var isQsvOclSupported = _mediaEncoder.SupportsHwaccel("qsv") && IsOpenclFullSupported();
  2713. var isIntelDx11OclSupported = isWindows
  2714. && _mediaEncoder.SupportsHwaccel("d3d11va")
  2715. && isQsvOclSupported;
  2716. var isIntelVaapiOclSupported = isLinux
  2717. && IsVaapiSupported(state)
  2718. && isQsvOclSupported;
  2719. // legacy qsv pipeline(copy-back)
  2720. if ((isSwDecoder && isSwEncoder)
  2721. || (!isIntelVaapiOclSupported && !isIntelDx11OclSupported)
  2722. || !_mediaEncoder.SupportsFilter("alphasrc"))
  2723. {
  2724. return GetSwVidFilterChain(state, options, vidEncoder);
  2725. }
  2726. // prefered qsv(vaapi) + opencl filters pipeline
  2727. if (isIntelVaapiOclSupported)
  2728. {
  2729. return GetIntelQsvVaapiVidFiltersPrefered(state, options, vidDecoder, vidEncoder);
  2730. }
  2731. // prefered qsv(d3d11) + opencl filters pipeline
  2732. if (isIntelDx11OclSupported)
  2733. {
  2734. return GetIntelQsvDx11VidFiltersPrefered(state, options, vidDecoder, vidEncoder);
  2735. }
  2736. return new Tuple<List<string>, List<string>, List<string>>(null, null, null);
  2737. }
  2738. public Tuple<List<string>, List<string>, List<string>> GetIntelQsvDx11VidFiltersPrefered(
  2739. EncodingJobInfo state,
  2740. EncodingOptions options,
  2741. string vidDecoder,
  2742. string vidEncoder)
  2743. {
  2744. var inW = state.VideoStream?.Width;
  2745. var inH = state.VideoStream?.Height;
  2746. var reqW = state.BaseRequest.Width;
  2747. var reqH = state.BaseRequest.Height;
  2748. var reqMaxW = state.BaseRequest.MaxWidth;
  2749. var reqMaxH = state.BaseRequest.MaxHeight;
  2750. var threeDFormat = state.MediaSource.Video3DFormat;
  2751. var isD3d11vaDecoder = vidDecoder.Contains("d3d11va", StringComparison.OrdinalIgnoreCase);
  2752. var isQsvDecoder = vidDecoder.Contains("qsv", StringComparison.OrdinalIgnoreCase);
  2753. var isQsvEncoder = vidEncoder.Contains("qsv", StringComparison.OrdinalIgnoreCase);
  2754. var isHwDecoder = isD3d11vaDecoder || isQsvDecoder;
  2755. var isSwDecoder = string.IsNullOrEmpty(vidDecoder);
  2756. var isSwEncoder = !isQsvEncoder;
  2757. var isQsvInQsvOut = isHwDecoder && isQsvEncoder;
  2758. var doDeintH264 = state.DeInterlace("h264", true) || state.DeInterlace("avc", true);
  2759. var doDeintHevc = state.DeInterlace("h265", true) || state.DeInterlace("hevc", true);
  2760. var doDeintH2645 = doDeintH264 || doDeintHevc;
  2761. var doOclTonemap = IsHwTonemapAvailable(state, options);
  2762. var hasSubs = state.SubtitleStream != null && state.SubtitleDeliveryMethod == SubtitleDeliveryMethod.Encode;
  2763. var hasTextSubs = hasSubs && state.SubtitleStream.IsTextSubtitleStream;
  2764. var hasGraphicalSubs = hasSubs && !state.SubtitleStream.IsTextSubtitleStream;
  2765. var hasAssSubs = hasSubs
  2766. && (string.Equals(state.SubtitleStream.Codec, "ass", StringComparison.OrdinalIgnoreCase)
  2767. || string.Equals(state.SubtitleStream.Codec, "ssa", StringComparison.OrdinalIgnoreCase));
  2768. /* Make main filters for video stream */
  2769. var mainFilters = new List<string>();
  2770. mainFilters.Add(GetOverwriteColorPropertiesParam(state, doOclTonemap));
  2771. if (isSwDecoder)
  2772. {
  2773. // INPUT sw surface(memory)
  2774. var outFormat = doOclTonemap ? "yuv420p10" : "yuv420p";
  2775. var swScaleFilter = GetSwScaleFilter(state, options, vidEncoder, inW, inH, threeDFormat, reqW, reqH, reqMaxW, reqMaxH);
  2776. // sw scale
  2777. mainFilters.AddRange(swScaleFilter);
  2778. mainFilters.Add("format=" + outFormat);
  2779. // sw deint
  2780. if (doDeintH2645)
  2781. {
  2782. var swDeintFilter = GetSwDeinterlaceFilter(state, options);
  2783. mainFilters.Add(swDeintFilter);
  2784. }
  2785. // keep video at memory except ocl tonemap,
  2786. // since the overhead caused by hwupload >>> using sw filter.
  2787. // sw => hw
  2788. if (doOclTonemap)
  2789. {
  2790. mainFilters.Add("hwupload");
  2791. }
  2792. }
  2793. else if (isD3d11vaDecoder || isQsvDecoder)
  2794. {
  2795. var outFormat = doOclTonemap ? string.Empty : "nv12";
  2796. var hwScaleFilter = GetHwScaleFilter("qsv", outFormat, inW, inH, reqW, reqH, reqMaxW, reqMaxH);
  2797. if (isD3d11vaDecoder)
  2798. {
  2799. if (!string.IsNullOrEmpty(hwScaleFilter) || doDeintH2645)
  2800. {
  2801. // INPUT d3d11 surface(vram)
  2802. // map from d3d11va to qsv.
  2803. mainFilters.Add("hwmap=derive_device=qsv");
  2804. }
  2805. }
  2806. // hw scale
  2807. mainFilters.Add(hwScaleFilter);
  2808. // hw deint
  2809. if (doDeintH2645)
  2810. {
  2811. var deintFilter = GetHwDeinterlaceFilter(state, options, "qsv");
  2812. mainFilters.Add(deintFilter);
  2813. }
  2814. }
  2815. if (doOclTonemap && isHwDecoder)
  2816. {
  2817. // map from qsv to opencl via qsv(d3d11)-opencl interop.
  2818. mainFilters.Add("hwmap=derive_device=opencl");
  2819. }
  2820. // hw tonemap
  2821. if (doOclTonemap)
  2822. {
  2823. var tonemapFilter = GetHwTonemapFilter(options, "opencl", "nv12");
  2824. mainFilters.Add(tonemapFilter);
  2825. }
  2826. var memoryOutput = false;
  2827. var isUploadForOclTonemap = isSwDecoder && doOclTonemap;
  2828. var isHwmapUsable = isSwEncoder && doOclTonemap;
  2829. if ((isHwDecoder && isSwEncoder) || isUploadForOclTonemap)
  2830. {
  2831. memoryOutput = true;
  2832. // OUTPUT nv12 surface(memory)
  2833. // prefer hwmap to hwdownload on opencl.
  2834. // qsv hwmap is not fully implemented for the time being.
  2835. mainFilters.Add(isHwmapUsable ? "hwmap" : "hwdownload");
  2836. mainFilters.Add("format=nv12");
  2837. }
  2838. // OUTPUT nv12 surface(memory)
  2839. if (isSwDecoder && isQsvEncoder)
  2840. {
  2841. memoryOutput = true;
  2842. }
  2843. if (memoryOutput)
  2844. {
  2845. // text subtitles
  2846. if (hasTextSubs)
  2847. {
  2848. var textSubtitlesFilter = GetTextSubtitlesFilter(state, false, false);
  2849. mainFilters.Add(textSubtitlesFilter);
  2850. }
  2851. }
  2852. if (isQsvInQsvOut && doOclTonemap)
  2853. {
  2854. // OUTPUT qsv(nv12) surface(vram)
  2855. // reverse-mapping via qsv(d3d11)-opencl interop.
  2856. mainFilters.Add("hwmap=derive_device=qsv:reverse=1:extra_hw_frames=16");
  2857. mainFilters.Add("format=qsv");
  2858. }
  2859. /* Make sub and overlay filters for subtitle stream */
  2860. var subFilters = new List<string>();
  2861. var overlayFilters = new List<string>();
  2862. if (isQsvInQsvOut)
  2863. {
  2864. if (hasSubs)
  2865. {
  2866. if (hasGraphicalSubs)
  2867. {
  2868. // scale,format=bgra,hwupload
  2869. // overlay_qsv can handle overlay scaling,
  2870. // add a dummy scale filter to pair with -canvas_size.
  2871. subFilters.Add("scale=flags=fast_bilinear");
  2872. subFilters.Add("format=bgra");
  2873. }
  2874. else if (hasTextSubs)
  2875. {
  2876. // alphasrc=s=1280x720:r=10:start=0,format=bgra,subtitles,hwupload
  2877. var alphaSrcFilter = GetAlphaSrcFilter(state, inW, inH, reqW, reqH, reqMaxW, 1080, hasAssSubs ? 10 : 5);
  2878. var subTextSubtitlesFilter = GetTextSubtitlesFilter(state, true, true);
  2879. subFilters.Add(alphaSrcFilter);
  2880. subFilters.Add("format=bgra");
  2881. subFilters.Add(subTextSubtitlesFilter);
  2882. }
  2883. // qsv requires a fixed pool size.
  2884. subFilters.Add("hwupload=extra_hw_frames=32");
  2885. var (overlayW, overlayH) = GetFixedOutputSize(inW, inH, reqW, reqH, reqMaxW, reqMaxH);
  2886. var overlaySize = (overlayW.HasValue && overlayH.HasValue)
  2887. ? (":w=" + overlayW.Value + ":h=" + overlayH.Value)
  2888. : string.Empty;
  2889. var overlayQsvFilter = string.Format(
  2890. CultureInfo.InvariantCulture,
  2891. "overlay_qsv=eof_action=endall:shortest=1:repeatlast=0{0}",
  2892. overlaySize);
  2893. overlayFilters.Add(overlayQsvFilter);
  2894. }
  2895. }
  2896. else if (memoryOutput)
  2897. {
  2898. if (hasGraphicalSubs)
  2899. {
  2900. var subSwScaleFilter = GetCustomSwScaleFilter(inW, inH, reqW, reqH, reqMaxW, reqMaxH);
  2901. subFilters.Add(subSwScaleFilter);
  2902. overlayFilters.Add("overlay=eof_action=endall:shortest=1:repeatlast=0");
  2903. }
  2904. }
  2905. return new Tuple<List<string>, List<string>, List<string>>(mainFilters, subFilters, overlayFilters);
  2906. }
  2907. public Tuple<List<string>, List<string>, List<string>> GetIntelQsvVaapiVidFiltersPrefered(
  2908. EncodingJobInfo state,
  2909. EncodingOptions options,
  2910. string vidDecoder,
  2911. string vidEncoder)
  2912. {
  2913. var inW = state.VideoStream?.Width;
  2914. var inH = state.VideoStream?.Height;
  2915. var reqW = state.BaseRequest.Width;
  2916. var reqH = state.BaseRequest.Height;
  2917. var reqMaxW = state.BaseRequest.MaxWidth;
  2918. var reqMaxH = state.BaseRequest.MaxHeight;
  2919. var threeDFormat = state.MediaSource.Video3DFormat;
  2920. var isVaapiDecoder = vidDecoder.Contains("vaapi", StringComparison.OrdinalIgnoreCase);
  2921. var isQsvDecoder = vidDecoder.Contains("qsv", StringComparison.OrdinalIgnoreCase);
  2922. var isQsvEncoder = vidEncoder.Contains("qsv", StringComparison.OrdinalIgnoreCase);
  2923. var isHwDecoder = isVaapiDecoder || isQsvDecoder;
  2924. var isSwDecoder = string.IsNullOrEmpty(vidDecoder);
  2925. var isSwEncoder = !isQsvEncoder;
  2926. var isQsvInQsvOut = isHwDecoder && isQsvEncoder;
  2927. var doDeintH264 = state.DeInterlace("h264", true) || state.DeInterlace("avc", true);
  2928. var doDeintHevc = state.DeInterlace("h265", true) || state.DeInterlace("hevc", true);
  2929. var doVaVppTonemap = IsVaapiVppTonemapAvailable(state, options);
  2930. var doOclTonemap = !doVaVppTonemap && IsHwTonemapAvailable(state, options);
  2931. var doTonemap = doVaVppTonemap || doOclTonemap;
  2932. var doDeintH2645 = doDeintH264 || doDeintHevc;
  2933. var hasSubs = state.SubtitleStream != null && state.SubtitleDeliveryMethod == SubtitleDeliveryMethod.Encode;
  2934. var hasTextSubs = hasSubs && state.SubtitleStream.IsTextSubtitleStream;
  2935. var hasGraphicalSubs = hasSubs && !state.SubtitleStream.IsTextSubtitleStream;
  2936. var hasAssSubs = hasSubs
  2937. && (string.Equals(state.SubtitleStream.Codec, "ass", StringComparison.OrdinalIgnoreCase)
  2938. || string.Equals(state.SubtitleStream.Codec, "ssa", StringComparison.OrdinalIgnoreCase));
  2939. /* Make main filters for video stream */
  2940. var mainFilters = new List<string>();
  2941. mainFilters.Add(GetOverwriteColorPropertiesParam(state, doTonemap));
  2942. if (isSwDecoder)
  2943. {
  2944. // INPUT sw surface(memory)
  2945. var outFormat = doOclTonemap ? "yuv420p10" : "yuv420p";
  2946. var swScaleFilter = GetSwScaleFilter(state, options, vidEncoder, inW, inH, threeDFormat, reqW, reqH, reqMaxW, reqMaxH);
  2947. // sw scale
  2948. mainFilters.AddRange(swScaleFilter);
  2949. mainFilters.Add("format=" + outFormat);
  2950. // sw deint
  2951. if (doDeintH2645)
  2952. {
  2953. var swDeintFilter = GetSwDeinterlaceFilter(state, options);
  2954. mainFilters.Add(swDeintFilter);
  2955. }
  2956. // keep video at memory except ocl tonemap,
  2957. // since the overhead caused by hwupload >>> using sw filter.
  2958. // sw => hw
  2959. if (doOclTonemap)
  2960. {
  2961. mainFilters.Add("hwupload");
  2962. }
  2963. }
  2964. else if (isVaapiDecoder || isQsvDecoder)
  2965. {
  2966. // INPUT vaapi/qsv surface(vram)
  2967. var outFormat = doTonemap ? string.Empty : "nv12";
  2968. var hwScaleFilter = GetHwScaleFilter(isVaapiDecoder ? "vaapi" : "qsv", outFormat, inW, inH, reqW, reqH, reqMaxW, reqMaxH);
  2969. // hw scale
  2970. mainFilters.Add(hwScaleFilter);
  2971. }
  2972. // hw deint
  2973. if (doDeintH2645 && isHwDecoder)
  2974. {
  2975. var deintFilter = string.Empty;
  2976. if (isVaapiDecoder)
  2977. {
  2978. deintFilter = GetHwDeinterlaceFilter(state, options, "vaapi");
  2979. }
  2980. else if (isQsvDecoder)
  2981. {
  2982. deintFilter = GetHwDeinterlaceFilter(state, options, "qsv");
  2983. }
  2984. mainFilters.Add(deintFilter);
  2985. }
  2986. // vaapi vpp tonemap
  2987. if (doVaVppTonemap && isHwDecoder)
  2988. {
  2989. if (isQsvDecoder)
  2990. {
  2991. // map from qsv to vaapi.
  2992. mainFilters.Add("hwmap=derive_device=vaapi");
  2993. }
  2994. var tonemapFilter = GetHwTonemapFilter(options, "vaapi", "nv12");
  2995. mainFilters.Add(tonemapFilter);
  2996. if (isQsvDecoder)
  2997. {
  2998. // map from vaapi to qsv.
  2999. mainFilters.Add("hwmap=derive_device=qsv");
  3000. }
  3001. }
  3002. if (doOclTonemap && isHwDecoder)
  3003. {
  3004. // map from qsv to opencl via qsv(vaapi)-opencl interop.
  3005. mainFilters.Add("hwmap=derive_device=opencl");
  3006. }
  3007. // ocl tonemap
  3008. if (doOclTonemap)
  3009. {
  3010. var tonemapFilter = GetHwTonemapFilter(options, "opencl", "nv12");
  3011. mainFilters.Add(tonemapFilter);
  3012. }
  3013. var memoryOutput = false;
  3014. var isUploadForOclTonemap = isSwDecoder && doOclTonemap;
  3015. var isHwmapUsable = isSwEncoder && (doOclTonemap || isVaapiDecoder);
  3016. if ((isHwDecoder && isSwEncoder) || isUploadForOclTonemap)
  3017. {
  3018. memoryOutput = true;
  3019. // OUTPUT nv12 surface(memory)
  3020. // prefer hwmap to hwdownload on opencl/vaapi.
  3021. // qsv hwmap is not fully implemented for the time being.
  3022. mainFilters.Add(isHwmapUsable ? "hwmap" : "hwdownload");
  3023. mainFilters.Add("format=nv12");
  3024. }
  3025. // OUTPUT nv12 surface(memory)
  3026. if (isSwDecoder && isQsvEncoder)
  3027. {
  3028. memoryOutput = true;
  3029. }
  3030. if (memoryOutput)
  3031. {
  3032. // text subtitles
  3033. if (hasTextSubs)
  3034. {
  3035. var textSubtitlesFilter = GetTextSubtitlesFilter(state, false, false);
  3036. mainFilters.Add(textSubtitlesFilter);
  3037. }
  3038. }
  3039. if (isQsvInQsvOut)
  3040. {
  3041. if (doOclTonemap)
  3042. {
  3043. // OUTPUT qsv(nv12) surface(vram)
  3044. // reverse-mapping via qsv(vaapi)-opencl interop.
  3045. mainFilters.Add("hwmap=derive_device=qsv:reverse=1:extra_hw_frames=16");
  3046. mainFilters.Add("format=qsv");
  3047. }
  3048. else if (isVaapiDecoder)
  3049. {
  3050. mainFilters.Add("hwmap=derive_device=qsv");
  3051. mainFilters.Add("format=qsv");
  3052. }
  3053. }
  3054. /* Make sub and overlay filters for subtitle stream */
  3055. var subFilters = new List<string>();
  3056. var overlayFilters = new List<string>();
  3057. if (isQsvInQsvOut)
  3058. {
  3059. if (hasSubs)
  3060. {
  3061. if (hasGraphicalSubs)
  3062. {
  3063. subFilters.Add("scale=flags=fast_bilinear");
  3064. subFilters.Add("format=bgra");
  3065. }
  3066. else if (hasTextSubs)
  3067. {
  3068. var alphaSrcFilter = GetAlphaSrcFilter(state, inW, inH, reqW, reqH, reqMaxW, 1080, hasAssSubs ? 10 : 5);
  3069. var subTextSubtitlesFilter = GetTextSubtitlesFilter(state, true, true);
  3070. subFilters.Add(alphaSrcFilter);
  3071. subFilters.Add("format=bgra");
  3072. subFilters.Add(subTextSubtitlesFilter);
  3073. }
  3074. // qsv requires a fixed pool size.
  3075. subFilters.Add("hwupload=extra_hw_frames=32");
  3076. var (overlayW, overlayH) = GetFixedOutputSize(inW, inH, reqW, reqH, reqMaxW, reqMaxH);
  3077. var overlaySize = (overlayW.HasValue && overlayH.HasValue)
  3078. ? (":w=" + overlayW.Value + ":h=" + overlayH.Value)
  3079. : string.Empty;
  3080. var overlayQsvFilter = string.Format(
  3081. CultureInfo.InvariantCulture,
  3082. "overlay_qsv=eof_action=endall:shortest=1:repeatlast=0{0}",
  3083. overlaySize);
  3084. overlayFilters.Add(overlayQsvFilter);
  3085. }
  3086. }
  3087. else if (memoryOutput)
  3088. {
  3089. if (hasGraphicalSubs)
  3090. {
  3091. var subSwScaleFilter = GetCustomSwScaleFilter(inW, inH, reqW, reqH, reqMaxW, reqMaxH);
  3092. subFilters.Add(subSwScaleFilter);
  3093. overlayFilters.Add("overlay=eof_action=pass:shortest=1:repeatlast=0");
  3094. }
  3095. }
  3096. return new Tuple<List<string>, List<string>, List<string>>(mainFilters, subFilters, overlayFilters);
  3097. }
  3098. /// <summary>
  3099. /// Gets the parameter of Intel/AMD VAAPI filter chain.
  3100. /// </summary>
  3101. /// <param name="state">Encoding state.</param>
  3102. /// <param name="options">Encoding options.</param>
  3103. /// <param name="vidEncoder">Video encoder to use.</param>
  3104. /// <returns>The tuple contains three lists: main, sub and overlay filters</returns>
  3105. public Tuple<List<string>, List<string>, List<string>> GetVaapiVidFilterChain(
  3106. EncodingJobInfo state,
  3107. EncodingOptions options,
  3108. string vidEncoder)
  3109. {
  3110. if (!string.Equals(options.HardwareAccelerationType, "vaapi", StringComparison.OrdinalIgnoreCase))
  3111. {
  3112. return new Tuple<List<string>, List<string>, List<string>>(null, null, null);
  3113. }
  3114. var isLinux = OperatingSystem.IsLinux();
  3115. var vidDecoder = GetHardwareVideoDecoder(state, options) ?? string.Empty;
  3116. var isSwDecoder = string.IsNullOrEmpty(vidDecoder);
  3117. var isSwEncoder = !vidEncoder.Contains("vaapi", StringComparison.OrdinalIgnoreCase);
  3118. var isVaapiOclSupported = isLinux && IsVaapiSupported(state) && IsVaapiFullSupported() && IsOpenclFullSupported();
  3119. // legacy vaapi pipeline(copy-back)
  3120. if ((isSwDecoder && isSwEncoder)
  3121. || !isVaapiOclSupported
  3122. || !_mediaEncoder.SupportsFilter("alphasrc"))
  3123. {
  3124. var swFilterChain = GetSwVidFilterChain(state, options, vidEncoder);
  3125. if (!isSwEncoder)
  3126. {
  3127. var newfilters = new List<string>();
  3128. var noOverlay = swFilterChain.Item3.Count == 0;
  3129. newfilters.AddRange(noOverlay ? swFilterChain.Item1 : swFilterChain.Item3);
  3130. newfilters.Add("hwupload");
  3131. var mainFilters = noOverlay ? newfilters : swFilterChain.Item1;
  3132. var overlayFilters = noOverlay ? swFilterChain.Item3 : newfilters;
  3133. return new Tuple<List<string>, List<string>, List<string>>(mainFilters, swFilterChain.Item2, overlayFilters);
  3134. }
  3135. return swFilterChain;
  3136. }
  3137. // prefered vaapi + opencl filters pipeline
  3138. if (_mediaEncoder.IsVaapiDeviceInteliHD())
  3139. {
  3140. // Intel iHD path, with extra vpp tonemap and overlay support.
  3141. return GetVaapiFullVidFiltersPrefered(state, options, vidDecoder, vidEncoder);
  3142. }
  3143. // Intel i965 and Amd radeonsi/r600 path, only featuring scale and deinterlace support.
  3144. return GetVaapiLimitedVidFiltersPrefered(state, options, vidDecoder, vidEncoder);
  3145. }
  3146. public Tuple<List<string>, List<string>, List<string>> GetVaapiFullVidFiltersPrefered(
  3147. EncodingJobInfo state,
  3148. EncodingOptions options,
  3149. string vidDecoder,
  3150. string vidEncoder)
  3151. {
  3152. var inW = state.VideoStream?.Width;
  3153. var inH = state.VideoStream?.Height;
  3154. var reqW = state.BaseRequest.Width;
  3155. var reqH = state.BaseRequest.Height;
  3156. var reqMaxW = state.BaseRequest.MaxWidth;
  3157. var reqMaxH = state.BaseRequest.MaxHeight;
  3158. var threeDFormat = state.MediaSource.Video3DFormat;
  3159. var isVaapiDecoder = vidDecoder.Contains("vaapi", StringComparison.OrdinalIgnoreCase);
  3160. var isVaapiEncoder = vidEncoder.Contains("vaapi", StringComparison.OrdinalIgnoreCase);
  3161. var isSwDecoder = string.IsNullOrEmpty(vidDecoder);
  3162. var isSwEncoder = !isVaapiEncoder;
  3163. var isVaInVaOut = isVaapiDecoder && isVaapiEncoder;
  3164. var doDeintH264 = state.DeInterlace("h264", true) || state.DeInterlace("avc", true);
  3165. var doDeintHevc = state.DeInterlace("h265", true) || state.DeInterlace("hevc", true);
  3166. var doVaVppTonemap = isVaapiDecoder && IsVaapiVppTonemapAvailable(state, options);
  3167. var doOclTonemap = !doVaVppTonemap && IsHwTonemapAvailable(state, options);
  3168. var doTonemap = doVaVppTonemap || doOclTonemap;
  3169. var doDeintH2645 = doDeintH264 || doDeintHevc;
  3170. var hasSubs = state.SubtitleStream != null && state.SubtitleDeliveryMethod == SubtitleDeliveryMethod.Encode;
  3171. var hasTextSubs = hasSubs && state.SubtitleStream.IsTextSubtitleStream;
  3172. var hasGraphicalSubs = hasSubs && !state.SubtitleStream.IsTextSubtitleStream;
  3173. var hasAssSubs = hasSubs
  3174. && (string.Equals(state.SubtitleStream.Codec, "ass", StringComparison.OrdinalIgnoreCase)
  3175. || string.Equals(state.SubtitleStream.Codec, "ssa", StringComparison.OrdinalIgnoreCase));
  3176. /* Make main filters for video stream */
  3177. var mainFilters = new List<string>();
  3178. mainFilters.Add(GetOverwriteColorPropertiesParam(state, doTonemap));
  3179. if (isSwDecoder)
  3180. {
  3181. // INPUT sw surface(memory)
  3182. var outFormat = doOclTonemap ? "yuv420p10" : "nv12";
  3183. var swScaleFilter = GetSwScaleFilter(state, options, vidEncoder, inW, inH, threeDFormat, reqW, reqH, reqMaxW, reqMaxH);
  3184. // sw scale
  3185. mainFilters.AddRange(swScaleFilter);
  3186. mainFilters.Add("format=" + outFormat);
  3187. // sw deint
  3188. if (doDeintH2645)
  3189. {
  3190. var swDeintFilter = GetSwDeinterlaceFilter(state, options);
  3191. mainFilters.Add(swDeintFilter);
  3192. }
  3193. // keep video at memory except ocl tonemap,
  3194. // since the overhead caused by hwupload >>> using sw filter.
  3195. // sw => hw
  3196. if (doOclTonemap)
  3197. {
  3198. mainFilters.Add("hwupload");
  3199. }
  3200. }
  3201. else if (isVaapiDecoder)
  3202. {
  3203. // INPUT vaapi surface(vram)
  3204. var outFormat = doTonemap ? string.Empty : "nv12";
  3205. var hwScaleFilter = GetHwScaleFilter("vaapi", outFormat, inW, inH, reqW, reqH, reqMaxW, reqMaxH);
  3206. // hw scale
  3207. mainFilters.Add(hwScaleFilter);
  3208. }
  3209. // hw deint
  3210. if (doDeintH2645 && isVaapiDecoder)
  3211. {
  3212. var deintFilter = GetHwDeinterlaceFilter(state, options, "vaapi");
  3213. mainFilters.Add(deintFilter);
  3214. }
  3215. // vaapi vpp tonemap
  3216. if (doVaVppTonemap && isVaapiDecoder)
  3217. {
  3218. var tonemapFilter = GetHwTonemapFilter(options, "vaapi", "nv12");
  3219. mainFilters.Add(tonemapFilter);
  3220. }
  3221. if (doOclTonemap && isVaapiDecoder)
  3222. {
  3223. // map from vaapi to opencl via vaapi-opencl interop(Intel only).
  3224. mainFilters.Add("hwmap=derive_device=opencl");
  3225. }
  3226. // ocl tonemap
  3227. if (doOclTonemap)
  3228. {
  3229. var tonemapFilter = GetHwTonemapFilter(options, "opencl", "nv12");
  3230. mainFilters.Add(tonemapFilter);
  3231. }
  3232. if (doOclTonemap && isVaInVaOut)
  3233. {
  3234. // OUTPUT vaapi(nv12) surface(vram)
  3235. // reverse-mapping via vaapi-opencl interop.
  3236. mainFilters.Add("hwmap=derive_device=vaapi:reverse=1");
  3237. mainFilters.Add("format=vaapi");
  3238. }
  3239. var memoryOutput = false;
  3240. var isUploadForOclTonemap = isSwDecoder && doOclTonemap;
  3241. var isHwmapNotUsable = isUploadForOclTonemap && isVaapiEncoder;
  3242. if ((isVaapiDecoder && isSwEncoder) || isUploadForOclTonemap)
  3243. {
  3244. memoryOutput = true;
  3245. // OUTPUT nv12 surface(memory)
  3246. // prefer hwmap to hwdownload on opencl/vaapi.
  3247. mainFilters.Add(isHwmapNotUsable ? "hwdownload" : "hwmap");
  3248. mainFilters.Add("format=nv12");
  3249. }
  3250. // OUTPUT nv12 surface(memory)
  3251. if (isSwDecoder && isVaapiEncoder)
  3252. {
  3253. memoryOutput = true;
  3254. }
  3255. if (memoryOutput)
  3256. {
  3257. // text subtitles
  3258. if (hasTextSubs)
  3259. {
  3260. var textSubtitlesFilter = GetTextSubtitlesFilter(state, false, false);
  3261. mainFilters.Add(textSubtitlesFilter);
  3262. }
  3263. }
  3264. if (memoryOutput && isVaapiEncoder)
  3265. {
  3266. if (!hasGraphicalSubs)
  3267. {
  3268. mainFilters.Add("hwupload_vaapi");
  3269. }
  3270. }
  3271. /* Make sub and overlay filters for subtitle stream */
  3272. var subFilters = new List<string>();
  3273. var overlayFilters = new List<string>();
  3274. if (isVaInVaOut)
  3275. {
  3276. if (hasSubs)
  3277. {
  3278. if (hasGraphicalSubs)
  3279. {
  3280. subFilters.Add("scale=flags=fast_bilinear");
  3281. subFilters.Add("format=bgra");
  3282. }
  3283. else if (hasTextSubs)
  3284. {
  3285. var alphaSrcFilter = GetAlphaSrcFilter(state, inW, inH, reqW, reqH, reqMaxW, 1080, hasAssSubs ? 10 : 5);
  3286. var subTextSubtitlesFilter = GetTextSubtitlesFilter(state, true, true);
  3287. subFilters.Add(alphaSrcFilter);
  3288. subFilters.Add("format=bgra");
  3289. subFilters.Add(subTextSubtitlesFilter);
  3290. }
  3291. subFilters.Add("hwupload");
  3292. var (overlayW, overlayH) = GetFixedOutputSize(inW, inH, reqW, reqH, reqMaxW, reqMaxH);
  3293. var overlaySize = (overlayW.HasValue && overlayH.HasValue)
  3294. ? (":w=" + overlayW.Value + ":h=" + overlayH.Value)
  3295. : string.Empty;
  3296. var overlayVaapiFilter = string.Format(
  3297. CultureInfo.InvariantCulture,
  3298. "overlay_vaapi=eof_action=endall:shortest=1:repeatlast=0{0}",
  3299. overlaySize);
  3300. overlayFilters.Add(overlayVaapiFilter);
  3301. }
  3302. }
  3303. else if (memoryOutput)
  3304. {
  3305. if (hasGraphicalSubs)
  3306. {
  3307. var subSwScaleFilter = GetCustomSwScaleFilter(inW, inH, reqW, reqH, reqMaxW, reqMaxH);
  3308. subFilters.Add(subSwScaleFilter);
  3309. overlayFilters.Add("overlay=eof_action=pass:shortest=1:repeatlast=0");
  3310. if (isVaapiEncoder)
  3311. {
  3312. overlayFilters.Add("hwupload_vaapi");
  3313. }
  3314. }
  3315. }
  3316. return new Tuple<List<string>, List<string>, List<string>>(mainFilters, subFilters, overlayFilters);
  3317. }
  3318. public Tuple<List<string>, List<string>, List<string>> GetVaapiLimitedVidFiltersPrefered(
  3319. EncodingJobInfo state,
  3320. EncodingOptions options,
  3321. string vidDecoder,
  3322. string vidEncoder)
  3323. {
  3324. var inW = state.VideoStream?.Width;
  3325. var inH = state.VideoStream?.Height;
  3326. var reqW = state.BaseRequest.Width;
  3327. var reqH = state.BaseRequest.Height;
  3328. var reqMaxW = state.BaseRequest.MaxWidth;
  3329. var reqMaxH = state.BaseRequest.MaxHeight;
  3330. var threeDFormat = state.MediaSource.Video3DFormat;
  3331. var isVaapiDecoder = vidDecoder.Contains("vaapi", StringComparison.OrdinalIgnoreCase);
  3332. var isVaapiEncoder = vidEncoder.Contains("vaapi", StringComparison.OrdinalIgnoreCase);
  3333. var isSwDecoder = string.IsNullOrEmpty(vidDecoder);
  3334. var isSwEncoder = !isVaapiEncoder;
  3335. var isVaInVaOut = isVaapiDecoder && isVaapiEncoder;
  3336. var isi965Driver = _mediaEncoder.IsVaapiDeviceInteli965();
  3337. var isAmdDriver = _mediaEncoder.IsVaapiDeviceAmd();
  3338. var doDeintH264 = state.DeInterlace("h264", true) || state.DeInterlace("avc", true);
  3339. var doDeintHevc = state.DeInterlace("h265", true) || state.DeInterlace("hevc", true);
  3340. var doDeintH2645 = doDeintH264 || doDeintHevc;
  3341. var doOclTonemap = IsHwTonemapAvailable(state, options);
  3342. var hasSubs = state.SubtitleStream != null && state.SubtitleDeliveryMethod == SubtitleDeliveryMethod.Encode;
  3343. var hasTextSubs = hasSubs && state.SubtitleStream.IsTextSubtitleStream;
  3344. var hasGraphicalSubs = hasSubs && !state.SubtitleStream.IsTextSubtitleStream;
  3345. /* Make main filters for video stream */
  3346. var mainFilters = new List<string>();
  3347. mainFilters.Add(GetOverwriteColorPropertiesParam(state, doOclTonemap));
  3348. var outFormat = string.Empty;
  3349. if (isSwDecoder)
  3350. {
  3351. // INPUT sw surface(memory)
  3352. outFormat = doOclTonemap ? "yuv420p10" : "nv12";
  3353. var swScaleFilter = GetSwScaleFilter(state, options, vidEncoder, inW, inH, threeDFormat, reqW, reqH, reqMaxW, reqMaxH);
  3354. // sw scale
  3355. mainFilters.AddRange(swScaleFilter);
  3356. mainFilters.Add("format=" + outFormat);
  3357. // sw deint
  3358. if (doDeintH2645)
  3359. {
  3360. var swDeintFilter = GetSwDeinterlaceFilter(state, options);
  3361. mainFilters.Add(swDeintFilter);
  3362. }
  3363. // keep video at memory except ocl tonemap,
  3364. // since the overhead caused by hwupload >>> using sw filter.
  3365. // sw => hw
  3366. if (doOclTonemap)
  3367. {
  3368. mainFilters.Add("hwupload");
  3369. }
  3370. }
  3371. else if (isVaapiDecoder)
  3372. {
  3373. // INPUT vaapi surface(vram)
  3374. outFormat = doOclTonemap ? string.Empty : "nv12";
  3375. var hwScaleFilter = GetHwScaleFilter("vaapi", outFormat, inW, inH, reqW, reqH, reqMaxW, reqMaxH);
  3376. // hw scale
  3377. mainFilters.Add(hwScaleFilter);
  3378. }
  3379. // hw deint
  3380. if (doDeintH2645 && isVaapiDecoder)
  3381. {
  3382. var deintFilter = GetHwDeinterlaceFilter(state, options, "vaapi");
  3383. mainFilters.Add(deintFilter);
  3384. }
  3385. if (doOclTonemap && isVaapiDecoder)
  3386. {
  3387. if (isi965Driver)
  3388. {
  3389. // map from vaapi to opencl via vaapi-opencl interop(Intel only).
  3390. mainFilters.Add("hwmap=derive_device=opencl");
  3391. }
  3392. else
  3393. {
  3394. mainFilters.Add("hwdownload");
  3395. mainFilters.Add("format=p010le");
  3396. mainFilters.Add("hwupload");
  3397. }
  3398. }
  3399. // ocl tonemap
  3400. if (doOclTonemap)
  3401. {
  3402. var tonemapFilter = GetHwTonemapFilter(options, "opencl", "nv12");
  3403. mainFilters.Add(tonemapFilter);
  3404. }
  3405. if (doOclTonemap && isVaInVaOut)
  3406. {
  3407. if (isi965Driver)
  3408. {
  3409. // OUTPUT vaapi(nv12) surface(vram)
  3410. // reverse-mapping via vaapi-opencl interop.
  3411. mainFilters.Add("hwmap=derive_device=vaapi:reverse=1");
  3412. mainFilters.Add("format=vaapi");
  3413. }
  3414. }
  3415. var memoryOutput = false;
  3416. var isUploadForOclTonemap = doOclTonemap && (isSwDecoder || (isVaapiDecoder && !isi965Driver));
  3417. var isHwmapNotUsable = hasGraphicalSubs || isUploadForOclTonemap;
  3418. var isHwmapForSubs = hasSubs && isVaapiDecoder;
  3419. var isHwUnmapForTextSubs = hasTextSubs && isVaInVaOut && !isUploadForOclTonemap;
  3420. if ((isVaapiDecoder && isSwEncoder) || isUploadForOclTonemap || isHwmapForSubs)
  3421. {
  3422. memoryOutput = true;
  3423. // OUTPUT nv12 surface(memory)
  3424. // prefer hwmap to hwdownload on opencl/vaapi.
  3425. mainFilters.Add(isHwmapNotUsable ? "hwdownload" : "hwmap");
  3426. mainFilters.Add("format=nv12");
  3427. }
  3428. // OUTPUT nv12 surface(memory)
  3429. if (isSwDecoder && isVaapiEncoder)
  3430. {
  3431. memoryOutput = true;
  3432. }
  3433. if (memoryOutput)
  3434. {
  3435. // text subtitles
  3436. if (hasTextSubs)
  3437. {
  3438. var textSubtitlesFilter = GetTextSubtitlesFilter(state, false, false);
  3439. mainFilters.Add(textSubtitlesFilter);
  3440. }
  3441. }
  3442. if (isHwUnmapForTextSubs)
  3443. {
  3444. mainFilters.Add("hwmap");
  3445. mainFilters.Add("format=vaapi");
  3446. }
  3447. else if (memoryOutput && isVaapiEncoder)
  3448. {
  3449. if (!hasGraphicalSubs)
  3450. {
  3451. mainFilters.Add("hwupload_vaapi");
  3452. }
  3453. }
  3454. /* Make sub and overlay filters for subtitle stream */
  3455. var subFilters = new List<string>();
  3456. var overlayFilters = new List<string>();
  3457. if (memoryOutput)
  3458. {
  3459. if (hasGraphicalSubs)
  3460. {
  3461. var subSwScaleFilter = GetCustomSwScaleFilter(inW, inH, reqW, reqH, reqMaxW, reqMaxH);
  3462. subFilters.Add(subSwScaleFilter);
  3463. overlayFilters.Add("overlay=eof_action=pass:shortest=1:repeatlast=0");
  3464. if (isVaapiEncoder)
  3465. {
  3466. overlayFilters.Add("hwupload_vaapi");
  3467. }
  3468. }
  3469. }
  3470. return new Tuple<List<string>, List<string>, List<string>>(mainFilters, subFilters, overlayFilters);
  3471. }
  3472. /// <summary>
  3473. /// Gets the parameter of video processing filters.
  3474. /// </summary>
  3475. /// <param name="state">Encoding state.</param>
  3476. /// <param name="options">Encoding options.</param>
  3477. /// <param name="outputVideoCodec">Video codec to use.</param>
  3478. /// <returns>The video processing filters parameter.</returns>
  3479. public string GetVideoProcessingFilterParam(
  3480. EncodingJobInfo state,
  3481. EncodingOptions options,
  3482. string outputVideoCodec)
  3483. {
  3484. var videoStream = state.VideoStream;
  3485. if (videoStream == null)
  3486. {
  3487. return string.Empty;
  3488. }
  3489. var hasSubs = state.SubtitleStream != null && state.SubtitleDeliveryMethod == SubtitleDeliveryMethod.Encode;
  3490. var hasTextSubs = hasSubs && state.SubtitleStream.IsTextSubtitleStream;
  3491. var hasGraphicalSubs = hasSubs && !state.SubtitleStream.IsTextSubtitleStream;
  3492. Tuple<List<string>, List<string>, List<string>> filterChain = null;
  3493. if (string.Equals(options.HardwareAccelerationType, "vaapi", StringComparison.OrdinalIgnoreCase))
  3494. {
  3495. filterChain = GetVaapiVidFilterChain(state, options, outputVideoCodec);
  3496. }
  3497. else if (string.Equals(options.HardwareAccelerationType, "qsv", StringComparison.OrdinalIgnoreCase))
  3498. {
  3499. filterChain = GetIntelVidFilterChain(state, options, outputVideoCodec);
  3500. }
  3501. else if (string.Equals(options.HardwareAccelerationType, "nvenc", StringComparison.OrdinalIgnoreCase))
  3502. {
  3503. filterChain = GetNvidiaVidFilterChain(state, options, outputVideoCodec);
  3504. }
  3505. else if (string.Equals(options.HardwareAccelerationType, "amf", StringComparison.OrdinalIgnoreCase))
  3506. {
  3507. filterChain = GetAmdVidFilterChain(state, options, outputVideoCodec);
  3508. }
  3509. else
  3510. {
  3511. filterChain = GetSwVidFilterChain(state, options, outputVideoCodec);
  3512. }
  3513. var mainFilters = filterChain.Item1;
  3514. mainFilters.RemoveAll(filter => string.IsNullOrEmpty(filter));
  3515. var subFilters = filterChain.Item2;
  3516. subFilters.RemoveAll(filter => string.IsNullOrEmpty(filter));
  3517. var overlayFilters = filterChain.Item3;
  3518. overlayFilters.RemoveAll(filter => string.IsNullOrEmpty(filter));
  3519. var mainStr = string.Empty;
  3520. if (mainFilters.Count > 0)
  3521. {
  3522. mainStr = string.Format(
  3523. CultureInfo.InvariantCulture,
  3524. "{0}",
  3525. string.Join(',', mainFilters));
  3526. }
  3527. if (overlayFilters.Count == 0)
  3528. {
  3529. // -vf "scale..."
  3530. return string.IsNullOrEmpty(mainStr) ? string.Empty : " -vf \"" + mainStr + "\"";
  3531. }
  3532. else if (overlayFilters.Count > 0 && subFilters.Count > 0 && state.SubtitleStream != null)
  3533. {
  3534. // overlay graphical/text subtitles
  3535. var subStr = string.Format(
  3536. CultureInfo.InvariantCulture,
  3537. "{0}",
  3538. string.Join(',', subFilters));
  3539. var overlayStr = string.Format(
  3540. CultureInfo.InvariantCulture,
  3541. "{0}",
  3542. string.Join(',', overlayFilters));
  3543. var mapPrefix = state.SubtitleStream.IsExternal
  3544. ? 1
  3545. : 0;
  3546. var subtitleStreamIndex = state.SubtitleStream.IsExternal
  3547. ? 0
  3548. : state.SubtitleStream.Index;
  3549. if (hasSubs)
  3550. {
  3551. // -filter_complex "[0:s]scale=s[sub]..."
  3552. var filterStr = string.IsNullOrEmpty(mainStr)
  3553. ? " -filter_complex \"[{0}:{1}]{4}[sub];[0:{2}][sub]{5}\""
  3554. : " -filter_complex \"[{0}:{1}]{4}[sub];[0:{2}]{3}[main];[main][sub]{5}\"";
  3555. if (hasTextSubs)
  3556. {
  3557. filterStr = string.IsNullOrEmpty(mainStr)
  3558. ? " -filter_complex \"{4}[sub];[0:{2}][sub]{5}\""
  3559. : " -filter_complex \"{4}[sub];[0:{2}]{3}[main];[main][sub]{5}\"";
  3560. }
  3561. return string.Format(
  3562. CultureInfo.InvariantCulture,
  3563. filterStr,
  3564. mapPrefix,
  3565. subtitleStreamIndex,
  3566. state.VideoStream.Index,
  3567. mainStr,
  3568. subStr,
  3569. overlayStr);
  3570. }
  3571. }
  3572. return string.Empty;
  3573. }
  3574. public string GetOverwriteColorPropertiesParam(EncodingJobInfo state, bool isTonemapAvailable)
  3575. {
  3576. if (isTonemapAvailable)
  3577. {
  3578. return GetInputHdrParam(state.VideoStream?.ColorTransfer);
  3579. }
  3580. else
  3581. {
  3582. return GetOutputSdrParam(null);
  3583. }
  3584. }
  3585. public string GetInputHdrParam(string colorTransfer)
  3586. {
  3587. if (string.Equals(colorTransfer, "arib-std-b67", StringComparison.OrdinalIgnoreCase))
  3588. {
  3589. // HLG
  3590. return "setparams=color_primaries=bt2020:color_trc=arib-std-b67:colorspace=bt2020nc";
  3591. }
  3592. else
  3593. {
  3594. // HDR10
  3595. return "setparams=color_primaries=bt2020:color_trc=smpte2084:colorspace=bt2020nc";
  3596. }
  3597. }
  3598. public string GetOutputSdrParam(string tonemappingRange)
  3599. {
  3600. // SDR
  3601. if (string.Equals(tonemappingRange, "tv", StringComparison.OrdinalIgnoreCase))
  3602. {
  3603. return "setparams=color_primaries=bt709:color_trc=bt709:colorspace=bt709:range=tv";
  3604. }
  3605. if (string.Equals(tonemappingRange, "pc", StringComparison.OrdinalIgnoreCase))
  3606. {
  3607. return "setparams=color_primaries=bt709:color_trc=bt709:colorspace=bt709:range=pc";
  3608. }
  3609. return "setparams=color_primaries=bt709:color_trc=bt709:colorspace=bt709";
  3610. }
  3611. public static int GetVideoColorBitDepth(EncodingJobInfo state)
  3612. {
  3613. var videoStream = state.VideoStream;
  3614. if (videoStream != null)
  3615. {
  3616. if (videoStream.BitDepth.HasValue)
  3617. {
  3618. return videoStream.BitDepth.Value;
  3619. }
  3620. else if (string.Equals(videoStream.PixelFormat, "yuv420p", StringComparison.OrdinalIgnoreCase)
  3621. || string.Equals(videoStream.PixelFormat, "yuv444p", StringComparison.OrdinalIgnoreCase))
  3622. {
  3623. return 8;
  3624. }
  3625. else if (string.Equals(videoStream.PixelFormat, "yuv420p10le", StringComparison.OrdinalIgnoreCase)
  3626. || string.Equals(videoStream.PixelFormat, "yuv444p10le", StringComparison.OrdinalIgnoreCase))
  3627. {
  3628. return 10;
  3629. }
  3630. else if (string.Equals(videoStream.PixelFormat, "yuv420p12le", StringComparison.OrdinalIgnoreCase)
  3631. || string.Equals(videoStream.PixelFormat, "yuv444p12le", StringComparison.OrdinalIgnoreCase))
  3632. {
  3633. return 12;
  3634. }
  3635. else
  3636. {
  3637. return 8;
  3638. }
  3639. }
  3640. return 0;
  3641. }
  3642. /// <summary>
  3643. /// Gets the ffmpeg option string for the hardware accelerated video decoder.
  3644. /// </summary>
  3645. /// <param name="state">The encoding job info.</param>
  3646. /// <param name="options">The encoding options.</param>
  3647. /// <returns>The option string or null if none available.</returns>
  3648. protected string GetHardwareVideoDecoder(EncodingJobInfo state, EncodingOptions options)
  3649. {
  3650. var videoStream = state.VideoStream;
  3651. if (videoStream == null)
  3652. {
  3653. return null;
  3654. }
  3655. // Only use alternative encoders for video files.
  3656. var videoType = state.MediaSource.VideoType ?? VideoType.VideoFile;
  3657. if (videoType != VideoType.VideoFile)
  3658. {
  3659. return null;
  3660. }
  3661. if (IsCopyCodec(state.OutputVideoCodec))
  3662. {
  3663. return null;
  3664. }
  3665. if (!string.IsNullOrEmpty(videoStream.Codec) && !string.IsNullOrEmpty(options.HardwareAccelerationType))
  3666. {
  3667. var bitDepth = GetVideoColorBitDepth(state);
  3668. // Only HEVC, VP9 and AV1 formats have 10-bit hardware decoder support now.
  3669. if (bitDepth == 10 && !(string.Equals(videoStream.Codec, "hevc", StringComparison.OrdinalIgnoreCase)
  3670. || string.Equals(videoStream.Codec, "h265", StringComparison.OrdinalIgnoreCase)
  3671. || string.Equals(videoStream.Codec, "vp9", StringComparison.OrdinalIgnoreCase)
  3672. || string.Equals(videoStream.Codec, "av1", StringComparison.OrdinalIgnoreCase)))
  3673. {
  3674. return null;
  3675. }
  3676. if (string.Equals(options.HardwareAccelerationType, "qsv", StringComparison.OrdinalIgnoreCase))
  3677. {
  3678. return GetQsvHwVidDecoder(state, options, videoStream, bitDepth);
  3679. }
  3680. if (string.Equals(options.HardwareAccelerationType, "nvenc", StringComparison.OrdinalIgnoreCase))
  3681. {
  3682. return GetNvdecVidDecoder(state, options, videoStream, bitDepth);
  3683. }
  3684. if (string.Equals(options.HardwareAccelerationType, "amf", StringComparison.OrdinalIgnoreCase))
  3685. {
  3686. return GetAmfVidDecoder(state, options, videoStream, bitDepth);
  3687. }
  3688. if (string.Equals(options.HardwareAccelerationType, "vaapi", StringComparison.OrdinalIgnoreCase))
  3689. {
  3690. return GetVaapiVidDecoder(state, options, videoStream, bitDepth);
  3691. }
  3692. if (string.Equals(options.HardwareAccelerationType, "videotoolbox", StringComparison.OrdinalIgnoreCase))
  3693. {
  3694. return GetVideotoolboxVidDecoder(state, options, videoStream, bitDepth);
  3695. }
  3696. if (string.Equals(options.HardwareAccelerationType, "omx", StringComparison.OrdinalIgnoreCase))
  3697. {
  3698. return GetOmxVidDecoder(state, options, videoStream, bitDepth);
  3699. }
  3700. }
  3701. var whichCodec = videoStream.Codec?.ToLowerInvariant();
  3702. switch (whichCodec)
  3703. {
  3704. case "avc":
  3705. whichCodec = "h264";
  3706. break;
  3707. case "h265":
  3708. whichCodec = "hevc";
  3709. break;
  3710. }
  3711. // Avoid a second attempt if no hardware acceleration is being used
  3712. options.HardwareDecodingCodecs = options.HardwareDecodingCodecs.Where(val => val != whichCodec).ToArray();
  3713. // leave blank so ffmpeg will decide
  3714. return null;
  3715. }
  3716. /// <summary>
  3717. /// Gets a hw decoder name.
  3718. /// </summary>
  3719. /// <param name="options">Encoding options.</param>
  3720. /// <param name="decoderPrefix">Decoder prefix.</param>
  3721. /// <param name="decoderSuffix">Decoder suffix.</param>
  3722. /// <param name="videoCodec">Video codec to use.</param>
  3723. /// <param name="bitDepth">Video color bit depth.</param>
  3724. /// <returns>Hardware decoder name.</returns>
  3725. public string GetHwDecoderName(EncodingOptions options, string decoderPrefix, string decoderSuffix, string videoCodec, int bitDepth)
  3726. {
  3727. if (string.IsNullOrEmpty(decoderPrefix) || string.IsNullOrEmpty(decoderSuffix))
  3728. {
  3729. return null;
  3730. }
  3731. var decoderName = decoderPrefix + '_' + decoderSuffix;
  3732. var isCodecAvailable = _mediaEncoder.SupportsDecoder(decoderName) && options.HardwareDecodingCodecs.Contains(videoCodec, StringComparer.OrdinalIgnoreCase);
  3733. if (bitDepth == 10 && isCodecAvailable)
  3734. {
  3735. if ((options.HardwareDecodingCodecs.Contains("hevc", StringComparer.OrdinalIgnoreCase) && !options.EnableDecodingColorDepth10Hevc)
  3736. || (options.HardwareDecodingCodecs.Contains("vp9", StringComparer.OrdinalIgnoreCase) && !options.EnableDecodingColorDepth10Vp9))
  3737. {
  3738. return null;
  3739. }
  3740. }
  3741. if (string.Equals(decoderSuffix, "cuvid", StringComparison.OrdinalIgnoreCase) && options.EnableEnhancedNvdecDecoder)
  3742. {
  3743. return null;
  3744. }
  3745. if (string.Equals(decoderSuffix, "qsv", StringComparison.OrdinalIgnoreCase) && options.PreferSystemNativeHwDecoder)
  3746. {
  3747. return null;
  3748. }
  3749. return isCodecAvailable ? (" -c:v " + decoderName) : null;
  3750. }
  3751. /// <summary>
  3752. /// Gets a hwaccel type to use as a hardware decoder depending on the system.
  3753. /// </summary>
  3754. /// <param name="state">Encoding state.</param>
  3755. /// <param name="options">Encoding options.</param>
  3756. /// <param name="videoCodec">Video codec to use.</param>
  3757. /// <param name="bitDepth">Video color bit depth.</param>
  3758. /// <param name="outputHwSurface">Specifies if output hw surface.</param>
  3759. /// <returns>Hardware accelerator type.</returns>
  3760. public string GetHwaccelType(EncodingJobInfo state, EncodingOptions options, string videoCodec, int bitDepth, bool outputHwSurface)
  3761. {
  3762. var isWindows = OperatingSystem.IsWindows();
  3763. var isLinux = OperatingSystem.IsLinux();
  3764. var isMacOS = OperatingSystem.IsMacOS();
  3765. var isD3d11Supported = isWindows && _mediaEncoder.SupportsHwaccel("d3d11va");
  3766. var isVaapiSupported = isLinux && IsVaapiSupported(state);
  3767. var isCudaSupported = (isLinux || isWindows) && IsCudaFullSupported();
  3768. var isQsvSupported = (isLinux || isWindows) && _mediaEncoder.SupportsHwaccel("qsv");
  3769. var isVideotoolboxSupported = isMacOS && _mediaEncoder.SupportsHwaccel("videotoolbox");
  3770. var isCodecAvailable = options.HardwareDecodingCodecs.Contains(videoCodec, StringComparer.OrdinalIgnoreCase);
  3771. if (bitDepth == 10 && isCodecAvailable)
  3772. {
  3773. if ((options.HardwareDecodingCodecs.Contains("hevc", StringComparer.OrdinalIgnoreCase) && !options.EnableDecodingColorDepth10Hevc)
  3774. || (options.HardwareDecodingCodecs.Contains("vp9", StringComparer.OrdinalIgnoreCase) && !options.EnableDecodingColorDepth10Vp9))
  3775. {
  3776. return null;
  3777. }
  3778. }
  3779. // Intel qsv/d3d11va/vaapi
  3780. if (string.Equals(options.HardwareAccelerationType, "qsv", StringComparison.OrdinalIgnoreCase))
  3781. {
  3782. if (options.PreferSystemNativeHwDecoder)
  3783. {
  3784. if (isVaapiSupported && isCodecAvailable)
  3785. {
  3786. return " -hwaccel vaapi" + (outputHwSurface ? " -hwaccel_output_format vaapi" : string.Empty);
  3787. }
  3788. if (isD3d11Supported && isCodecAvailable)
  3789. {
  3790. return " -hwaccel d3d11va" + (outputHwSurface ? " -hwaccel_output_format d3d11" : string.Empty);
  3791. }
  3792. }
  3793. else
  3794. {
  3795. if (isQsvSupported && isCodecAvailable)
  3796. {
  3797. return " -hwaccel qsv" + (outputHwSurface ? " -hwaccel_output_format qsv" : string.Empty);
  3798. }
  3799. }
  3800. }
  3801. // Nvidia cuda
  3802. if (string.Equals(options.HardwareAccelerationType, "nvenc", StringComparison.OrdinalIgnoreCase))
  3803. {
  3804. if (options.EnableEnhancedNvdecDecoder && isCudaSupported && isCodecAvailable)
  3805. {
  3806. return " -hwaccel cuda" + (outputHwSurface ? " -hwaccel_output_format cuda" : string.Empty);
  3807. }
  3808. }
  3809. // Amd d3d11va
  3810. if (string.Equals(options.HardwareAccelerationType, "amf", StringComparison.OrdinalIgnoreCase))
  3811. {
  3812. if (isD3d11Supported && isCodecAvailable)
  3813. {
  3814. return " -hwaccel d3d11va" + (outputHwSurface ? " -hwaccel_output_format d3d11" : string.Empty);
  3815. }
  3816. }
  3817. // Vaapi
  3818. if (string.Equals(options.HardwareAccelerationType, "vaapi", StringComparison.OrdinalIgnoreCase))
  3819. {
  3820. if (isVaapiSupported && isCodecAvailable)
  3821. {
  3822. return " -hwaccel vaapi" + (outputHwSurface ? " -hwaccel_output_format vaapi" : string.Empty);
  3823. }
  3824. }
  3825. if (string.Equals(options.HardwareAccelerationType, "videotoolbox", StringComparison.OrdinalIgnoreCase))
  3826. {
  3827. if (isVideotoolboxSupported && isCodecAvailable)
  3828. {
  3829. return " -hwaccel videotoolbox" + (outputHwSurface ? " -hwaccel_output_format videotoolbox_vld" : string.Empty);
  3830. }
  3831. }
  3832. return null;
  3833. }
  3834. public string GetQsvHwVidDecoder(EncodingJobInfo state, EncodingOptions options, MediaStream videoStream, int bitDepth)
  3835. {
  3836. var isWindows = OperatingSystem.IsWindows();
  3837. var isLinux = OperatingSystem.IsLinux();
  3838. if (!isWindows && !isLinux)
  3839. {
  3840. return null;
  3841. }
  3842. var isQsvOclSupported = _mediaEncoder.SupportsHwaccel("qsv") && IsOpenclFullSupported();
  3843. var isIntelDx11OclSupported = isWindows
  3844. && _mediaEncoder.SupportsHwaccel("d3d11va")
  3845. && isQsvOclSupported;
  3846. var isIntelVaapiOclSupported = isLinux
  3847. && IsVaapiSupported(state)
  3848. && isQsvOclSupported;
  3849. var hwSurface = (isIntelDx11OclSupported || isIntelVaapiOclSupported)
  3850. && _mediaEncoder.SupportsFilter("alphasrc");
  3851. var _8bitSwFormatsQsv = new List<string> { "yuv420p", };
  3852. var _8_10bitSwFormatsQsv = new List<string> { "yuv420p", "yuv420p10le", };
  3853. // TODO: add more 8/10bit and 4:4:4 formats for Qsv after finshing the ffcheck tool
  3854. if (string.Equals(options.HardwareAccelerationType, "qsv", StringComparison.OrdinalIgnoreCase))
  3855. {
  3856. switch (videoStream.Codec.ToLowerInvariant())
  3857. {
  3858. case "avc":
  3859. case "h264":
  3860. return _8bitSwFormatsQsv.Contains(videoStream.PixelFormat)
  3861. ? GetHwaccelType(state, options, "h264", bitDepth, hwSurface) + GetHwDecoderName(options, "h264", "qsv", "h264", bitDepth)
  3862. : string.Empty;
  3863. case "hevc":
  3864. case "h265":
  3865. return _8_10bitSwFormatsQsv.Contains(videoStream.PixelFormat)
  3866. ? GetHwaccelType(state, options, "hevc", bitDepth, hwSurface) + GetHwDecoderName(options, "hevc", "qsv", "hevc", bitDepth)
  3867. : string.Empty;
  3868. case "mpeg2video":
  3869. return _8bitSwFormatsQsv.Contains(videoStream.PixelFormat)
  3870. ? GetHwaccelType(state, options, "mpeg2video", bitDepth, hwSurface) + GetHwDecoderName(options, "mpeg2", "qsv", "mpeg2video", bitDepth)
  3871. : string.Empty;
  3872. case "vc1":
  3873. return _8bitSwFormatsQsv.Contains(videoStream.PixelFormat)
  3874. ? GetHwaccelType(state, options, "vc1", bitDepth, hwSurface) + GetHwDecoderName(options, "vc1", "qsv", "vc1", bitDepth)
  3875. : string.Empty;
  3876. case "vp8":
  3877. return _8bitSwFormatsQsv.Contains(videoStream.PixelFormat)
  3878. ? GetHwaccelType(state, options, "vp8", bitDepth, hwSurface) + GetHwDecoderName(options, "vp8", "qsv", "vp8", bitDepth)
  3879. : string.Empty;
  3880. case "vp9":
  3881. return _8_10bitSwFormatsQsv.Contains(videoStream.PixelFormat)
  3882. ? GetHwaccelType(state, options, "vp9", bitDepth, hwSurface) + GetHwDecoderName(options, "vp9", "qsv", "vp9", bitDepth)
  3883. : string.Empty;
  3884. case "av1":
  3885. return _8_10bitSwFormatsQsv.Contains(videoStream.PixelFormat)
  3886. ? GetHwaccelType(state, options, "av1", bitDepth, hwSurface) + GetHwDecoderName(options, "av1", "qsv", "av1", bitDepth)
  3887. : string.Empty;
  3888. }
  3889. }
  3890. return null;
  3891. }
  3892. public string GetNvdecVidDecoder(EncodingJobInfo state, EncodingOptions options, MediaStream videoStream, int bitDepth)
  3893. {
  3894. if (!OperatingSystem.IsWindows() && !OperatingSystem.IsLinux())
  3895. {
  3896. return null;
  3897. }
  3898. var hwSurface = IsCudaFullSupported()
  3899. && options.EnableEnhancedNvdecDecoder
  3900. && _mediaEncoder.SupportsFilter("alphasrc");
  3901. var _8bitSwFormatsNvdec = new List<string> { "yuv420p", };
  3902. var _8_10bitSwFormatsNvdec = new List<string> { "yuv420p", "yuv420p10le", };
  3903. // TODO: add more 8/10/12bit and 4:4:4 formats for Nvdec after finshing the ffcheck tool
  3904. if (string.Equals(options.HardwareAccelerationType, "nvenc", StringComparison.OrdinalIgnoreCase))
  3905. {
  3906. switch (videoStream.Codec.ToLowerInvariant())
  3907. {
  3908. case "avc":
  3909. case "h264":
  3910. return _8bitSwFormatsNvdec.Contains(videoStream.PixelFormat)
  3911. ? GetHwaccelType(state, options, "h264", bitDepth, hwSurface) + GetHwDecoderName(options, "h264", "cuvid", "h264", bitDepth)
  3912. : string.Empty;
  3913. case "hevc":
  3914. case "h265":
  3915. return _8_10bitSwFormatsNvdec.Contains(videoStream.PixelFormat)
  3916. ? GetHwaccelType(state, options, "hevc", bitDepth, hwSurface) + GetHwDecoderName(options, "hevc", "cuvid", "hevc", bitDepth)
  3917. : string.Empty;
  3918. case "mpeg2video":
  3919. return _8bitSwFormatsNvdec.Contains(videoStream.PixelFormat)
  3920. ? GetHwaccelType(state, options, "mpeg2video", bitDepth, hwSurface) + GetHwDecoderName(options, "mpeg2", "cuvid", "mpeg2video", bitDepth)
  3921. : string.Empty;
  3922. case "vc1":
  3923. return _8bitSwFormatsNvdec.Contains(videoStream.PixelFormat)
  3924. ? GetHwaccelType(state, options, "vc1", bitDepth, hwSurface) + GetHwDecoderName(options, "vc1", "cuvid", "vc1", bitDepth)
  3925. : string.Empty;
  3926. case "mpeg4":
  3927. return _8bitSwFormatsNvdec.Contains(videoStream.PixelFormat)
  3928. ? GetHwaccelType(state, options, "mpeg4", bitDepth, hwSurface) + GetHwDecoderName(options, "mpeg4", "cuvid", "mpeg4", bitDepth)
  3929. : string.Empty;
  3930. case "vp8":
  3931. return _8bitSwFormatsNvdec.Contains(videoStream.PixelFormat)
  3932. ? GetHwaccelType(state, options, "vp8", bitDepth, hwSurface) + GetHwDecoderName(options, "vp8", "cuvid", "vp8", bitDepth)
  3933. : string.Empty;
  3934. case "vp9":
  3935. return _8_10bitSwFormatsNvdec.Contains(videoStream.PixelFormat)
  3936. ? GetHwaccelType(state, options, "vp9", bitDepth, hwSurface) + GetHwDecoderName(options, "vp9", "cuvid", "vp9", bitDepth)
  3937. : string.Empty;
  3938. case "av1":
  3939. return _8_10bitSwFormatsNvdec.Contains(videoStream.PixelFormat)
  3940. ? GetHwaccelType(state, options, "av1", bitDepth, hwSurface) + GetHwDecoderName(options, "av1", "cuvid", "av1", bitDepth)
  3941. : string.Empty;
  3942. }
  3943. }
  3944. return null;
  3945. }
  3946. public string GetAmfVidDecoder(EncodingJobInfo state, EncodingOptions options, MediaStream videoStream, int bitDepth)
  3947. {
  3948. if (!OperatingSystem.IsWindows())
  3949. {
  3950. return null;
  3951. }
  3952. var hwSurface = _mediaEncoder.SupportsHwaccel("d3d11va")
  3953. && IsOpenclFullSupported()
  3954. && _mediaEncoder.SupportsFilter("alphasrc");
  3955. var _8bitSwFormatsAmf = new List<string> { "yuv420p", };
  3956. var _8_10bitSwFormatsAmf = new List<string> { "yuv420p", "yuv420p10le", };
  3957. if (string.Equals(options.HardwareAccelerationType, "amf", StringComparison.OrdinalIgnoreCase))
  3958. {
  3959. switch (videoStream.Codec.ToLowerInvariant())
  3960. {
  3961. case "avc":
  3962. case "h264":
  3963. return _8bitSwFormatsAmf.Contains(videoStream.PixelFormat)
  3964. ? GetHwaccelType(state, options, "h264", bitDepth, hwSurface)
  3965. : string.Empty;
  3966. case "hevc":
  3967. case "h265":
  3968. return _8_10bitSwFormatsAmf.Contains(videoStream.PixelFormat)
  3969. ? GetHwaccelType(state, options, "hevc", bitDepth, hwSurface)
  3970. : string.Empty;
  3971. case "mpeg2video":
  3972. return _8bitSwFormatsAmf.Contains(videoStream.PixelFormat)
  3973. ? GetHwaccelType(state, options, "mpeg2video", bitDepth, hwSurface)
  3974. : string.Empty;
  3975. case "vc1":
  3976. return _8bitSwFormatsAmf.Contains(videoStream.PixelFormat)
  3977. ? GetHwaccelType(state, options, "vc1", bitDepth, hwSurface)
  3978. : string.Empty;
  3979. case "mpeg4":
  3980. return _8bitSwFormatsAmf.Contains(videoStream.PixelFormat)
  3981. ? GetHwaccelType(state, options, "mpeg4", bitDepth, hwSurface)
  3982. : string.Empty;
  3983. case "vp9":
  3984. return _8_10bitSwFormatsAmf.Contains(videoStream.PixelFormat)
  3985. ? GetHwaccelType(state, options, "vp9", bitDepth, hwSurface)
  3986. : string.Empty;
  3987. case "av1":
  3988. return _8_10bitSwFormatsAmf.Contains(videoStream.PixelFormat)
  3989. ? GetHwaccelType(state, options, "av1", bitDepth, hwSurface)
  3990. : string.Empty;
  3991. }
  3992. }
  3993. return null;
  3994. }
  3995. public string GetVaapiVidDecoder(EncodingJobInfo state, EncodingOptions options, MediaStream videoStream, int bitDepth)
  3996. {
  3997. if (!OperatingSystem.IsLinux())
  3998. {
  3999. return null;
  4000. }
  4001. var hwSurface = IsVaapiSupported(state)
  4002. && IsVaapiFullSupported()
  4003. && IsOpenclFullSupported()
  4004. && _mediaEncoder.SupportsFilter("alphasrc");
  4005. var _8bitSwFormatsVaapi = new List<string> { "yuv420p", };
  4006. var _8_10bitSwFormatsVaapi = new List<string> { "yuv420p", "yuv420p10le", };
  4007. if (string.Equals(options.HardwareAccelerationType, "vaapi", StringComparison.OrdinalIgnoreCase))
  4008. {
  4009. switch (videoStream.Codec.ToLowerInvariant())
  4010. {
  4011. case "avc":
  4012. case "h264":
  4013. return _8bitSwFormatsVaapi.Contains(videoStream.PixelFormat)
  4014. ? GetHwaccelType(state, options, "h264", bitDepth, hwSurface)
  4015. : string.Empty;
  4016. case "hevc":
  4017. case "h265":
  4018. return _8_10bitSwFormatsVaapi.Contains(videoStream.PixelFormat)
  4019. ? GetHwaccelType(state, options, "hevc", bitDepth, hwSurface)
  4020. : string.Empty;
  4021. case "mpeg2video":
  4022. return _8bitSwFormatsVaapi.Contains(videoStream.PixelFormat)
  4023. ? GetHwaccelType(state, options, "mpeg2video", bitDepth, hwSurface)
  4024. : string.Empty;
  4025. case "vc1":
  4026. return _8bitSwFormatsVaapi.Contains(videoStream.PixelFormat)
  4027. ? GetHwaccelType(state, options, "vc1", bitDepth, hwSurface)
  4028. : string.Empty;
  4029. case "vp8":
  4030. return _8bitSwFormatsVaapi.Contains(videoStream.PixelFormat)
  4031. ? GetHwaccelType(state, options, "vp8", bitDepth, hwSurface)
  4032. : string.Empty;
  4033. case "vp9":
  4034. return _8_10bitSwFormatsVaapi.Contains(videoStream.PixelFormat)
  4035. ? GetHwaccelType(state, options, "vp9", bitDepth, hwSurface)
  4036. : string.Empty;
  4037. case "av1":
  4038. return _8_10bitSwFormatsVaapi.Contains(videoStream.PixelFormat)
  4039. ? GetHwaccelType(state, options, "av1", bitDepth, hwSurface)
  4040. : string.Empty;
  4041. }
  4042. }
  4043. return null;
  4044. }
  4045. public string GetVideotoolboxVidDecoder(EncodingJobInfo state, EncodingOptions options, MediaStream videoStream, int bitDepth)
  4046. {
  4047. if (!OperatingSystem.IsMacOS())
  4048. {
  4049. return null;
  4050. }
  4051. var _8bitSwFormatsVt = new List<string> { "yuv420p", };
  4052. var _8_10bitSwFormatsVt = new List<string> { "yuv420p", "yuv420p10le", };
  4053. if (string.Equals(options.HardwareAccelerationType, "videotoolbox", StringComparison.OrdinalIgnoreCase))
  4054. {
  4055. switch (videoStream.Codec.ToLowerInvariant())
  4056. {
  4057. case "avc":
  4058. case "h264":
  4059. return _8bitSwFormatsVt.Contains(videoStream.PixelFormat)
  4060. ? GetHwaccelType(state, options, "h264", bitDepth, false)
  4061. : string.Empty;
  4062. case "hevc":
  4063. case "h265":
  4064. return _8_10bitSwFormatsVt.Contains(videoStream.PixelFormat)
  4065. ? GetHwaccelType(state, options, "hevc", bitDepth, false)
  4066. : string.Empty;
  4067. case "mpeg2video":
  4068. return _8bitSwFormatsVt.Contains(videoStream.PixelFormat)
  4069. ? GetHwaccelType(state, options, "mpeg2video", bitDepth, false)
  4070. : string.Empty;
  4071. case "mpeg4":
  4072. return _8_10bitSwFormatsVt.Contains(videoStream.PixelFormat)
  4073. ? GetHwaccelType(state, options, "mpeg4", bitDepth, false)
  4074. : string.Empty;
  4075. }
  4076. }
  4077. return null;
  4078. }
  4079. public string GetOmxVidDecoder(EncodingJobInfo state, EncodingOptions options, MediaStream videoStream, int bitDepth)
  4080. {
  4081. if (!OperatingSystem.IsLinux())
  4082. {
  4083. return null;
  4084. }
  4085. var _8bitSwFormatsOmx = new List<string> { "yuv420p", };
  4086. if (string.Equals(options.HardwareAccelerationType, "omx", StringComparison.OrdinalIgnoreCase))
  4087. {
  4088. switch (videoStream.Codec.ToLowerInvariant())
  4089. {
  4090. case "avc":
  4091. case "h264":
  4092. return _8bitSwFormatsOmx.Contains(videoStream.PixelFormat)
  4093. ? GetHwDecoderName(options, "h264", "mmal", "h264", bitDepth)
  4094. : string.Empty;
  4095. case "mpeg2video":
  4096. return _8bitSwFormatsOmx.Contains(videoStream.PixelFormat)
  4097. ? GetHwDecoderName(options, "mpeg2", "mmal", "mpeg2video", bitDepth)
  4098. : string.Empty;
  4099. case "mpeg4":
  4100. return _8bitSwFormatsOmx.Contains(videoStream.PixelFormat)
  4101. ? GetHwDecoderName(options, "mpeg4", "mmal", "mpeg4", bitDepth)
  4102. : string.Empty;
  4103. case "vc1":
  4104. return _8bitSwFormatsOmx.Contains(videoStream.PixelFormat)
  4105. ? GetHwDecoderName(options, "vc1", "mmal", "vc1", bitDepth)
  4106. : string.Empty;
  4107. }
  4108. }
  4109. return null;
  4110. }
  4111. /// <summary>
  4112. /// Gets the number of threads.
  4113. /// </summary>
  4114. /// <param name="state">Encoding state.</param>
  4115. /// <param name="encodingOptions">Encoding options.</param>
  4116. /// <param name="outputVideoCodec">Video codec to use.</param>
  4117. /// <returns>Number of threads.</returns>
  4118. #nullable enable
  4119. public static int GetNumberOfThreads(EncodingJobInfo? state, EncodingOptions encodingOptions, string? outputVideoCodec)
  4120. {
  4121. // VP8 and VP9 encoders must have their thread counts set.
  4122. bool mustSetThreadCount = string.Equals(outputVideoCodec, "libvpx", StringComparison.OrdinalIgnoreCase)
  4123. || string.Equals(outputVideoCodec, "libvpx-vp9", StringComparison.OrdinalIgnoreCase);
  4124. var threads = state?.BaseRequest.CpuCoreLimit ?? encodingOptions.EncodingThreadCount;
  4125. if (threads <= 0)
  4126. {
  4127. // Automatically set thread count
  4128. return mustSetThreadCount ? Math.Max(Environment.ProcessorCount - 1, 1) : 0;
  4129. }
  4130. else if (threads >= Environment.ProcessorCount)
  4131. {
  4132. return Environment.ProcessorCount;
  4133. }
  4134. return threads;
  4135. }
  4136. #nullable disable
  4137. public void TryStreamCopy(EncodingJobInfo state)
  4138. {
  4139. if (state.VideoStream != null && CanStreamCopyVideo(state, state.VideoStream))
  4140. {
  4141. state.OutputVideoCodec = "copy";
  4142. }
  4143. else
  4144. {
  4145. var user = state.User;
  4146. // If the user doesn't have access to transcoding, then force stream copy, regardless of whether it will be compatible or not
  4147. if (user != null && !user.HasPermission(PermissionKind.EnableVideoPlaybackTranscoding))
  4148. {
  4149. state.OutputVideoCodec = "copy";
  4150. }
  4151. }
  4152. if (state.AudioStream != null
  4153. && CanStreamCopyAudio(state, state.AudioStream, state.SupportedAudioCodecs))
  4154. {
  4155. state.OutputAudioCodec = "copy";
  4156. }
  4157. else
  4158. {
  4159. var user = state.User;
  4160. // If the user doesn't have access to transcoding, then force stream copy, regardless of whether it will be compatible or not
  4161. if (user != null && !user.HasPermission(PermissionKind.EnableAudioPlaybackTranscoding))
  4162. {
  4163. state.OutputAudioCodec = "copy";
  4164. }
  4165. }
  4166. }
  4167. public string GetInputModifier(EncodingJobInfo state, EncodingOptions encodingOptions)
  4168. {
  4169. var inputModifier = string.Empty;
  4170. var probeSizeArgument = string.Empty;
  4171. string analyzeDurationArgument;
  4172. if (state.MediaSource.AnalyzeDurationMs.HasValue)
  4173. {
  4174. analyzeDurationArgument = "-analyzeduration " + (state.MediaSource.AnalyzeDurationMs.Value * 1000).ToString(CultureInfo.InvariantCulture);
  4175. }
  4176. else
  4177. {
  4178. analyzeDurationArgument = string.Empty;
  4179. }
  4180. if (!string.IsNullOrEmpty(probeSizeArgument))
  4181. {
  4182. inputModifier += " " + probeSizeArgument;
  4183. }
  4184. if (!string.IsNullOrEmpty(analyzeDurationArgument))
  4185. {
  4186. inputModifier += " " + analyzeDurationArgument;
  4187. }
  4188. inputModifier = inputModifier.Trim();
  4189. var userAgentParam = GetUserAgentParam(state);
  4190. if (!string.IsNullOrEmpty(userAgentParam))
  4191. {
  4192. inputModifier += " " + userAgentParam;
  4193. }
  4194. inputModifier = inputModifier.Trim();
  4195. inputModifier += " " + GetFastSeekCommandLineParameter(state, encodingOptions);
  4196. inputModifier = inputModifier.Trim();
  4197. if (state.InputProtocol == MediaProtocol.Rtsp)
  4198. {
  4199. inputModifier += " -rtsp_transport tcp -rtsp_transport udp -rtsp_flags prefer_tcp";
  4200. }
  4201. if (!string.IsNullOrEmpty(state.InputAudioSync))
  4202. {
  4203. inputModifier += " -async " + state.InputAudioSync;
  4204. }
  4205. if (!string.IsNullOrEmpty(state.InputVideoSync))
  4206. {
  4207. inputModifier += " -vsync " + state.InputVideoSync;
  4208. }
  4209. if (state.ReadInputAtNativeFramerate && state.InputProtocol != MediaProtocol.Rtsp)
  4210. {
  4211. inputModifier += " -re";
  4212. }
  4213. var flags = new List<string>();
  4214. if (state.IgnoreInputDts)
  4215. {
  4216. flags.Add("+igndts");
  4217. }
  4218. if (state.IgnoreInputIndex)
  4219. {
  4220. flags.Add("+ignidx");
  4221. }
  4222. if (state.GenPtsInput || IsCopyCodec(state.OutputVideoCodec))
  4223. {
  4224. flags.Add("+genpts");
  4225. }
  4226. if (state.DiscardCorruptFramesInput)
  4227. {
  4228. flags.Add("+discardcorrupt");
  4229. }
  4230. if (state.EnableFastSeekInput)
  4231. {
  4232. flags.Add("+fastseek");
  4233. }
  4234. if (flags.Count > 0)
  4235. {
  4236. inputModifier += " -fflags " + string.Join(string.Empty, flags);
  4237. }
  4238. if (state.IsVideoRequest)
  4239. {
  4240. if (!string.IsNullOrEmpty(state.InputContainer) && state.VideoType == VideoType.VideoFile && string.IsNullOrEmpty(encodingOptions.HardwareAccelerationType))
  4241. {
  4242. var inputFormat = GetInputFormat(state.InputContainer);
  4243. if (!string.IsNullOrEmpty(inputFormat))
  4244. {
  4245. inputModifier += " -f " + inputFormat;
  4246. }
  4247. }
  4248. }
  4249. if (state.MediaSource.RequiresLooping)
  4250. {
  4251. inputModifier += " -stream_loop -1 -reconnect_at_eof 1 -reconnect_streamed 1 -reconnect_delay_max 2";
  4252. }
  4253. return inputModifier;
  4254. }
  4255. public void AttachMediaSourceInfo(
  4256. EncodingJobInfo state,
  4257. EncodingOptions encodingOptions,
  4258. MediaSourceInfo mediaSource,
  4259. string requestedUrl)
  4260. {
  4261. if (state == null)
  4262. {
  4263. throw new ArgumentNullException(nameof(state));
  4264. }
  4265. if (mediaSource == null)
  4266. {
  4267. throw new ArgumentNullException(nameof(mediaSource));
  4268. }
  4269. var path = mediaSource.Path;
  4270. var protocol = mediaSource.Protocol;
  4271. if (!string.IsNullOrEmpty(mediaSource.EncoderPath) && mediaSource.EncoderProtocol.HasValue)
  4272. {
  4273. path = mediaSource.EncoderPath;
  4274. protocol = mediaSource.EncoderProtocol.Value;
  4275. }
  4276. state.MediaPath = path;
  4277. state.InputProtocol = protocol;
  4278. state.InputContainer = mediaSource.Container;
  4279. state.RunTimeTicks = mediaSource.RunTimeTicks;
  4280. state.RemoteHttpHeaders = mediaSource.RequiredHttpHeaders;
  4281. state.IsoType = mediaSource.IsoType;
  4282. if (mediaSource.Timestamp.HasValue)
  4283. {
  4284. state.InputTimestamp = mediaSource.Timestamp.Value;
  4285. }
  4286. state.RunTimeTicks = mediaSource.RunTimeTicks;
  4287. state.RemoteHttpHeaders = mediaSource.RequiredHttpHeaders;
  4288. state.ReadInputAtNativeFramerate = mediaSource.ReadAtNativeFramerate;
  4289. if (state.ReadInputAtNativeFramerate
  4290. || (mediaSource.Protocol == MediaProtocol.File
  4291. && string.Equals(mediaSource.Container, "wtv", StringComparison.OrdinalIgnoreCase)))
  4292. {
  4293. state.InputVideoSync = "-1";
  4294. state.InputAudioSync = "1";
  4295. }
  4296. if (string.Equals(mediaSource.Container, "wma", StringComparison.OrdinalIgnoreCase)
  4297. || string.Equals(mediaSource.Container, "asf", StringComparison.OrdinalIgnoreCase))
  4298. {
  4299. // Seeing some stuttering when transcoding wma to audio-only HLS
  4300. state.InputAudioSync = "1";
  4301. }
  4302. var mediaStreams = mediaSource.MediaStreams;
  4303. if (state.IsVideoRequest)
  4304. {
  4305. var videoRequest = state.BaseRequest;
  4306. if (string.IsNullOrEmpty(videoRequest.VideoCodec))
  4307. {
  4308. if (string.IsNullOrEmpty(requestedUrl))
  4309. {
  4310. requestedUrl = "test." + videoRequest.Container;
  4311. }
  4312. videoRequest.VideoCodec = InferVideoCodec(requestedUrl);
  4313. }
  4314. state.VideoStream = GetMediaStream(mediaStreams, videoRequest.VideoStreamIndex, MediaStreamType.Video);
  4315. state.SubtitleStream = GetMediaStream(mediaStreams, videoRequest.SubtitleStreamIndex, MediaStreamType.Subtitle, false);
  4316. state.SubtitleDeliveryMethod = videoRequest.SubtitleMethod;
  4317. state.AudioStream = GetMediaStream(mediaStreams, videoRequest.AudioStreamIndex, MediaStreamType.Audio);
  4318. if (state.SubtitleStream != null && !state.SubtitleStream.IsExternal)
  4319. {
  4320. state.InternalSubtitleStreamOffset = mediaStreams.Where(i => i.Type == MediaStreamType.Subtitle && !i.IsExternal).ToList().IndexOf(state.SubtitleStream);
  4321. }
  4322. EnforceResolutionLimit(state);
  4323. NormalizeSubtitleEmbed(state);
  4324. }
  4325. else
  4326. {
  4327. state.AudioStream = GetMediaStream(mediaStreams, null, MediaStreamType.Audio, true);
  4328. }
  4329. state.MediaSource = mediaSource;
  4330. var request = state.BaseRequest;
  4331. var supportedAudioCodecs = state.SupportedAudioCodecs;
  4332. if (request != null && supportedAudioCodecs != null && supportedAudioCodecs.Length > 0)
  4333. {
  4334. var supportedAudioCodecsList = supportedAudioCodecs.ToList();
  4335. ShiftAudioCodecsIfNeeded(supportedAudioCodecsList, state.AudioStream);
  4336. state.SupportedAudioCodecs = supportedAudioCodecsList.ToArray();
  4337. request.AudioCodec = state.SupportedAudioCodecs.FirstOrDefault(i => _mediaEncoder.CanEncodeToAudioCodec(i))
  4338. ?? state.SupportedAudioCodecs.FirstOrDefault();
  4339. }
  4340. var supportedVideoCodecs = state.SupportedVideoCodecs;
  4341. if (request != null && supportedVideoCodecs != null && supportedVideoCodecs.Length > 0)
  4342. {
  4343. var supportedVideoCodecsList = supportedVideoCodecs.ToList();
  4344. ShiftVideoCodecsIfNeeded(supportedVideoCodecsList, encodingOptions);
  4345. state.SupportedVideoCodecs = supportedVideoCodecsList.ToArray();
  4346. request.VideoCodec = state.SupportedVideoCodecs.FirstOrDefault();
  4347. }
  4348. }
  4349. private void ShiftAudioCodecsIfNeeded(List<string> audioCodecs, MediaStream audioStream)
  4350. {
  4351. // No need to shift if there is only one supported audio codec.
  4352. if (audioCodecs.Count < 2)
  4353. {
  4354. return;
  4355. }
  4356. var inputChannels = audioStream == null ? 6 : audioStream.Channels ?? 6;
  4357. if (inputChannels >= 6)
  4358. {
  4359. return;
  4360. }
  4361. // Transcoding to 2ch ac3 almost always causes a playback failure
  4362. // 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
  4363. var shiftAudioCodecs = new[] { "ac3", "eac3" };
  4364. if (audioCodecs.All(i => shiftAudioCodecs.Contains(i, StringComparer.OrdinalIgnoreCase)))
  4365. {
  4366. return;
  4367. }
  4368. while (shiftAudioCodecs.Contains(audioCodecs[0], StringComparer.OrdinalIgnoreCase))
  4369. {
  4370. var removed = shiftAudioCodecs[0];
  4371. audioCodecs.RemoveAt(0);
  4372. audioCodecs.Add(removed);
  4373. }
  4374. }
  4375. private void ShiftVideoCodecsIfNeeded(List<string> videoCodecs, EncodingOptions encodingOptions)
  4376. {
  4377. // Shift hevc/h265 to the end of list if hevc encoding is not allowed.
  4378. if (encodingOptions.AllowHevcEncoding)
  4379. {
  4380. return;
  4381. }
  4382. // No need to shift if there is only one supported video codec.
  4383. if (videoCodecs.Count < 2)
  4384. {
  4385. return;
  4386. }
  4387. var shiftVideoCodecs = new[] { "hevc", "h265" };
  4388. if (videoCodecs.All(i => shiftVideoCodecs.Contains(i, StringComparer.OrdinalIgnoreCase)))
  4389. {
  4390. return;
  4391. }
  4392. while (shiftVideoCodecs.Contains(videoCodecs[0], StringComparer.OrdinalIgnoreCase))
  4393. {
  4394. var removed = shiftVideoCodecs[0];
  4395. videoCodecs.RemoveAt(0);
  4396. videoCodecs.Add(removed);
  4397. }
  4398. }
  4399. private void NormalizeSubtitleEmbed(EncodingJobInfo state)
  4400. {
  4401. if (state.SubtitleStream == null || state.SubtitleDeliveryMethod != SubtitleDeliveryMethod.Embed)
  4402. {
  4403. return;
  4404. }
  4405. // This is tricky to remux in, after converting to dvdsub it's not positioned correctly
  4406. // Therefore, let's just burn it in
  4407. if (string.Equals(state.SubtitleStream.Codec, "DVBSUB", StringComparison.OrdinalIgnoreCase))
  4408. {
  4409. state.SubtitleDeliveryMethod = SubtitleDeliveryMethod.Encode;
  4410. }
  4411. }
  4412. public string GetSubtitleEmbedArguments(EncodingJobInfo state)
  4413. {
  4414. if (state.SubtitleStream == null || state.SubtitleDeliveryMethod != SubtitleDeliveryMethod.Embed)
  4415. {
  4416. return string.Empty;
  4417. }
  4418. var format = state.SupportedSubtitleCodecs.FirstOrDefault();
  4419. string codec;
  4420. if (string.IsNullOrEmpty(format) || string.Equals(format, state.SubtitleStream.Codec, StringComparison.OrdinalIgnoreCase))
  4421. {
  4422. codec = "copy";
  4423. }
  4424. else
  4425. {
  4426. codec = format;
  4427. }
  4428. return " -codec:s:0 " + codec + " -disposition:s:0 default";
  4429. }
  4430. public string GetProgressiveVideoFullCommandLine(EncodingJobInfo state, EncodingOptions encodingOptions, string outputPath, string defaultPreset)
  4431. {
  4432. // Get the output codec name
  4433. var videoCodec = GetVideoEncoder(state, encodingOptions);
  4434. var format = string.Empty;
  4435. var keyFrame = string.Empty;
  4436. if (string.Equals(Path.GetExtension(outputPath), ".mp4", StringComparison.OrdinalIgnoreCase)
  4437. && state.BaseRequest.Context == EncodingContext.Streaming)
  4438. {
  4439. // Comparison: https://github.com/jansmolders86/mediacenterjs/blob/master/lib/transcoding/desktop.js
  4440. format = " -f mp4 -movflags frag_keyframe+empty_moov";
  4441. }
  4442. var threads = GetNumberOfThreads(state, encodingOptions, videoCodec);
  4443. var inputModifier = GetInputModifier(state, encodingOptions);
  4444. return string.Format(
  4445. CultureInfo.InvariantCulture,
  4446. "{0} {1}{2} {3} {4} -map_metadata -1 -map_chapters -1 -threads {5} {6}{7}{8} -y \"{9}\"",
  4447. inputModifier,
  4448. GetInputArgument(state, encodingOptions),
  4449. keyFrame,
  4450. GetMapArgs(state),
  4451. GetProgressiveVideoArguments(state, encodingOptions, videoCodec, defaultPreset),
  4452. threads,
  4453. GetProgressiveVideoAudioArguments(state, encodingOptions),
  4454. GetSubtitleEmbedArguments(state),
  4455. format,
  4456. outputPath).Trim();
  4457. }
  4458. public string GetOutputFFlags(EncodingJobInfo state)
  4459. {
  4460. var flags = new List<string>();
  4461. if (state.GenPtsOutput)
  4462. {
  4463. flags.Add("+genpts");
  4464. }
  4465. if (flags.Count > 0)
  4466. {
  4467. return " -fflags " + string.Join(string.Empty, flags);
  4468. }
  4469. return string.Empty;
  4470. }
  4471. public string GetProgressiveVideoArguments(EncodingJobInfo state, EncodingOptions encodingOptions, string videoCodec, string defaultPreset)
  4472. {
  4473. var args = "-codec:v:0 " + videoCodec;
  4474. if (state.BaseRequest.EnableMpegtsM2TsMode)
  4475. {
  4476. args += " -mpegts_m2ts_mode 1";
  4477. }
  4478. if (IsCopyCodec(videoCodec))
  4479. {
  4480. if (state.VideoStream != null
  4481. && string.Equals(state.OutputContainer, "ts", StringComparison.OrdinalIgnoreCase)
  4482. && !string.Equals(state.VideoStream.NalLengthSize, "0", StringComparison.OrdinalIgnoreCase))
  4483. {
  4484. string bitStreamArgs = GetBitStreamArgs(state.VideoStream);
  4485. if (!string.IsNullOrEmpty(bitStreamArgs))
  4486. {
  4487. args += " " + bitStreamArgs;
  4488. }
  4489. }
  4490. if (state.RunTimeTicks.HasValue && state.BaseRequest.CopyTimestamps)
  4491. {
  4492. args += " -copyts -avoid_negative_ts disabled -start_at_zero";
  4493. }
  4494. if (!state.RunTimeTicks.HasValue)
  4495. {
  4496. args += " -fflags +genpts";
  4497. }
  4498. }
  4499. else
  4500. {
  4501. var keyFrameArg = string.Format(
  4502. CultureInfo.InvariantCulture,
  4503. " -force_key_frames \"expr:gte(t,n_forced*{0})\"",
  4504. 5);
  4505. args += keyFrameArg;
  4506. var hasGraphicalSubs = state.SubtitleStream != null && !state.SubtitleStream.IsTextSubtitleStream && state.SubtitleDeliveryMethod == SubtitleDeliveryMethod.Encode;
  4507. var hasCopyTs = false;
  4508. // video processing filters.
  4509. var videoProcessParam = GetVideoProcessingFilterParam(state, encodingOptions, videoCodec);
  4510. args += videoProcessParam;
  4511. hasCopyTs = videoProcessParam.IndexOf("copyts", StringComparison.OrdinalIgnoreCase) != -1;
  4512. if (state.RunTimeTicks.HasValue && state.BaseRequest.CopyTimestamps)
  4513. {
  4514. if (!hasCopyTs)
  4515. {
  4516. args += " -copyts";
  4517. }
  4518. args += " -avoid_negative_ts disabled";
  4519. if (!(state.SubtitleStream != null && state.SubtitleStream.IsExternal && !state.SubtitleStream.IsTextSubtitleStream))
  4520. {
  4521. args += " -start_at_zero";
  4522. }
  4523. }
  4524. var qualityParam = GetVideoQualityParam(state, videoCodec, encodingOptions, defaultPreset);
  4525. if (!string.IsNullOrEmpty(qualityParam))
  4526. {
  4527. args += " " + qualityParam.Trim();
  4528. }
  4529. }
  4530. if (!string.IsNullOrEmpty(state.OutputVideoSync))
  4531. {
  4532. args += " -vsync " + state.OutputVideoSync;
  4533. }
  4534. args += GetOutputFFlags(state);
  4535. return args;
  4536. }
  4537. public string GetProgressiveVideoAudioArguments(EncodingJobInfo state, EncodingOptions encodingOptions)
  4538. {
  4539. // If the video doesn't have an audio stream, return a default.
  4540. if (state.AudioStream == null && state.VideoStream != null)
  4541. {
  4542. return string.Empty;
  4543. }
  4544. // Get the output codec name
  4545. var codec = GetAudioEncoder(state);
  4546. var args = "-codec:a:0 " + codec;
  4547. if (IsCopyCodec(codec))
  4548. {
  4549. return args;
  4550. }
  4551. // Add the number of audio channels
  4552. var channels = state.OutputAudioChannels;
  4553. if (channels.HasValue)
  4554. {
  4555. args += " -ac " + channels.Value;
  4556. }
  4557. var bitrate = state.OutputAudioBitrate;
  4558. if (bitrate.HasValue)
  4559. {
  4560. args += " -ab " + bitrate.Value.ToString(CultureInfo.InvariantCulture);
  4561. }
  4562. if (state.OutputAudioSampleRate.HasValue)
  4563. {
  4564. args += " -ar " + state.OutputAudioSampleRate.Value.ToString(CultureInfo.InvariantCulture);
  4565. }
  4566. args += GetAudioFilterParam(state, encodingOptions);
  4567. return args;
  4568. }
  4569. public string GetProgressiveAudioFullCommandLine(EncodingJobInfo state, EncodingOptions encodingOptions, string outputPath)
  4570. {
  4571. var audioTranscodeParams = new List<string>();
  4572. var bitrate = state.OutputAudioBitrate;
  4573. if (bitrate.HasValue)
  4574. {
  4575. audioTranscodeParams.Add("-ab " + bitrate.Value.ToString(CultureInfo.InvariantCulture));
  4576. }
  4577. if (state.OutputAudioChannels.HasValue)
  4578. {
  4579. audioTranscodeParams.Add("-ac " + state.OutputAudioChannels.Value.ToString(CultureInfo.InvariantCulture));
  4580. }
  4581. // opus will fail on 44100
  4582. if (!string.Equals(state.OutputAudioCodec, "opus", StringComparison.OrdinalIgnoreCase))
  4583. {
  4584. if (state.OutputAudioSampleRate.HasValue)
  4585. {
  4586. audioTranscodeParams.Add("-ar " + state.OutputAudioSampleRate.Value.ToString(CultureInfo.InvariantCulture));
  4587. }
  4588. }
  4589. var threads = GetNumberOfThreads(state, encodingOptions, null);
  4590. var inputModifier = GetInputModifier(state, encodingOptions);
  4591. return string.Format(
  4592. CultureInfo.InvariantCulture,
  4593. "{0} {1}{7}{8} -threads {2}{3} {4} -id3v2_version 3 -write_id3v1 1{6} -y \"{5}\"",
  4594. inputModifier,
  4595. GetInputArgument(state, encodingOptions),
  4596. threads,
  4597. " -vn",
  4598. string.Join(' ', audioTranscodeParams),
  4599. outputPath,
  4600. string.Empty,
  4601. string.Empty,
  4602. string.Empty).Trim();
  4603. }
  4604. public static bool IsCopyCodec(string codec)
  4605. {
  4606. return string.Equals(codec, "copy", StringComparison.OrdinalIgnoreCase);
  4607. }
  4608. }
  4609. }