EncodingHelper.cs 246 KB

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