2
0

EncodingHelper.cs 179 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239
  1. #nullable disable
  2. #pragma warning disable CS1591
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Globalization;
  6. using System.IO;
  7. using System.Linq;
  8. using System.Text;
  9. using System.Text.RegularExpressions;
  10. using System.Threading;
  11. using Jellyfin.Data.Enums;
  12. using MediaBrowser.Model.Configuration;
  13. using MediaBrowser.Model.Dlna;
  14. using MediaBrowser.Model.Dto;
  15. using MediaBrowser.Model.Entities;
  16. using MediaBrowser.Model.MediaInfo;
  17. namespace MediaBrowser.Controller.MediaEncoding
  18. {
  19. public class EncodingHelper
  20. {
  21. private readonly IMediaEncoder _mediaEncoder;
  22. private readonly ISubtitleEncoder _subtitleEncoder;
  23. private static readonly string[] _videoProfiles = new[]
  24. {
  25. "ConstrainedBaseline",
  26. "Baseline",
  27. "Extended",
  28. "Main",
  29. "High",
  30. "ProgressiveHigh",
  31. "ConstrainedHigh"
  32. };
  33. private static readonly Version _minVersionForCudaOverlay = new Version(4, 4);
  34. public EncodingHelper(
  35. IMediaEncoder mediaEncoder,
  36. ISubtitleEncoder subtitleEncoder)
  37. {
  38. _mediaEncoder = mediaEncoder;
  39. _subtitleEncoder = subtitleEncoder;
  40. }
  41. public string GetH264Encoder(EncodingJobInfo state, EncodingOptions encodingOptions)
  42. => GetH264OrH265Encoder("libx264", "h264", state, encodingOptions);
  43. public string GetH265Encoder(EncodingJobInfo state, EncodingOptions encodingOptions)
  44. => GetH264OrH265Encoder("libx265", "hevc", state, encodingOptions);
  45. private string GetH264OrH265Encoder(string defaultEncoder, string hwEncoder, EncodingJobInfo state, EncodingOptions encodingOptions)
  46. {
  47. // Only use alternative encoders for video files.
  48. // When using concat with folder rips, if the mfx session fails to initialize, ffmpeg will be stuck retrying and will not exit gracefully
  49. // Since transcoding of folder rips is experimental anyway, it's not worth adding additional variables such as this.
  50. if (state.VideoType == VideoType.VideoFile)
  51. {
  52. var hwType = encodingOptions.HardwareAccelerationType;
  53. var codecMap = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
  54. {
  55. { "qsv", hwEncoder + "_qsv" },
  56. { hwEncoder + "_qsv", hwEncoder + "_qsv" },
  57. { "nvenc", hwEncoder + "_nvenc" },
  58. { "amf", hwEncoder + "_amf" },
  59. { "omx", hwEncoder + "_omx" },
  60. { hwEncoder + "_v4l2m2m", hwEncoder + "_v4l2m2m" },
  61. { "mediacodec", hwEncoder + "_mediacodec" },
  62. { "vaapi", hwEncoder + "_vaapi" },
  63. { "videotoolbox", hwEncoder + "_videotoolbox" }
  64. };
  65. if (!string.IsNullOrEmpty(hwType)
  66. && encodingOptions.EnableHardwareEncoding
  67. && codecMap.ContainsKey(hwType))
  68. {
  69. var preferredEncoder = codecMap[hwType];
  70. if (_mediaEncoder.SupportsEncoder(preferredEncoder))
  71. {
  72. return preferredEncoder;
  73. }
  74. }
  75. }
  76. return defaultEncoder;
  77. }
  78. private bool IsVaapiSupported(EncodingJobInfo state)
  79. {
  80. var videoStream = state.VideoStream;
  81. // vaapi will throw an error with this input
  82. // [vaapi @ 0x7faed8000960] No VAAPI support for codec mpeg4 profile -99.
  83. if (string.Equals(videoStream?.Codec, "mpeg4", StringComparison.OrdinalIgnoreCase))
  84. {
  85. return false;
  86. }
  87. return _mediaEncoder.SupportsHwaccel("vaapi");
  88. }
  89. private bool IsCudaSupported()
  90. {
  91. return _mediaEncoder.SupportsHwaccel("cuda")
  92. && _mediaEncoder.SupportsFilter("scale_cuda")
  93. && _mediaEncoder.SupportsFilter("yadif_cuda")
  94. && _mediaEncoder.SupportsFilter("hwupload_cuda");
  95. }
  96. private bool IsOpenclTonemappingSupported(EncodingJobInfo state, EncodingOptions options)
  97. {
  98. var videoStream = state.VideoStream;
  99. if (videoStream == null)
  100. {
  101. return false;
  102. }
  103. return options.EnableTonemapping
  104. && (string.Equals(videoStream.ColorTransfer, "smpte2084", StringComparison.OrdinalIgnoreCase)
  105. || string.Equals(videoStream.ColorTransfer, "arib-std-b67", StringComparison.OrdinalIgnoreCase))
  106. && IsColorDepth10(state)
  107. && _mediaEncoder.SupportsHwaccel("opencl")
  108. && _mediaEncoder.SupportsFilter("tonemap_opencl");
  109. }
  110. private bool IsCudaTonemappingSupported(EncodingJobInfo state, EncodingOptions options)
  111. {
  112. var videoStream = state.VideoStream;
  113. if (videoStream == null)
  114. {
  115. return false;
  116. }
  117. return options.EnableTonemapping
  118. && (string.Equals(videoStream.ColorTransfer, "smpte2084", StringComparison.OrdinalIgnoreCase)
  119. || string.Equals(videoStream.ColorTransfer, "arib-std-b67", StringComparison.OrdinalIgnoreCase))
  120. && IsColorDepth10(state)
  121. && _mediaEncoder.SupportsHwaccel("cuda")
  122. && _mediaEncoder.SupportsFilterWithOption(FilterOptionType.TonemapCudaName);
  123. }
  124. private bool IsVppTonemappingSupported(EncodingJobInfo state, EncodingOptions options)
  125. {
  126. var videoStream = state.VideoStream;
  127. if (videoStream == null)
  128. {
  129. // Remote stream doesn't have media info, disable vpp tonemapping.
  130. return false;
  131. }
  132. var codec = videoStream.Codec;
  133. if (string.Equals(options.HardwareAccelerationType, "vaapi", StringComparison.OrdinalIgnoreCase))
  134. {
  135. // Limited to HEVC for now since the filter doesn't accept master data from VP9.
  136. return options.EnableVppTonemapping
  137. && string.Equals(videoStream.ColorTransfer, "smpte2084", StringComparison.OrdinalIgnoreCase)
  138. && IsColorDepth10(state)
  139. && string.Equals(codec, "hevc", StringComparison.OrdinalIgnoreCase)
  140. && _mediaEncoder.SupportsHwaccel("vaapi")
  141. && _mediaEncoder.SupportsFilter("tonemap_vaapi");
  142. }
  143. // Hybrid VPP tonemapping for QSV with VAAPI
  144. if (OperatingSystem.IsLinux() && string.Equals(options.HardwareAccelerationType, "qsv", StringComparison.OrdinalIgnoreCase))
  145. {
  146. // Limited to HEVC for now since the filter doesn't accept master data from VP9.
  147. return options.EnableVppTonemapping
  148. && string.Equals(videoStream.ColorTransfer, "smpte2084", StringComparison.OrdinalIgnoreCase)
  149. && IsColorDepth10(state)
  150. && string.Equals(codec, "hevc", StringComparison.OrdinalIgnoreCase)
  151. && _mediaEncoder.SupportsHwaccel("vaapi")
  152. && _mediaEncoder.SupportsFilter("tonemap_vaapi")
  153. && _mediaEncoder.SupportsHwaccel("qsv");
  154. }
  155. // Native VPP tonemapping may come to QSV in the future.
  156. return false;
  157. }
  158. /// <summary>
  159. /// Gets the name of the output video codec.
  160. /// </summary>
  161. /// <param name="state">Encording state.</param>
  162. /// <param name="encodingOptions">Encoding options.</param>
  163. /// <returns>Encoder string.</returns>
  164. public string GetVideoEncoder(EncodingJobInfo state, EncodingOptions encodingOptions)
  165. {
  166. var codec = state.OutputVideoCodec;
  167. if (!string.IsNullOrEmpty(codec))
  168. {
  169. if (string.Equals(codec, "h265", StringComparison.OrdinalIgnoreCase)
  170. || string.Equals(codec, "hevc", StringComparison.OrdinalIgnoreCase))
  171. {
  172. return GetH265Encoder(state, encodingOptions);
  173. }
  174. if (string.Equals(codec, "h264", StringComparison.OrdinalIgnoreCase))
  175. {
  176. return GetH264Encoder(state, encodingOptions);
  177. }
  178. if (string.Equals(codec, "vp8", StringComparison.OrdinalIgnoreCase)
  179. || string.Equals(codec, "vpx", StringComparison.OrdinalIgnoreCase))
  180. {
  181. return "libvpx";
  182. }
  183. if (string.Equals(codec, "vp9", StringComparison.OrdinalIgnoreCase))
  184. {
  185. return "libvpx-vp9";
  186. }
  187. if (string.Equals(codec, "wmv", StringComparison.OrdinalIgnoreCase))
  188. {
  189. return "wmv2";
  190. }
  191. if (string.Equals(codec, "theora", StringComparison.OrdinalIgnoreCase))
  192. {
  193. return "libtheora";
  194. }
  195. return codec.ToLowerInvariant();
  196. }
  197. return "copy";
  198. }
  199. /// <summary>
  200. /// Gets the user agent param.
  201. /// </summary>
  202. /// <param name="state">The state.</param>
  203. /// <returns>System.String.</returns>
  204. public string GetUserAgentParam(EncodingJobInfo state)
  205. {
  206. if (state.RemoteHttpHeaders.TryGetValue("User-Agent", out string useragent))
  207. {
  208. return "-user_agent \"" + useragent + "\"";
  209. }
  210. return string.Empty;
  211. }
  212. public static string GetInputFormat(string container)
  213. {
  214. if (string.IsNullOrEmpty(container))
  215. {
  216. return null;
  217. }
  218. container = container.Replace("mkv", "matroska", StringComparison.OrdinalIgnoreCase);
  219. if (string.Equals(container, "ts", StringComparison.OrdinalIgnoreCase))
  220. {
  221. return "mpegts";
  222. }
  223. // For these need to find out the ffmpeg names
  224. if (string.Equals(container, "m2ts", StringComparison.OrdinalIgnoreCase))
  225. {
  226. return null;
  227. }
  228. if (string.Equals(container, "wmv", StringComparison.OrdinalIgnoreCase))
  229. {
  230. return null;
  231. }
  232. if (string.Equals(container, "mts", StringComparison.OrdinalIgnoreCase))
  233. {
  234. return null;
  235. }
  236. if (string.Equals(container, "vob", StringComparison.OrdinalIgnoreCase))
  237. {
  238. return null;
  239. }
  240. if (string.Equals(container, "mpg", StringComparison.OrdinalIgnoreCase))
  241. {
  242. return null;
  243. }
  244. if (string.Equals(container, "mpeg", StringComparison.OrdinalIgnoreCase))
  245. {
  246. return null;
  247. }
  248. if (string.Equals(container, "rec", StringComparison.OrdinalIgnoreCase))
  249. {
  250. return null;
  251. }
  252. if (string.Equals(container, "dvr-ms", StringComparison.OrdinalIgnoreCase))
  253. {
  254. return null;
  255. }
  256. if (string.Equals(container, "ogm", StringComparison.OrdinalIgnoreCase))
  257. {
  258. return null;
  259. }
  260. if (string.Equals(container, "divx", StringComparison.OrdinalIgnoreCase))
  261. {
  262. return null;
  263. }
  264. if (string.Equals(container, "tp", StringComparison.OrdinalIgnoreCase))
  265. {
  266. return null;
  267. }
  268. if (string.Equals(container, "rmvb", StringComparison.OrdinalIgnoreCase))
  269. {
  270. return null;
  271. }
  272. if (string.Equals(container, "rtp", StringComparison.OrdinalIgnoreCase))
  273. {
  274. return null;
  275. }
  276. // Seeing reported failures here, not sure yet if this is related to specifying input format
  277. if (string.Equals(container, "m4v", StringComparison.OrdinalIgnoreCase))
  278. {
  279. return null;
  280. }
  281. // obviously don't do this for strm files
  282. if (string.Equals(container, "strm", StringComparison.OrdinalIgnoreCase))
  283. {
  284. return null;
  285. }
  286. // ISO files don't have an ffmpeg format
  287. if (string.Equals(container, "iso", StringComparison.OrdinalIgnoreCase))
  288. {
  289. return null;
  290. }
  291. return container;
  292. }
  293. /// <summary>
  294. /// Gets decoder from a codec.
  295. /// </summary>
  296. /// <param name="codec">Codec to use.</param>
  297. /// <returns>Decoder string.</returns>
  298. public string GetDecoderFromCodec(string codec)
  299. {
  300. // For these need to find out the ffmpeg names
  301. if (string.Equals(codec, "mp2", StringComparison.OrdinalIgnoreCase))
  302. {
  303. return null;
  304. }
  305. if (string.Equals(codec, "aac_latm", StringComparison.OrdinalIgnoreCase))
  306. {
  307. return null;
  308. }
  309. if (string.Equals(codec, "eac3", StringComparison.OrdinalIgnoreCase))
  310. {
  311. return null;
  312. }
  313. if (_mediaEncoder.SupportsDecoder(codec))
  314. {
  315. return codec;
  316. }
  317. return null;
  318. }
  319. /// <summary>
  320. /// Infers the audio codec based on the url.
  321. /// </summary>
  322. /// <param name="container">Container to use.</param>
  323. /// <returns>Codec string.</returns>
  324. public string InferAudioCodec(string container)
  325. {
  326. var ext = "." + (container ?? string.Empty);
  327. if (string.Equals(ext, ".mp3", StringComparison.OrdinalIgnoreCase))
  328. {
  329. return "mp3";
  330. }
  331. if (string.Equals(ext, ".aac", StringComparison.OrdinalIgnoreCase))
  332. {
  333. return "aac";
  334. }
  335. if (string.Equals(ext, ".wma", StringComparison.OrdinalIgnoreCase))
  336. {
  337. return "wma";
  338. }
  339. if (string.Equals(ext, ".ogg", StringComparison.OrdinalIgnoreCase))
  340. {
  341. return "vorbis";
  342. }
  343. if (string.Equals(ext, ".oga", StringComparison.OrdinalIgnoreCase))
  344. {
  345. return "vorbis";
  346. }
  347. if (string.Equals(ext, ".ogv", StringComparison.OrdinalIgnoreCase))
  348. {
  349. return "vorbis";
  350. }
  351. if (string.Equals(ext, ".webm", StringComparison.OrdinalIgnoreCase))
  352. {
  353. return "vorbis";
  354. }
  355. if (string.Equals(ext, ".webma", StringComparison.OrdinalIgnoreCase))
  356. {
  357. return "vorbis";
  358. }
  359. return "copy";
  360. }
  361. /// <summary>
  362. /// Infers the video codec.
  363. /// </summary>
  364. /// <param name="url">The URL.</param>
  365. /// <returns>System.Nullable{VideoCodecs}.</returns>
  366. public string InferVideoCodec(string url)
  367. {
  368. var ext = Path.GetExtension(url);
  369. if (string.Equals(ext, ".asf", StringComparison.OrdinalIgnoreCase))
  370. {
  371. return "wmv";
  372. }
  373. if (string.Equals(ext, ".webm", StringComparison.OrdinalIgnoreCase))
  374. {
  375. // TODO: this may not always mean VP8, as the codec ages
  376. return "vp8";
  377. }
  378. if (string.Equals(ext, ".ogg", StringComparison.OrdinalIgnoreCase) || string.Equals(ext, ".ogv", StringComparison.OrdinalIgnoreCase))
  379. {
  380. return "theora";
  381. }
  382. if (string.Equals(ext, ".m3u8", StringComparison.OrdinalIgnoreCase) || string.Equals(ext, ".ts", StringComparison.OrdinalIgnoreCase))
  383. {
  384. return "h264";
  385. }
  386. return "copy";
  387. }
  388. public int GetVideoProfileScore(string profile)
  389. {
  390. // strip spaces because they may be stripped out on the query string
  391. profile = profile.Replace(" ", string.Empty, StringComparison.Ordinal);
  392. return Array.FindIndex(_videoProfiles, x => string.Equals(x, profile, StringComparison.OrdinalIgnoreCase));
  393. }
  394. public string GetInputPathArgument(EncodingJobInfo state)
  395. {
  396. var mediaPath = state.MediaPath ?? string.Empty;
  397. return _mediaEncoder.GetInputArgument(mediaPath, state.MediaSource);
  398. }
  399. /// <summary>
  400. /// Gets the audio encoder.
  401. /// </summary>
  402. /// <param name="state">The state.</param>
  403. /// <returns>System.String.</returns>
  404. public string GetAudioEncoder(EncodingJobInfo state)
  405. {
  406. var codec = state.OutputAudioCodec;
  407. if (string.Equals(codec, "aac", StringComparison.OrdinalIgnoreCase))
  408. {
  409. // Use libfdk_aac for better audio quality if using custom build of FFmpeg which has fdk_aac support
  410. if (_mediaEncoder.SupportsEncoder("libfdk_aac"))
  411. {
  412. return "libfdk_aac";
  413. }
  414. return "aac";
  415. }
  416. if (string.Equals(codec, "mp3", StringComparison.OrdinalIgnoreCase))
  417. {
  418. return "libmp3lame";
  419. }
  420. if (string.Equals(codec, "vorbis", StringComparison.OrdinalIgnoreCase))
  421. {
  422. return "libvorbis";
  423. }
  424. if (string.Equals(codec, "wma", StringComparison.OrdinalIgnoreCase))
  425. {
  426. return "wmav2";
  427. }
  428. if (string.Equals(codec, "opus", StringComparison.OrdinalIgnoreCase))
  429. {
  430. return "libopus";
  431. }
  432. if (string.Equals(codec, "flac", StringComparison.OrdinalIgnoreCase))
  433. {
  434. // flac is experimental in mp4 muxer
  435. return "flac -strict -2";
  436. }
  437. return codec.ToLowerInvariant();
  438. }
  439. /// <summary>
  440. /// Gets the input argument.
  441. /// </summary>
  442. /// <param name="state">Encoding state.</param>
  443. /// <param name="options">Encoding options.</param>
  444. /// <returns>Input arguments.</returns>
  445. public string GetInputArgument(EncodingJobInfo state, EncodingOptions options)
  446. {
  447. var arg = new StringBuilder();
  448. var videoDecoder = GetHardwareAcceleratedVideoDecoder(state, options) ?? string.Empty;
  449. var outputVideoCodec = GetVideoEncoder(state, options) ?? string.Empty;
  450. var isWindows = OperatingSystem.IsWindows();
  451. var isLinux = OperatingSystem.IsLinux();
  452. var isMacOS = OperatingSystem.IsMacOS();
  453. #pragma warning disable CA1508 // Defaults to string.Empty
  454. var isSwDecoder = string.IsNullOrEmpty(videoDecoder);
  455. #pragma warning restore CA1508
  456. var isD3d11vaDecoder = videoDecoder.IndexOf("d3d11va", StringComparison.OrdinalIgnoreCase) != -1;
  457. var isVaapiDecoder = videoDecoder.IndexOf("vaapi", StringComparison.OrdinalIgnoreCase) != -1;
  458. var isVaapiEncoder = outputVideoCodec.IndexOf("vaapi", StringComparison.OrdinalIgnoreCase) != -1;
  459. var isQsvDecoder = videoDecoder.IndexOf("qsv", StringComparison.OrdinalIgnoreCase) != -1;
  460. var isQsvEncoder = outputVideoCodec.IndexOf("qsv", StringComparison.OrdinalIgnoreCase) != -1;
  461. var isNvdecDecoder = videoDecoder.Contains("cuda", StringComparison.OrdinalIgnoreCase);
  462. var isCuvidHevcDecoder = videoDecoder.Contains("hevc_cuvid", StringComparison.OrdinalIgnoreCase);
  463. var isCuvidVp9Decoder = videoDecoder.Contains("vp9_cuvid", StringComparison.OrdinalIgnoreCase);
  464. var isOpenclTonemappingSupported = IsOpenclTonemappingSupported(state, options);
  465. var isVppTonemappingSupported = IsVppTonemappingSupported(state, options);
  466. var isCudaTonemappingSupported = IsCudaTonemappingSupported(state, options);
  467. if (!IsCopyCodec(outputVideoCodec))
  468. {
  469. if (state.IsVideoRequest
  470. && _mediaEncoder.SupportsHwaccel("vaapi")
  471. && string.Equals(options.HardwareAccelerationType, "vaapi", StringComparison.OrdinalIgnoreCase))
  472. {
  473. if (isVaapiDecoder)
  474. {
  475. if (isOpenclTonemappingSupported && !isVppTonemappingSupported)
  476. {
  477. arg.Append("-init_hw_device vaapi=va:")
  478. .Append(options.VaapiDevice)
  479. .Append(" -init_hw_device opencl=ocl@va ")
  480. .Append("-hwaccel_device va ")
  481. .Append("-hwaccel_output_format vaapi ")
  482. .Append("-filter_hw_device ocl ");
  483. }
  484. else
  485. {
  486. arg.Append("-hwaccel_output_format vaapi ")
  487. .Append("-vaapi_device ")
  488. .Append(options.VaapiDevice)
  489. .Append(' ');
  490. }
  491. }
  492. else if (!isVaapiDecoder && isVaapiEncoder)
  493. {
  494. arg.Append("-vaapi_device ")
  495. .Append(options.VaapiDevice)
  496. .Append(' ');
  497. }
  498. arg.Append("-autorotate 0 ");
  499. }
  500. if (state.IsVideoRequest
  501. && string.Equals(options.HardwareAccelerationType, "qsv", StringComparison.OrdinalIgnoreCase))
  502. {
  503. var hasGraphicalSubs = state.SubtitleStream != null && !state.SubtitleStream.IsTextSubtitleStream && state.SubtitleDeliveryMethod == SubtitleDeliveryMethod.Encode;
  504. if (isQsvEncoder)
  505. {
  506. if (isQsvDecoder)
  507. {
  508. if (isLinux)
  509. {
  510. if (hasGraphicalSubs)
  511. {
  512. arg.Append("-init_hw_device qsv=hw -filter_hw_device hw ");
  513. }
  514. else
  515. {
  516. arg.Append("-hwaccel qsv ");
  517. }
  518. }
  519. if (isWindows)
  520. {
  521. arg.Append("-hwaccel qsv ");
  522. }
  523. }
  524. // While using SW decoder
  525. else if (isSwDecoder)
  526. {
  527. arg.Append("-init_hw_device qsv=hw -filter_hw_device hw ");
  528. }
  529. // Hybrid VPP tonemapping with VAAPI
  530. else if (isVaapiDecoder && isVppTonemappingSupported)
  531. {
  532. arg.Append("-init_hw_device vaapi=va:")
  533. .Append(options.VaapiDevice)
  534. .Append(" -init_hw_device qsv@va ")
  535. .Append("-hwaccel_output_format vaapi ");
  536. }
  537. arg.Append("-autorotate 0 ");
  538. }
  539. }
  540. if (state.IsVideoRequest
  541. && string.Equals(options.HardwareAccelerationType, "nvenc", StringComparison.OrdinalIgnoreCase)
  542. && isNvdecDecoder)
  543. {
  544. // Fix for 'No decoder surfaces left' error. https://trac.ffmpeg.org/ticket/7562
  545. arg.Append("-hwaccel_output_format cuda -extra_hw_frames 3 -autorotate 0 ");
  546. }
  547. if (state.IsVideoRequest
  548. && string.Equals(options.HardwareAccelerationType, "nvenc", StringComparison.OrdinalIgnoreCase)
  549. && (isNvdecDecoder || isCuvidHevcDecoder || isCuvidVp9Decoder || isSwDecoder))
  550. {
  551. if (!isCudaTonemappingSupported && isOpenclTonemappingSupported)
  552. {
  553. arg.Append("-init_hw_device opencl=ocl:")
  554. .Append(options.OpenclDevice)
  555. .Append(" -filter_hw_device ocl ");
  556. }
  557. }
  558. if (state.IsVideoRequest
  559. && string.Equals(options.HardwareAccelerationType, "amf", StringComparison.OrdinalIgnoreCase)
  560. && (isD3d11vaDecoder || isSwDecoder))
  561. {
  562. if (isOpenclTonemappingSupported)
  563. {
  564. arg.Append("-init_hw_device opencl=ocl:")
  565. .Append(options.OpenclDevice)
  566. .Append(" -filter_hw_device ocl ");
  567. }
  568. }
  569. if (state.IsVideoRequest
  570. && string.Equals(options.HardwareAccelerationType, "videotoolbox", StringComparison.OrdinalIgnoreCase))
  571. {
  572. arg.Append("-hwaccel videotoolbox ");
  573. }
  574. }
  575. arg.Append("-i ")
  576. .Append(GetInputPathArgument(state));
  577. if (state.SubtitleStream != null
  578. && state.SubtitleDeliveryMethod == SubtitleDeliveryMethod.Encode
  579. && state.SubtitleStream.IsExternal && !state.SubtitleStream.IsTextSubtitleStream)
  580. {
  581. var subtitlePath = state.SubtitleStream.Path;
  582. if (string.Equals(Path.GetExtension(subtitlePath), ".sub", StringComparison.OrdinalIgnoreCase))
  583. {
  584. var idxFile = Path.ChangeExtension(subtitlePath, ".idx");
  585. if (File.Exists(idxFile))
  586. {
  587. subtitlePath = idxFile;
  588. }
  589. }
  590. arg.Append(" -i \"").Append(subtitlePath).Append('\"');
  591. }
  592. if (state.AudioStream != null && state.AudioStream.IsExternal)
  593. {
  594. arg.Append(" -i \"").Append(state.AudioStream.Path).Append('"');
  595. }
  596. return arg.ToString();
  597. }
  598. /// <summary>
  599. /// Determines whether the specified stream is H264.
  600. /// </summary>
  601. /// <param name="stream">The stream.</param>
  602. /// <returns><c>true</c> if the specified stream is H264; otherwise, <c>false</c>.</returns>
  603. public static bool IsH264(MediaStream stream)
  604. {
  605. var codec = stream.Codec ?? string.Empty;
  606. return codec.IndexOf("264", StringComparison.OrdinalIgnoreCase) != -1
  607. || codec.IndexOf("avc", StringComparison.OrdinalIgnoreCase) != -1;
  608. }
  609. public static bool IsH265(MediaStream stream)
  610. {
  611. var codec = stream.Codec ?? string.Empty;
  612. return codec.IndexOf("265", StringComparison.OrdinalIgnoreCase) != -1
  613. || codec.IndexOf("hevc", StringComparison.OrdinalIgnoreCase) != -1;
  614. }
  615. public static bool IsAAC(MediaStream stream)
  616. {
  617. var codec = stream.Codec ?? string.Empty;
  618. return codec.IndexOf("aac", StringComparison.OrdinalIgnoreCase) != -1;
  619. }
  620. public static string GetBitStreamArgs(MediaStream stream)
  621. {
  622. // TODO This is auto inserted into the mpegts mux so it might not be needed.
  623. // https://www.ffmpeg.org/ffmpeg-bitstream-filters.html#h264_005fmp4toannexb
  624. if (IsH264(stream))
  625. {
  626. return "-bsf:v h264_mp4toannexb";
  627. }
  628. else if (IsH265(stream))
  629. {
  630. return "-bsf:v hevc_mp4toannexb";
  631. }
  632. else if (IsAAC(stream))
  633. {
  634. // Convert adts header(mpegts) to asc header(mp4).
  635. return "-bsf:a aac_adtstoasc";
  636. }
  637. else
  638. {
  639. return null;
  640. }
  641. }
  642. public static string GetAudioBitStreamArguments(EncodingJobInfo state, string segmentContainer, string mediaSourceContainer)
  643. {
  644. var bitStreamArgs = string.Empty;
  645. var segmentFormat = GetSegmentFileExtension(segmentContainer).TrimStart('.');
  646. // Apply aac_adtstoasc bitstream filter when media source is in mpegts.
  647. if (string.Equals(segmentFormat, "mp4", StringComparison.OrdinalIgnoreCase)
  648. && (string.Equals(mediaSourceContainer, "mpegts", StringComparison.OrdinalIgnoreCase)
  649. || string.Equals(mediaSourceContainer, "hls", StringComparison.OrdinalIgnoreCase)))
  650. {
  651. bitStreamArgs = GetBitStreamArgs(state.AudioStream);
  652. bitStreamArgs = string.IsNullOrEmpty(bitStreamArgs) ? string.Empty : " " + bitStreamArgs;
  653. }
  654. return bitStreamArgs;
  655. }
  656. public static string GetSegmentFileExtension(string segmentContainer)
  657. {
  658. if (!string.IsNullOrWhiteSpace(segmentContainer))
  659. {
  660. return "." + segmentContainer;
  661. }
  662. return ".ts";
  663. }
  664. public string GetVideoBitrateParam(EncodingJobInfo state, string videoCodec)
  665. {
  666. if (state.OutputVideoBitrate == null)
  667. {
  668. return string.Empty;
  669. }
  670. int bitrate = state.OutputVideoBitrate.Value;
  671. // Currently use the same buffer size for all encoders
  672. int bufsize = bitrate * 2;
  673. if (string.Equals(videoCodec, "libvpx", StringComparison.OrdinalIgnoreCase)
  674. || string.Equals(videoCodec, "libvpx-vp9", StringComparison.OrdinalIgnoreCase))
  675. {
  676. // When crf is used with vpx, b:v becomes a max rate
  677. // https://trac.ffmpeg.org/wiki/Encode/VP8
  678. // https://trac.ffmpeg.org/wiki/Encode/VP9
  679. return FormattableString.Invariant($" -maxrate:v {bitrate} -bufsize:v {bufsize} -b:v {bitrate}");
  680. }
  681. if (string.Equals(videoCodec, "msmpeg4", StringComparison.OrdinalIgnoreCase))
  682. {
  683. return FormattableString.Invariant($" -b:v {bitrate}");
  684. }
  685. if (string.Equals(videoCodec, "libx264", StringComparison.OrdinalIgnoreCase)
  686. || string.Equals(videoCodec, "libx265", StringComparison.OrdinalIgnoreCase))
  687. {
  688. return FormattableString.Invariant($" -maxrate {bitrate} -bufsize {bufsize}");
  689. }
  690. return FormattableString.Invariant($" -b:v {bitrate} -maxrate {bitrate} -bufsize {bufsize}");
  691. }
  692. public static string NormalizeTranscodingLevel(EncodingJobInfo state, string level)
  693. {
  694. if (double.TryParse(level, NumberStyles.Any, CultureInfo.InvariantCulture, out double requestLevel))
  695. {
  696. if (string.Equals(state.ActualOutputVideoCodec, "hevc", StringComparison.OrdinalIgnoreCase)
  697. || string.Equals(state.ActualOutputVideoCodec, "h265", StringComparison.OrdinalIgnoreCase))
  698. {
  699. // Transcode to level 5.0 and lower for maximum compatibility.
  700. // Level 5.0 is suitable for up to 4k 30fps hevc encoding, otherwise let the encoder to handle it.
  701. // https://en.wikipedia.org/wiki/High_Efficiency_Video_Coding_tiers_and_levels
  702. // MaxLumaSampleRate = 3840*2160*30 = 248832000 < 267386880.
  703. if (requestLevel >= 150)
  704. {
  705. return "150";
  706. }
  707. }
  708. else if (string.Equals(state.ActualOutputVideoCodec, "h264", StringComparison.OrdinalIgnoreCase))
  709. {
  710. // Clients may direct play higher than level 41, but there's no reason to transcode higher.
  711. if (requestLevel >= 41)
  712. {
  713. return "41";
  714. }
  715. }
  716. }
  717. return level;
  718. }
  719. /// <summary>
  720. /// Gets the text subtitle param.
  721. /// </summary>
  722. /// <param name="state">The state.</param>
  723. /// <returns>System.String.</returns>
  724. public string GetTextSubtitleParam(EncodingJobInfo state)
  725. {
  726. var seconds = Math.Round(TimeSpan.FromTicks(state.StartTimeTicks ?? 0).TotalSeconds);
  727. // hls always copies timestamps
  728. var setPtsParam = state.CopyTimestamps || state.TranscodingType != TranscodingJobType.Progressive
  729. ? string.Empty
  730. : string.Format(CultureInfo.InvariantCulture, ",setpts=PTS -{0}/TB", seconds);
  731. // TODO
  732. // var fallbackFontPath = Path.Combine(_appPaths.ProgramDataPath, "fonts", "DroidSansFallback.ttf");
  733. // string fallbackFontParam = string.Empty;
  734. // if (!File.Exists(fallbackFontPath))
  735. // {
  736. // _fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(fallbackFontPath));
  737. // using (var stream = _assemblyInfo.GetManifestResourceStream(GetType(), GetType().Namespace + ".DroidSansFallback.ttf"))
  738. // {
  739. // using (var fileStream = new FileStream(fallbackFontPath, FileMode.Create, FileAccess.Write, FileShare.Read))
  740. // {
  741. // stream.CopyTo(fileStream);
  742. // }
  743. // }
  744. // }
  745. // fallbackFontParam = string.Format(CultureInfo.InvariantCulture, ":force_style='FontName=Droid Sans Fallback':fontsdir='{0}'", _mediaEncoder.EscapeSubtitleFilterPath(_fileSystem.GetDirectoryName(fallbackFontPath)));
  746. if (state.SubtitleStream.IsExternal)
  747. {
  748. var subtitlePath = state.SubtitleStream.Path;
  749. var charsetParam = string.Empty;
  750. if (!string.IsNullOrEmpty(state.SubtitleStream.Language))
  751. {
  752. var charenc = _subtitleEncoder.GetSubtitleFileCharacterSet(
  753. subtitlePath,
  754. state.SubtitleStream.Language,
  755. state.MediaSource.Protocol,
  756. CancellationToken.None).GetAwaiter().GetResult();
  757. if (!string.IsNullOrEmpty(charenc))
  758. {
  759. charsetParam = ":charenc=" + charenc;
  760. }
  761. }
  762. // TODO: Perhaps also use original_size=1920x800 ??
  763. return string.Format(
  764. CultureInfo.InvariantCulture,
  765. "subtitles=filename='{0}'{1}{2}",
  766. _mediaEncoder.EscapeSubtitleFilterPath(subtitlePath),
  767. charsetParam,
  768. // fallbackFontParam,
  769. setPtsParam);
  770. }
  771. var mediaPath = state.MediaPath ?? string.Empty;
  772. return string.Format(
  773. CultureInfo.InvariantCulture,
  774. "subtitles='{0}:si={1}'{2}",
  775. _mediaEncoder.EscapeSubtitleFilterPath(mediaPath),
  776. state.InternalSubtitleStreamOffset.ToString(CultureInfo.InvariantCulture),
  777. // fallbackFontParam,
  778. setPtsParam);
  779. }
  780. public double? GetFramerateParam(EncodingJobInfo state)
  781. {
  782. var request = state.BaseRequest;
  783. if (request.Framerate.HasValue)
  784. {
  785. return request.Framerate.Value;
  786. }
  787. var maxrate = request.MaxFramerate;
  788. if (maxrate.HasValue && state.VideoStream != null)
  789. {
  790. var contentRate = state.VideoStream.AverageFrameRate ?? state.VideoStream.RealFrameRate;
  791. if (contentRate.HasValue && contentRate.Value > maxrate.Value)
  792. {
  793. return maxrate;
  794. }
  795. }
  796. return null;
  797. }
  798. public string GetHlsVideoKeyFrameArguments(
  799. EncodingJobInfo state,
  800. string codec,
  801. int segmentLength,
  802. bool isEventPlaylist,
  803. int? startNumber)
  804. {
  805. var args = string.Empty;
  806. var gopArg = string.Empty;
  807. var keyFrameArg = string.Empty;
  808. if (isEventPlaylist)
  809. {
  810. keyFrameArg = string.Format(
  811. CultureInfo.InvariantCulture,
  812. " -force_key_frames:0 \"expr:gte(t,n_forced*{0})\"",
  813. segmentLength);
  814. }
  815. else if (startNumber.HasValue)
  816. {
  817. keyFrameArg = string.Format(
  818. CultureInfo.InvariantCulture,
  819. " -force_key_frames:0 \"expr:gte(t,{0}+n_forced*{1})\"",
  820. startNumber.Value * segmentLength,
  821. segmentLength);
  822. }
  823. var framerate = state.VideoStream?.RealFrameRate;
  824. if (framerate.HasValue)
  825. {
  826. // This is to make sure keyframe interval is limited to our segment,
  827. // as forcing keyframes is not enough.
  828. // Example: we encoded half of desired length, then codec detected
  829. // scene cut and inserted a keyframe; next forced keyframe would
  830. // be created outside of segment, which breaks seeking.
  831. // -sc_threshold 0 is used to prevent the hardware encoder from post processing to break the set keyframe.
  832. gopArg = string.Format(
  833. CultureInfo.InvariantCulture,
  834. " -g:v:0 {0} -keyint_min:v:0 {0} -sc_threshold:v:0 0",
  835. Math.Ceiling(segmentLength * framerate.Value));
  836. }
  837. // Unable to force key frames using these encoders, set key frames by GOP.
  838. if (string.Equals(codec, "h264_qsv", StringComparison.OrdinalIgnoreCase)
  839. || string.Equals(codec, "h264_nvenc", StringComparison.OrdinalIgnoreCase)
  840. || string.Equals(codec, "h264_amf", StringComparison.OrdinalIgnoreCase)
  841. || string.Equals(codec, "hevc_qsv", StringComparison.OrdinalIgnoreCase)
  842. || string.Equals(codec, "hevc_nvenc", StringComparison.OrdinalIgnoreCase)
  843. || string.Equals(codec, "hevc_amf", StringComparison.OrdinalIgnoreCase))
  844. {
  845. args += gopArg;
  846. }
  847. else if (string.Equals(codec, "libx264", StringComparison.OrdinalIgnoreCase)
  848. || string.Equals(codec, "libx265", StringComparison.OrdinalIgnoreCase)
  849. || string.Equals(codec, "h264_vaapi", StringComparison.OrdinalIgnoreCase)
  850. || string.Equals(codec, "hevc_vaapi", StringComparison.OrdinalIgnoreCase))
  851. {
  852. args += " " + keyFrameArg;
  853. }
  854. else
  855. {
  856. args += " " + keyFrameArg + gopArg;
  857. }
  858. return args;
  859. }
  860. /// <summary>
  861. /// Gets the video bitrate to specify on the command line.
  862. /// </summary>
  863. /// <param name="state">Encoding state.</param>
  864. /// <param name="videoEncoder">Video encoder to use.</param>
  865. /// <param name="encodingOptions">Encoding options.</param>
  866. /// <param name="defaultPreset">Default present to use for encoding.</param>
  867. /// <returns>Video bitrate.</returns>
  868. public string GetVideoQualityParam(EncodingJobInfo state, string videoEncoder, EncodingOptions encodingOptions, string defaultPreset)
  869. {
  870. var param = string.Empty;
  871. if (!string.Equals(videoEncoder, "h264_omx", StringComparison.OrdinalIgnoreCase)
  872. && !string.Equals(videoEncoder, "h264_qsv", StringComparison.OrdinalIgnoreCase)
  873. && !string.Equals(videoEncoder, "h264_vaapi", StringComparison.OrdinalIgnoreCase)
  874. && !string.Equals(videoEncoder, "h264_nvenc", StringComparison.OrdinalIgnoreCase)
  875. && !string.Equals(videoEncoder, "h264_amf", StringComparison.OrdinalIgnoreCase)
  876. && !string.Equals(videoEncoder, "h264_v4l2m2m", StringComparison.OrdinalIgnoreCase)
  877. && !string.Equals(videoEncoder, "hevc_qsv", StringComparison.OrdinalIgnoreCase)
  878. && !string.Equals(videoEncoder, "hevc_vaapi", StringComparison.OrdinalIgnoreCase)
  879. && !string.Equals(videoEncoder, "hevc_nvenc", StringComparison.OrdinalIgnoreCase)
  880. && !string.Equals(videoEncoder, "hevc_amf", StringComparison.OrdinalIgnoreCase))
  881. {
  882. param += " -pix_fmt yuv420p";
  883. }
  884. if (string.Equals(videoEncoder, "h264_nvenc", StringComparison.OrdinalIgnoreCase)
  885. || string.Equals(videoEncoder, "h264_amf", StringComparison.OrdinalIgnoreCase)
  886. || string.Equals(videoEncoder, "hevc_nvenc", StringComparison.OrdinalIgnoreCase)
  887. || string.Equals(videoEncoder, "hevc_amf", StringComparison.OrdinalIgnoreCase))
  888. {
  889. var videoStream = state.VideoStream;
  890. var isColorDepth10 = IsColorDepth10(state);
  891. var videoDecoder = GetHardwareAcceleratedVideoDecoder(state, encodingOptions) ?? string.Empty;
  892. var isNvdecDecoder = videoDecoder.Contains("cuda", StringComparison.OrdinalIgnoreCase);
  893. if (!isNvdecDecoder)
  894. {
  895. if (isColorDepth10
  896. && _mediaEncoder.SupportsHwaccel("opencl")
  897. && encodingOptions.EnableTonemapping
  898. && !string.IsNullOrEmpty(videoStream.VideoRange)
  899. && videoStream.VideoRange.Contains("HDR", StringComparison.OrdinalIgnoreCase))
  900. {
  901. param += " -pix_fmt nv12";
  902. }
  903. else
  904. {
  905. param += " -pix_fmt yuv420p";
  906. }
  907. }
  908. }
  909. if (string.Equals(videoEncoder, "h264_v4l2m2m", StringComparison.OrdinalIgnoreCase))
  910. {
  911. param += " -pix_fmt nv21";
  912. }
  913. var isVc1 = state.VideoStream != null &&
  914. string.Equals(state.VideoStream.Codec, "vc1", StringComparison.OrdinalIgnoreCase);
  915. var isLibX265 = string.Equals(videoEncoder, "libx265", StringComparison.OrdinalIgnoreCase);
  916. if (string.Equals(videoEncoder, "libx264", StringComparison.OrdinalIgnoreCase) || isLibX265)
  917. {
  918. if (!string.IsNullOrEmpty(encodingOptions.EncoderPreset))
  919. {
  920. param += " -preset " + encodingOptions.EncoderPreset;
  921. }
  922. else
  923. {
  924. param += " -preset " + defaultPreset;
  925. }
  926. int encodeCrf = encodingOptions.H264Crf;
  927. if (isLibX265)
  928. {
  929. encodeCrf = encodingOptions.H265Crf;
  930. }
  931. if (encodeCrf >= 0 && encodeCrf <= 51)
  932. {
  933. param += " -crf " + encodeCrf.ToString(CultureInfo.InvariantCulture);
  934. }
  935. else
  936. {
  937. string defaultCrf = "23";
  938. if (isLibX265)
  939. {
  940. defaultCrf = "28";
  941. }
  942. param += " -crf " + defaultCrf;
  943. }
  944. }
  945. else if (string.Equals(videoEncoder, "h264_qsv", StringComparison.OrdinalIgnoreCase) // h264 (h264_qsv)
  946. || string.Equals(videoEncoder, "hevc_qsv", StringComparison.OrdinalIgnoreCase)) // hevc (hevc_qsv)
  947. {
  948. string[] valid_h264_qsv = { "veryslow", "slower", "slow", "medium", "fast", "faster", "veryfast" };
  949. if (valid_h264_qsv.Contains(encodingOptions.EncoderPreset, StringComparer.OrdinalIgnoreCase))
  950. {
  951. param += " -preset " + encodingOptions.EncoderPreset;
  952. }
  953. else
  954. {
  955. param += " -preset 7";
  956. }
  957. param += " -look_ahead 0";
  958. }
  959. else if (string.Equals(videoEncoder, "h264_nvenc", StringComparison.OrdinalIgnoreCase) // h264 (h264_nvenc)
  960. || string.Equals(videoEncoder, "hevc_nvenc", StringComparison.OrdinalIgnoreCase)) // hevc (hevc_nvenc)
  961. {
  962. switch (encodingOptions.EncoderPreset)
  963. {
  964. case "veryslow":
  965. param += " -preset slow"; // lossless is only supported on maxwell and newer(2014+)
  966. break;
  967. case "slow":
  968. case "slower":
  969. param += " -preset slow";
  970. break;
  971. case "medium":
  972. param += " -preset medium";
  973. break;
  974. case "fast":
  975. case "faster":
  976. case "veryfast":
  977. case "superfast":
  978. case "ultrafast":
  979. param += " -preset fast";
  980. break;
  981. default:
  982. param += " -preset default";
  983. break;
  984. }
  985. }
  986. else if (string.Equals(videoEncoder, "h264_amf", StringComparison.OrdinalIgnoreCase) // h264 (h264_amf)
  987. || string.Equals(videoEncoder, "hevc_amf", StringComparison.OrdinalIgnoreCase)) // hevc (hevc_amf)
  988. {
  989. switch (encodingOptions.EncoderPreset)
  990. {
  991. case "veryslow":
  992. case "slow":
  993. case "slower":
  994. param += " -quality quality";
  995. break;
  996. case "medium":
  997. param += " -quality balanced";
  998. break;
  999. case "fast":
  1000. case "faster":
  1001. case "veryfast":
  1002. case "superfast":
  1003. case "ultrafast":
  1004. param += " -quality speed";
  1005. break;
  1006. default:
  1007. param += " -quality speed";
  1008. break;
  1009. }
  1010. var videoStream = state.VideoStream;
  1011. var isColorDepth10 = IsColorDepth10(state);
  1012. if (isColorDepth10
  1013. && _mediaEncoder.SupportsHwaccel("opencl")
  1014. && encodingOptions.EnableTonemapping
  1015. && !string.IsNullOrEmpty(videoStream.VideoRange)
  1016. && videoStream.VideoRange.Contains("HDR", StringComparison.OrdinalIgnoreCase))
  1017. {
  1018. // Enhance workload when tone mapping with AMF on some APUs
  1019. param += " -preanalysis true";
  1020. }
  1021. if (string.Equals(videoEncoder, "hevc_amf", StringComparison.OrdinalIgnoreCase))
  1022. {
  1023. param += " -header_insertion_mode gop -gops_per_idr 1";
  1024. }
  1025. }
  1026. else if (string.Equals(videoEncoder, "libvpx", StringComparison.OrdinalIgnoreCase)) // vp8
  1027. {
  1028. // Values 0-3, 0 being highest quality but slower
  1029. var profileScore = 0;
  1030. string crf;
  1031. var qmin = "0";
  1032. var qmax = "50";
  1033. crf = "10";
  1034. if (isVc1)
  1035. {
  1036. profileScore++;
  1037. }
  1038. // Max of 2
  1039. profileScore = Math.Min(profileScore, 2);
  1040. // http://www.webmproject.org/docs/encoder-parameters/
  1041. param += string.Format(
  1042. CultureInfo.InvariantCulture,
  1043. " -speed 16 -quality good -profile:v {0} -slices 8 -crf {1} -qmin {2} -qmax {3}",
  1044. profileScore.ToString(CultureInfo.InvariantCulture),
  1045. crf,
  1046. qmin,
  1047. qmax);
  1048. }
  1049. else if (string.Equals(videoEncoder, "libvpx-vp9", StringComparison.OrdinalIgnoreCase)) // vp9
  1050. {
  1051. // When `-deadline` is set to `good` or `best`, `-cpu-used` ranges from 0-5.
  1052. // When `-deadline` is set to `realtime`, `-cpu-used` ranges from 0-15.
  1053. // Resources:
  1054. // * https://trac.ffmpeg.org/wiki/Encode/VP9
  1055. // * https://superuser.com/questions/1586934
  1056. // * https://developers.google.com/media/vp9
  1057. param += encodingOptions.EncoderPreset switch
  1058. {
  1059. "veryslow" => " -deadline best -cpu-used 0",
  1060. "slower" => " -deadline best -cpu-used 2",
  1061. "slow" => " -deadline best -cpu-used 3",
  1062. "medium" => " -deadline good -cpu-used 0",
  1063. "fast" => " -deadline good -cpu-used 1",
  1064. "faster" => " -deadline good -cpu-used 2",
  1065. "veryfast" => " -deadline good -cpu-used 3",
  1066. "superfast" => " -deadline good -cpu-used 4",
  1067. "ultrafast" => " -deadline good -cpu-used 5",
  1068. _ => " -deadline good -cpu-used 1"
  1069. };
  1070. // TODO: until VP9 gets its own CRF setting, base CRF on H.265.
  1071. int h265Crf = encodingOptions.H265Crf;
  1072. int defaultVp9Crf = 31;
  1073. if (h265Crf >= 0 && h265Crf <= 51)
  1074. {
  1075. // This conversion factor is chosen to match the default CRF for H.265 to the
  1076. // recommended 1080p CRF from Google. The factor also maps the logarithmic CRF
  1077. // scale of x265 [0, 51] to that of VP9 [0, 63] relatively well.
  1078. // Resources:
  1079. // * https://developers.google.com/media/vp9/settings/vod
  1080. const float H265ToVp9CrfConversionFactor = 1.12F;
  1081. var vp9Crf = Convert.ToInt32(h265Crf * H265ToVp9CrfConversionFactor);
  1082. // Encoder allows for CRF values in the range [0, 63].
  1083. vp9Crf = Math.Clamp(vp9Crf, 0, 63);
  1084. param += FormattableString.Invariant($" -crf {vp9Crf}");
  1085. }
  1086. else
  1087. {
  1088. param += FormattableString.Invariant($" -crf {defaultVp9Crf}");
  1089. }
  1090. param += " -row-mt 1 -profile 1";
  1091. }
  1092. else if (string.Equals(videoEncoder, "mpeg4", StringComparison.OrdinalIgnoreCase))
  1093. {
  1094. param += " -mbd rd -flags +mv4+aic -trellis 2 -cmp 2 -subcmp 2 -bf 2";
  1095. }
  1096. else if (string.Equals(videoEncoder, "wmv2", StringComparison.OrdinalIgnoreCase)) // asf/wmv
  1097. {
  1098. param += " -qmin 2";
  1099. }
  1100. else if (string.Equals(videoEncoder, "msmpeg4", StringComparison.OrdinalIgnoreCase))
  1101. {
  1102. param += " -mbd 2";
  1103. }
  1104. param += GetVideoBitrateParam(state, videoEncoder);
  1105. var framerate = GetFramerateParam(state);
  1106. if (framerate.HasValue)
  1107. {
  1108. param += string.Format(CultureInfo.InvariantCulture, " -r {0}", framerate.Value.ToString(CultureInfo.InvariantCulture));
  1109. }
  1110. var targetVideoCodec = state.ActualOutputVideoCodec;
  1111. if (string.Equals(targetVideoCodec, "h265", StringComparison.OrdinalIgnoreCase)
  1112. || string.Equals(targetVideoCodec, "hevc", StringComparison.OrdinalIgnoreCase))
  1113. {
  1114. targetVideoCodec = "hevc";
  1115. }
  1116. var profile = state.GetRequestedProfiles(targetVideoCodec).FirstOrDefault() ?? string.Empty;
  1117. profile = Regex.Replace(profile, @"\s+", string.Empty);
  1118. // We only transcode to HEVC 8-bit for now, force Main Profile.
  1119. if (profile.Contains("main10", StringComparison.OrdinalIgnoreCase)
  1120. || profile.Contains("mainstill", StringComparison.OrdinalIgnoreCase))
  1121. {
  1122. profile = "main";
  1123. }
  1124. // Extended Profile is not supported by any known h264 encoders, force Main Profile.
  1125. if (profile.Contains("extended", StringComparison.OrdinalIgnoreCase))
  1126. {
  1127. profile = "main";
  1128. }
  1129. // Only libx264 support encoding H264 High 10 Profile, otherwise force High Profile.
  1130. if (!string.Equals(videoEncoder, "libx264", StringComparison.OrdinalIgnoreCase)
  1131. && profile.Contains("high10", StringComparison.OrdinalIgnoreCase))
  1132. {
  1133. profile = "high";
  1134. }
  1135. // h264_vaapi does not support Baseline profile, force Constrained Baseline in this case,
  1136. // which is compatible (and ugly).
  1137. if (string.Equals(videoEncoder, "h264_vaapi", StringComparison.OrdinalIgnoreCase)
  1138. && profile.Contains("baseline", StringComparison.OrdinalIgnoreCase))
  1139. {
  1140. profile = "constrained_baseline";
  1141. }
  1142. // libx264, h264_qsv and h264_nvenc does not support Constrained Baseline profile, force Baseline in this case.
  1143. if ((string.Equals(videoEncoder, "libx264", StringComparison.OrdinalIgnoreCase)
  1144. || string.Equals(videoEncoder, "h264_qsv", StringComparison.OrdinalIgnoreCase)
  1145. || string.Equals(videoEncoder, "h264_nvenc", StringComparison.OrdinalIgnoreCase))
  1146. && profile.Contains("baseline", StringComparison.OrdinalIgnoreCase))
  1147. {
  1148. profile = "baseline";
  1149. }
  1150. // libx264, h264_qsv, h264_nvenc and h264_vaapi does not support Constrained High profile, force High in this case.
  1151. if ((string.Equals(videoEncoder, "libx264", StringComparison.OrdinalIgnoreCase)
  1152. || string.Equals(videoEncoder, "h264_qsv", StringComparison.OrdinalIgnoreCase)
  1153. || string.Equals(videoEncoder, "h264_nvenc", StringComparison.OrdinalIgnoreCase)
  1154. || string.Equals(videoEncoder, "h264_vaapi", StringComparison.OrdinalIgnoreCase))
  1155. && profile.Contains("high", StringComparison.OrdinalIgnoreCase))
  1156. {
  1157. profile = "high";
  1158. }
  1159. if (string.Equals(videoEncoder, "h264_amf", StringComparison.OrdinalIgnoreCase)
  1160. && profile.Contains("baseline", StringComparison.OrdinalIgnoreCase))
  1161. {
  1162. profile = "constrained_baseline";
  1163. }
  1164. if (string.Equals(videoEncoder, "h264_amf", StringComparison.OrdinalIgnoreCase)
  1165. && profile.Contains("constrainedhigh", StringComparison.OrdinalIgnoreCase))
  1166. {
  1167. profile = "constrained_high";
  1168. }
  1169. // Currently hevc_amf only support encoding HEVC Main Profile, otherwise force Main Profile.
  1170. if (string.Equals(videoEncoder, "hevc_amf", StringComparison.OrdinalIgnoreCase)
  1171. && profile.Contains("main10", StringComparison.OrdinalIgnoreCase))
  1172. {
  1173. profile = "main";
  1174. }
  1175. if (!string.IsNullOrEmpty(profile))
  1176. {
  1177. if (!string.Equals(videoEncoder, "h264_omx", StringComparison.OrdinalIgnoreCase)
  1178. && !string.Equals(videoEncoder, "h264_v4l2m2m", StringComparison.OrdinalIgnoreCase))
  1179. {
  1180. // not supported by h264_omx
  1181. param += " -profile:v:0 " + profile;
  1182. }
  1183. }
  1184. var level = state.GetRequestedLevel(targetVideoCodec);
  1185. if (!string.IsNullOrEmpty(level))
  1186. {
  1187. level = NormalizeTranscodingLevel(state, level);
  1188. // libx264, QSV, AMF, VAAPI can adjust the given level to match the output.
  1189. if (string.Equals(videoEncoder, "h264_qsv", StringComparison.OrdinalIgnoreCase)
  1190. || string.Equals(videoEncoder, "libx264", StringComparison.OrdinalIgnoreCase))
  1191. {
  1192. param += " -level " + level;
  1193. }
  1194. else if (string.Equals(videoEncoder, "hevc_qsv", StringComparison.OrdinalIgnoreCase))
  1195. {
  1196. // hevc_qsv use -level 51 instead of -level 153.
  1197. if (double.TryParse(level, NumberStyles.Any, CultureInfo.InvariantCulture, out double hevcLevel))
  1198. {
  1199. param += " -level " + (hevcLevel / 3);
  1200. }
  1201. }
  1202. else if (string.Equals(videoEncoder, "h264_amf", StringComparison.OrdinalIgnoreCase)
  1203. || string.Equals(videoEncoder, "hevc_amf", StringComparison.OrdinalIgnoreCase))
  1204. {
  1205. param += " -level " + level;
  1206. }
  1207. else if (string.Equals(videoEncoder, "h264_nvenc", StringComparison.OrdinalIgnoreCase)
  1208. || string.Equals(videoEncoder, "hevc_nvenc", StringComparison.OrdinalIgnoreCase))
  1209. {
  1210. // level option may cause NVENC to fail.
  1211. // NVENC cannot adjust the given level, just throw an error.
  1212. }
  1213. else if (!string.Equals(videoEncoder, "h264_omx", StringComparison.OrdinalIgnoreCase)
  1214. || !string.Equals(videoEncoder, "libx265", StringComparison.OrdinalIgnoreCase))
  1215. {
  1216. param += " -level " + level;
  1217. }
  1218. }
  1219. if (string.Equals(videoEncoder, "libx264", StringComparison.OrdinalIgnoreCase))
  1220. {
  1221. param += " -x264opts:0 subme=0:me_range=4:rc_lookahead=10:me=dia:no_chroma_me:8x8dct=0:partitions=none";
  1222. }
  1223. if (string.Equals(videoEncoder, "libx265", StringComparison.OrdinalIgnoreCase))
  1224. {
  1225. // libx265 only accept level option in -x265-params.
  1226. // level option may cause libx265 to fail.
  1227. // libx265 cannot adjust the given level, just throw an error.
  1228. // TODO: set fine tuned params.
  1229. param += " -x265-params:0 no-info=1";
  1230. }
  1231. return param;
  1232. }
  1233. public bool CanStreamCopyVideo(EncodingJobInfo state, MediaStream videoStream)
  1234. {
  1235. var request = state.BaseRequest;
  1236. if (!request.AllowVideoStreamCopy)
  1237. {
  1238. return false;
  1239. }
  1240. if (videoStream.IsInterlaced
  1241. && state.DeInterlace(videoStream.Codec, false))
  1242. {
  1243. return false;
  1244. }
  1245. if (videoStream.IsAnamorphic ?? false)
  1246. {
  1247. if (request.RequireNonAnamorphic)
  1248. {
  1249. return false;
  1250. }
  1251. }
  1252. // Can't stream copy if we're burning in subtitles
  1253. if (request.SubtitleStreamIndex.HasValue
  1254. && state.SubtitleDeliveryMethod == SubtitleDeliveryMethod.Encode)
  1255. {
  1256. return false;
  1257. }
  1258. if (string.Equals("h264", videoStream.Codec, StringComparison.OrdinalIgnoreCase)
  1259. && videoStream.IsAVC.HasValue
  1260. && !videoStream.IsAVC.Value
  1261. && request.RequireAvc)
  1262. {
  1263. return false;
  1264. }
  1265. // Source and target codecs must match
  1266. if (string.IsNullOrEmpty(videoStream.Codec)
  1267. || !state.SupportedVideoCodecs.Contains(videoStream.Codec, StringComparer.OrdinalIgnoreCase))
  1268. {
  1269. return false;
  1270. }
  1271. var requestedProfiles = state.GetRequestedProfiles(videoStream.Codec);
  1272. // If client is requesting a specific video profile, it must match the source
  1273. if (requestedProfiles.Length > 0)
  1274. {
  1275. if (string.IsNullOrEmpty(videoStream.Profile))
  1276. {
  1277. // return false;
  1278. }
  1279. var requestedProfile = requestedProfiles[0];
  1280. // strip spaces because they may be stripped out on the query string as well
  1281. if (!string.IsNullOrEmpty(videoStream.Profile)
  1282. && !requestedProfiles.Contains(videoStream.Profile.Replace(" ", string.Empty, StringComparison.Ordinal), StringComparer.OrdinalIgnoreCase))
  1283. {
  1284. var currentScore = GetVideoProfileScore(videoStream.Profile);
  1285. var requestedScore = GetVideoProfileScore(requestedProfile);
  1286. if (currentScore == -1 || currentScore > requestedScore)
  1287. {
  1288. return false;
  1289. }
  1290. }
  1291. }
  1292. // Video width must fall within requested value
  1293. if (request.MaxWidth.HasValue
  1294. && (!videoStream.Width.HasValue || videoStream.Width.Value > request.MaxWidth.Value))
  1295. {
  1296. return false;
  1297. }
  1298. // Video height must fall within requested value
  1299. if (request.MaxHeight.HasValue
  1300. && (!videoStream.Height.HasValue || videoStream.Height.Value > request.MaxHeight.Value))
  1301. {
  1302. return false;
  1303. }
  1304. // Video framerate must fall within requested value
  1305. var requestedFramerate = request.MaxFramerate ?? request.Framerate;
  1306. if (requestedFramerate.HasValue)
  1307. {
  1308. var videoFrameRate = videoStream.AverageFrameRate ?? videoStream.RealFrameRate;
  1309. if (!videoFrameRate.HasValue || videoFrameRate.Value > requestedFramerate.Value)
  1310. {
  1311. return false;
  1312. }
  1313. }
  1314. // Video bitrate must fall within requested value
  1315. if (request.VideoBitRate.HasValue
  1316. && (!videoStream.BitRate.HasValue || videoStream.BitRate.Value > request.VideoBitRate.Value))
  1317. {
  1318. return false;
  1319. }
  1320. var maxBitDepth = state.GetRequestedVideoBitDepth(videoStream.Codec);
  1321. if (maxBitDepth.HasValue)
  1322. {
  1323. if (videoStream.BitDepth.HasValue && videoStream.BitDepth.Value > maxBitDepth.Value)
  1324. {
  1325. return false;
  1326. }
  1327. }
  1328. var maxRefFrames = state.GetRequestedMaxRefFrames(videoStream.Codec);
  1329. if (maxRefFrames.HasValue
  1330. && videoStream.RefFrames.HasValue && videoStream.RefFrames.Value > maxRefFrames.Value)
  1331. {
  1332. return false;
  1333. }
  1334. // If a specific level was requested, the source must match or be less than
  1335. var level = state.GetRequestedLevel(videoStream.Codec);
  1336. if (!string.IsNullOrEmpty(level)
  1337. && double.TryParse(level, NumberStyles.Any, CultureInfo.InvariantCulture, out var requestLevel))
  1338. {
  1339. if (!videoStream.Level.HasValue)
  1340. {
  1341. // return false;
  1342. }
  1343. if (videoStream.Level.HasValue && videoStream.Level.Value > requestLevel)
  1344. {
  1345. return false;
  1346. }
  1347. }
  1348. if (string.Equals(state.InputContainer, "avi", StringComparison.OrdinalIgnoreCase)
  1349. && string.Equals(videoStream.Codec, "h264", StringComparison.OrdinalIgnoreCase)
  1350. && !(videoStream.IsAVC ?? false))
  1351. {
  1352. // see Coach S01E01 - Kelly and the Professor(0).avi
  1353. return false;
  1354. }
  1355. return request.EnableAutoStreamCopy;
  1356. }
  1357. public bool CanStreamCopyAudio(EncodingJobInfo state, MediaStream audioStream, IEnumerable<string> supportedAudioCodecs)
  1358. {
  1359. var request = state.BaseRequest;
  1360. if (!request.AllowAudioStreamCopy)
  1361. {
  1362. return false;
  1363. }
  1364. var maxBitDepth = state.GetRequestedAudioBitDepth(audioStream.Codec);
  1365. if (maxBitDepth.HasValue
  1366. && audioStream.BitDepth.HasValue
  1367. && audioStream.BitDepth.Value > maxBitDepth.Value)
  1368. {
  1369. return false;
  1370. }
  1371. // Source and target codecs must match
  1372. if (string.IsNullOrEmpty(audioStream.Codec)
  1373. || !supportedAudioCodecs.Contains(audioStream.Codec, StringComparer.OrdinalIgnoreCase))
  1374. {
  1375. return false;
  1376. }
  1377. // Channels must fall within requested value
  1378. var channels = state.GetRequestedAudioChannels(audioStream.Codec);
  1379. if (channels.HasValue)
  1380. {
  1381. if (!audioStream.Channels.HasValue || audioStream.Channels.Value <= 0)
  1382. {
  1383. return false;
  1384. }
  1385. if (audioStream.Channels.Value > channels.Value)
  1386. {
  1387. return false;
  1388. }
  1389. }
  1390. // Sample rate must fall within requested value
  1391. if (request.AudioSampleRate.HasValue)
  1392. {
  1393. if (!audioStream.SampleRate.HasValue || audioStream.SampleRate.Value <= 0)
  1394. {
  1395. return false;
  1396. }
  1397. if (audioStream.SampleRate.Value > request.AudioSampleRate.Value)
  1398. {
  1399. return false;
  1400. }
  1401. }
  1402. // Video bitrate must fall within requested value
  1403. if (request.AudioBitRate.HasValue)
  1404. {
  1405. if (!audioStream.BitRate.HasValue || audioStream.BitRate.Value <= 0)
  1406. {
  1407. return false;
  1408. }
  1409. if (audioStream.BitRate.Value > request.AudioBitRate.Value)
  1410. {
  1411. return false;
  1412. }
  1413. }
  1414. return request.EnableAutoStreamCopy;
  1415. }
  1416. public int? GetVideoBitrateParamValue(BaseEncodingJobOptions request, MediaStream videoStream, string outputVideoCodec)
  1417. {
  1418. var bitrate = request.VideoBitRate;
  1419. if (videoStream != null)
  1420. {
  1421. var isUpscaling = request.Height.HasValue
  1422. && videoStream.Height.HasValue
  1423. && request.Height.Value > videoStream.Height.Value
  1424. && request.Width.HasValue
  1425. && videoStream.Width.HasValue
  1426. && request.Width.Value > videoStream.Width.Value;
  1427. // Don't allow bitrate increases unless upscaling
  1428. if (!isUpscaling && bitrate.HasValue && videoStream.BitRate.HasValue)
  1429. {
  1430. bitrate = GetMinBitrate(videoStream.BitRate.Value, bitrate.Value);
  1431. }
  1432. if (bitrate.HasValue)
  1433. {
  1434. var inputVideoCodec = videoStream.Codec;
  1435. bitrate = ScaleBitrate(bitrate.Value, inputVideoCodec, outputVideoCodec);
  1436. // If a max bitrate was requested, don't let the scaled bitrate exceed it
  1437. if (request.VideoBitRate.HasValue)
  1438. {
  1439. bitrate = Math.Min(bitrate.Value, request.VideoBitRate.Value);
  1440. }
  1441. }
  1442. }
  1443. return bitrate;
  1444. }
  1445. private int GetMinBitrate(int sourceBitrate, int requestedBitrate)
  1446. {
  1447. // these values were chosen from testing to improve low bitrate streams
  1448. if (sourceBitrate <= 2000000)
  1449. {
  1450. sourceBitrate = Convert.ToInt32(sourceBitrate * 2.5);
  1451. }
  1452. else if (sourceBitrate <= 3000000)
  1453. {
  1454. sourceBitrate *= 2;
  1455. }
  1456. var bitrate = Math.Min(sourceBitrate, requestedBitrate);
  1457. return bitrate;
  1458. }
  1459. private static double GetVideoBitrateScaleFactor(string codec)
  1460. {
  1461. if (string.Equals(codec, "h265", StringComparison.OrdinalIgnoreCase)
  1462. || string.Equals(codec, "hevc", StringComparison.OrdinalIgnoreCase)
  1463. || string.Equals(codec, "vp9", StringComparison.OrdinalIgnoreCase))
  1464. {
  1465. return .6;
  1466. }
  1467. return 1;
  1468. }
  1469. private static int ScaleBitrate(int bitrate, string inputVideoCodec, string outputVideoCodec)
  1470. {
  1471. var inputScaleFactor = GetVideoBitrateScaleFactor(inputVideoCodec);
  1472. var outputScaleFactor = GetVideoBitrateScaleFactor(outputVideoCodec);
  1473. var scaleFactor = outputScaleFactor / inputScaleFactor;
  1474. if (bitrate <= 500000)
  1475. {
  1476. scaleFactor = Math.Max(scaleFactor, 4);
  1477. }
  1478. else if (bitrate <= 1000000)
  1479. {
  1480. scaleFactor = Math.Max(scaleFactor, 3);
  1481. }
  1482. else if (bitrate <= 2000000)
  1483. {
  1484. scaleFactor = Math.Max(scaleFactor, 2.5);
  1485. }
  1486. else if (bitrate <= 3000000)
  1487. {
  1488. scaleFactor = Math.Max(scaleFactor, 2);
  1489. }
  1490. return Convert.ToInt32(scaleFactor * bitrate);
  1491. }
  1492. public int? GetAudioBitrateParam(BaseEncodingJobOptions request, MediaStream audioStream)
  1493. {
  1494. return GetAudioBitrateParam(request.AudioBitRate, request.AudioCodec, audioStream);
  1495. }
  1496. public int? GetAudioBitrateParam(int? audioBitRate, string audioCodec, MediaStream audioStream)
  1497. {
  1498. if (audioStream == null)
  1499. {
  1500. return null;
  1501. }
  1502. if (audioBitRate.HasValue && string.IsNullOrEmpty(audioCodec))
  1503. {
  1504. return Math.Min(384000, audioBitRate.Value);
  1505. }
  1506. if (audioBitRate.HasValue && !string.IsNullOrEmpty(audioCodec))
  1507. {
  1508. if (string.Equals(audioCodec, "aac", StringComparison.OrdinalIgnoreCase)
  1509. || string.Equals(audioCodec, "mp3", StringComparison.OrdinalIgnoreCase)
  1510. || string.Equals(audioCodec, "ac3", StringComparison.OrdinalIgnoreCase)
  1511. || string.Equals(audioCodec, "eac3", StringComparison.OrdinalIgnoreCase))
  1512. {
  1513. if ((audioStream.Channels ?? 0) >= 6)
  1514. {
  1515. return Math.Min(640000, audioBitRate.Value);
  1516. }
  1517. return Math.Min(384000, audioBitRate.Value);
  1518. }
  1519. if (string.Equals(audioCodec, "flac", StringComparison.OrdinalIgnoreCase)
  1520. || string.Equals(audioCodec, "alac", StringComparison.OrdinalIgnoreCase))
  1521. {
  1522. if ((audioStream.Channels ?? 0) >= 6)
  1523. {
  1524. return Math.Min(3584000, audioBitRate.Value);
  1525. }
  1526. return Math.Min(1536000, audioBitRate.Value);
  1527. }
  1528. }
  1529. // Empty bitrate area is not allow on iOS
  1530. // Default audio bitrate to 128K if it is not being requested
  1531. // https://ffmpeg.org/ffmpeg-codecs.html#toc-Codec-Options
  1532. return 128000;
  1533. }
  1534. public string GetAudioFilterParam(EncodingJobInfo state, EncodingOptions encodingOptions)
  1535. {
  1536. var channels = state.OutputAudioChannels;
  1537. var filters = new List<string>();
  1538. // Boost volume to 200% when downsampling from 6ch to 2ch
  1539. if (channels.HasValue
  1540. && channels.Value <= 2
  1541. && state.AudioStream != null
  1542. && state.AudioStream.Channels.HasValue
  1543. && state.AudioStream.Channels.Value > 5
  1544. && !encodingOptions.DownMixAudioBoost.Equals(1))
  1545. {
  1546. filters.Add("volume=" + encodingOptions.DownMixAudioBoost.ToString(CultureInfo.InvariantCulture));
  1547. }
  1548. var isCopyingTimestamps = state.CopyTimestamps || state.TranscodingType != TranscodingJobType.Progressive;
  1549. if (state.SubtitleStream != null && state.SubtitleStream.IsTextSubtitleStream && state.SubtitleDeliveryMethod == SubtitleDeliveryMethod.Encode && !isCopyingTimestamps)
  1550. {
  1551. var seconds = TimeSpan.FromTicks(state.StartTimeTicks ?? 0).TotalSeconds;
  1552. filters.Add(
  1553. string.Format(
  1554. CultureInfo.InvariantCulture,
  1555. "asetpts=PTS-{0}/TB",
  1556. Math.Round(seconds)));
  1557. }
  1558. if (filters.Count > 0)
  1559. {
  1560. return " -af \"" + string.Join(',', filters) + "\"";
  1561. }
  1562. return string.Empty;
  1563. }
  1564. /// <summary>
  1565. /// Gets the number of audio channels to specify on the command line.
  1566. /// </summary>
  1567. /// <param name="state">The state.</param>
  1568. /// <param name="audioStream">The audio stream.</param>
  1569. /// <param name="outputAudioCodec">The output audio codec.</param>
  1570. /// <returns>System.Nullable{System.Int32}.</returns>
  1571. public int? GetNumAudioChannelsParam(EncodingJobInfo state, MediaStream audioStream, string outputAudioCodec)
  1572. {
  1573. if (audioStream == null)
  1574. {
  1575. return null;
  1576. }
  1577. var request = state.BaseRequest;
  1578. var inputChannels = audioStream.Channels;
  1579. if (inputChannels <= 0)
  1580. {
  1581. inputChannels = null;
  1582. }
  1583. var codec = outputAudioCodec ?? string.Empty;
  1584. int? transcoderChannelLimit;
  1585. if (codec.IndexOf("wma", StringComparison.OrdinalIgnoreCase) != -1)
  1586. {
  1587. // wmav2 currently only supports two channel output
  1588. transcoderChannelLimit = 2;
  1589. }
  1590. else if (codec.IndexOf("mp3", StringComparison.OrdinalIgnoreCase) != -1)
  1591. {
  1592. // libmp3lame currently only supports two channel output
  1593. transcoderChannelLimit = 2;
  1594. }
  1595. else if (codec.IndexOf("aac", StringComparison.OrdinalIgnoreCase) != -1)
  1596. {
  1597. // aac is able to handle 8ch(7.1 layout)
  1598. transcoderChannelLimit = 8;
  1599. }
  1600. else
  1601. {
  1602. // If we don't have any media info then limit it to 6 to prevent encoding errors due to asking for too many channels
  1603. transcoderChannelLimit = 6;
  1604. }
  1605. var isTranscodingAudio = !IsCopyCodec(codec);
  1606. int? resultChannels = state.GetRequestedAudioChannels(codec);
  1607. if (isTranscodingAudio)
  1608. {
  1609. resultChannels = GetMinValue(request.TranscodingMaxAudioChannels, resultChannels);
  1610. }
  1611. if (inputChannels.HasValue)
  1612. {
  1613. resultChannels = resultChannels.HasValue
  1614. ? Math.Min(resultChannels.Value, inputChannels.Value)
  1615. : inputChannels.Value;
  1616. }
  1617. if (isTranscodingAudio && transcoderChannelLimit.HasValue)
  1618. {
  1619. resultChannels = resultChannels.HasValue
  1620. ? Math.Min(resultChannels.Value, transcoderChannelLimit.Value)
  1621. : transcoderChannelLimit.Value;
  1622. }
  1623. // Avoid transcoding to audio channels other than 1ch, 2ch, 6ch (5.1 layout) and 8ch (7.1 layout).
  1624. // https://developer.apple.com/documentation/http_live_streaming/hls_authoring_specification_for_apple_devices
  1625. if (isTranscodingAudio
  1626. && state.TranscodingType != TranscodingJobType.Progressive
  1627. && resultChannels.HasValue
  1628. && ((resultChannels.Value > 2 && resultChannels.Value < 6) || resultChannels.Value == 7))
  1629. {
  1630. resultChannels = 2;
  1631. }
  1632. return resultChannels;
  1633. }
  1634. private int? GetMinValue(int? val1, int? val2)
  1635. {
  1636. if (!val1.HasValue)
  1637. {
  1638. return val2;
  1639. }
  1640. if (!val2.HasValue)
  1641. {
  1642. return val1;
  1643. }
  1644. return Math.Min(val1.Value, val2.Value);
  1645. }
  1646. /// <summary>
  1647. /// Enforces the resolution limit.
  1648. /// </summary>
  1649. /// <param name="state">The state.</param>
  1650. public void EnforceResolutionLimit(EncodingJobInfo state)
  1651. {
  1652. var videoRequest = state.BaseRequest;
  1653. // Switch the incoming params to be ceilings rather than fixed values
  1654. videoRequest.MaxWidth = videoRequest.MaxWidth ?? videoRequest.Width;
  1655. videoRequest.MaxHeight = videoRequest.MaxHeight ?? videoRequest.Height;
  1656. videoRequest.Width = null;
  1657. videoRequest.Height = null;
  1658. }
  1659. /// <summary>
  1660. /// Gets the fast seek command line parameter.
  1661. /// </summary>
  1662. /// <param name="request">The request.</param>
  1663. /// <returns>System.String.</returns>
  1664. /// <value>The fast seek command line parameter.</value>
  1665. public string GetFastSeekCommandLineParameter(BaseEncodingJobOptions request)
  1666. {
  1667. var time = request.StartTimeTicks ?? 0;
  1668. if (time > 0)
  1669. {
  1670. return string.Format(CultureInfo.InvariantCulture, "-ss {0}", _mediaEncoder.GetTimeParameter(time));
  1671. }
  1672. return string.Empty;
  1673. }
  1674. /// <summary>
  1675. /// Gets the map args.
  1676. /// </summary>
  1677. /// <param name="state">The state.</param>
  1678. /// <returns>System.String.</returns>
  1679. public string GetMapArgs(EncodingJobInfo state)
  1680. {
  1681. // If we don't have known media info
  1682. // If input is video, use -sn to drop subtitles
  1683. // Otherwise just return empty
  1684. if (state.VideoStream == null && state.AudioStream == null)
  1685. {
  1686. return state.IsInputVideo ? "-sn" : string.Empty;
  1687. }
  1688. // We have media info, but we don't know the stream indexes
  1689. if (state.VideoStream != null && state.VideoStream.Index == -1)
  1690. {
  1691. return "-sn";
  1692. }
  1693. // We have media info, but we don't know the stream indexes
  1694. if (state.AudioStream != null && state.AudioStream.Index == -1)
  1695. {
  1696. return state.IsInputVideo ? "-sn" : string.Empty;
  1697. }
  1698. var args = string.Empty;
  1699. if (state.VideoStream != null)
  1700. {
  1701. args += string.Format(
  1702. CultureInfo.InvariantCulture,
  1703. "-map 0:{0}",
  1704. state.VideoStream.Index);
  1705. }
  1706. else
  1707. {
  1708. // No known video stream
  1709. args += "-vn";
  1710. }
  1711. if (state.AudioStream != null)
  1712. {
  1713. if (state.AudioStream.IsExternal)
  1714. {
  1715. int externalAudioMapIndex = state.SubtitleStream != null && state.SubtitleStream.IsExternal ? 2 : 1;
  1716. int externalAudioStream = state.MediaSource.MediaStreams.FindIndex(i => i.Path == state.AudioStream.Path);
  1717. args += string.Format(
  1718. CultureInfo.InvariantCulture,
  1719. " -map {0}:{1}",
  1720. externalAudioMapIndex,
  1721. externalAudioStream);
  1722. }
  1723. else
  1724. {
  1725. args += string.Format(
  1726. CultureInfo.InvariantCulture,
  1727. " -map 0:{0}",
  1728. state.AudioStream.Index);
  1729. }
  1730. }
  1731. else
  1732. {
  1733. args += " -map -0:a";
  1734. }
  1735. var subtitleMethod = state.SubtitleDeliveryMethod;
  1736. if (state.SubtitleStream == null || subtitleMethod == SubtitleDeliveryMethod.Hls)
  1737. {
  1738. args += " -map -0:s";
  1739. }
  1740. else if (subtitleMethod == SubtitleDeliveryMethod.Embed)
  1741. {
  1742. args += string.Format(
  1743. CultureInfo.InvariantCulture,
  1744. " -map 0:{0}",
  1745. state.SubtitleStream.Index);
  1746. }
  1747. else if (state.SubtitleStream.IsExternal && !state.SubtitleStream.IsTextSubtitleStream)
  1748. {
  1749. args += " -map 1:0 -sn";
  1750. }
  1751. return args;
  1752. }
  1753. /// <summary>
  1754. /// Determines which stream will be used for playback.
  1755. /// </summary>
  1756. /// <param name="allStream">All stream.</param>
  1757. /// <param name="desiredIndex">Index of the desired.</param>
  1758. /// <param name="type">The type.</param>
  1759. /// <param name="returnFirstIfNoIndex">if set to <c>true</c> [return first if no index].</param>
  1760. /// <returns>MediaStream.</returns>
  1761. public MediaStream GetMediaStream(IEnumerable<MediaStream> allStream, int? desiredIndex, MediaStreamType type, bool returnFirstIfNoIndex = true)
  1762. {
  1763. var streams = allStream.Where(s => s.Type == type).OrderBy(i => i.Index).ToList();
  1764. if (desiredIndex.HasValue)
  1765. {
  1766. var stream = streams.FirstOrDefault(s => s.Index == desiredIndex.Value);
  1767. if (stream != null)
  1768. {
  1769. return stream;
  1770. }
  1771. }
  1772. if (returnFirstIfNoIndex && type == MediaStreamType.Audio)
  1773. {
  1774. return streams.FirstOrDefault(i => i.Channels.HasValue && i.Channels.Value > 0) ??
  1775. streams.FirstOrDefault();
  1776. }
  1777. // Just return the first one
  1778. return returnFirstIfNoIndex ? streams.FirstOrDefault() : null;
  1779. }
  1780. /// <summary>
  1781. /// Gets the graphical subtitle parameter.
  1782. /// </summary>
  1783. /// <param name="state">Encoding state.</param>
  1784. /// <param name="options">Encoding options.</param>
  1785. /// <param name="outputVideoCodec">Video codec to use.</param>
  1786. /// <returns>Graphical subtitle parameter.</returns>
  1787. public string GetGraphicalSubtitleParam(
  1788. EncodingJobInfo state,
  1789. EncodingOptions options,
  1790. string outputVideoCodec)
  1791. {
  1792. outputVideoCodec ??= string.Empty;
  1793. var outputSizeParam = ReadOnlySpan<char>.Empty;
  1794. var request = state.BaseRequest;
  1795. outputSizeParam = GetOutputSizeParamInternal(state, options, outputVideoCodec);
  1796. var videoSizeParam = string.Empty;
  1797. var videoDecoder = GetHardwareAcceleratedVideoDecoder(state, options) ?? string.Empty;
  1798. var isLinux = OperatingSystem.IsLinux();
  1799. var isVaapiDecoder = videoDecoder.IndexOf("vaapi", StringComparison.OrdinalIgnoreCase) != -1;
  1800. var isVaapiH264Encoder = outputVideoCodec.IndexOf("h264_vaapi", StringComparison.OrdinalIgnoreCase) != -1;
  1801. var isVaapiHevcEncoder = outputVideoCodec.IndexOf("hevc_vaapi", StringComparison.OrdinalIgnoreCase) != -1;
  1802. var isQsvH264Encoder = outputVideoCodec.Contains("h264_qsv", StringComparison.OrdinalIgnoreCase);
  1803. var isQsvHevcEncoder = outputVideoCodec.Contains("hevc_qsv", StringComparison.OrdinalIgnoreCase);
  1804. var isNvdecDecoder = videoDecoder.Contains("cuda", StringComparison.OrdinalIgnoreCase);
  1805. var isNvencEncoder = outputVideoCodec.Contains("nvenc", StringComparison.OrdinalIgnoreCase);
  1806. var isTonemappingSupportedOnVaapi = string.Equals(options.HardwareAccelerationType, "vaapi", StringComparison.OrdinalIgnoreCase) && isVaapiDecoder && (isVaapiH264Encoder || isVaapiHevcEncoder);
  1807. var isTonemappingSupportedOnQsv = string.Equals(options.HardwareAccelerationType, "qsv", StringComparison.OrdinalIgnoreCase) && isVaapiDecoder && (isQsvH264Encoder || isQsvHevcEncoder);
  1808. var isOpenclTonemappingSupported = IsOpenclTonemappingSupported(state, options);
  1809. var isVppTonemappingSupported = IsVppTonemappingSupported(state, options);
  1810. var mediaEncoderVersion = _mediaEncoder.GetMediaEncoderVersion();
  1811. var isCudaOverlaySupported = _mediaEncoder.SupportsFilter("overlay_cuda") && mediaEncoderVersion != null && mediaEncoderVersion >= _minVersionForCudaOverlay;
  1812. var isCudaFormatConversionSupported = _mediaEncoder.SupportsFilterWithOption(FilterOptionType.ScaleCudaFormat);
  1813. // Tonemapping and burn-in graphical subtitles requires overlay_vaapi.
  1814. // But it's still in ffmpeg mailing list. Disable it for now.
  1815. if (isTonemappingSupportedOnVaapi && isOpenclTonemappingSupported && !isVppTonemappingSupported)
  1816. {
  1817. return GetOutputSizeParam(state, options, outputVideoCodec);
  1818. }
  1819. // Setup subtitle scaling
  1820. if (state.VideoStream != null && state.VideoStream.Width.HasValue && state.VideoStream.Height.HasValue)
  1821. {
  1822. // Adjust the size of graphical subtitles to fit the video stream.
  1823. var videoStream = state.VideoStream;
  1824. var inputWidth = videoStream.Width;
  1825. var inputHeight = videoStream.Height;
  1826. var (width, height) = GetFixedOutputSize(inputWidth, inputHeight, request.Width, request.Height, request.MaxWidth, request.MaxHeight);
  1827. if (width.HasValue && height.HasValue)
  1828. {
  1829. videoSizeParam = string.Format(
  1830. CultureInfo.InvariantCulture,
  1831. "scale={0}x{1}",
  1832. width.Value,
  1833. height.Value);
  1834. }
  1835. if (!string.IsNullOrEmpty(videoSizeParam)
  1836. && !(isTonemappingSupportedOnQsv && isVppTonemappingSupported))
  1837. {
  1838. // upload graphical subtitle to QSV
  1839. if (isLinux && (string.Equals(outputVideoCodec, "h264_qsv", StringComparison.OrdinalIgnoreCase)
  1840. || string.Equals(outputVideoCodec, "hevc_qsv", StringComparison.OrdinalIgnoreCase)))
  1841. {
  1842. videoSizeParam += ",hwupload=extra_hw_frames=64";
  1843. }
  1844. }
  1845. if (!string.IsNullOrEmpty(videoSizeParam))
  1846. {
  1847. // upload graphical subtitle to cuda
  1848. if (isNvdecDecoder && isNvencEncoder && isCudaOverlaySupported && isCudaFormatConversionSupported)
  1849. {
  1850. videoSizeParam += ",hwupload_cuda";
  1851. }
  1852. }
  1853. }
  1854. var mapPrefix = state.SubtitleStream.IsExternal ?
  1855. 1 :
  1856. 0;
  1857. var subtitleStreamIndex = state.SubtitleStream.IsExternal
  1858. ? 0
  1859. : state.SubtitleStream.Index;
  1860. // Setup default filtergraph utilizing FFMpeg overlay() and FFMpeg scale() (see the return of this function for index reference)
  1861. // Always put the scaler before the overlay for better performance
  1862. var retStr = outputSizeParam.IsEmpty
  1863. ? " -filter_complex \"[{0}:{1}]{4}[sub];[0:{2}][sub]overlay\""
  1864. : " -filter_complex \"[{0}:{1}]{4}[sub];[0:{2}]{3}[base];[base][sub]overlay\"";
  1865. // When the input may or may not be hardware VAAPI decodable
  1866. if (string.Equals(outputVideoCodec, "h264_vaapi", StringComparison.OrdinalIgnoreCase)
  1867. || string.Equals(outputVideoCodec, "hevc_vaapi", StringComparison.OrdinalIgnoreCase))
  1868. {
  1869. /*
  1870. [base]: HW scaling video to OutputSize
  1871. [sub]: SW scaling subtitle to FixedOutputSize
  1872. [base][sub]: SW overlay
  1873. */
  1874. retStr = outputSizeParam.IsEmpty
  1875. ? " -filter_complex \"[{0}:{1}]{4}[sub];[0:{2}]hwdownload[base];[base][sub]overlay,format=nv12,hwupload\""
  1876. : " -filter_complex \"[{0}:{1}]{4}[sub];[0:{2}]{3},hwdownload[base];[base][sub]overlay,format=nv12,hwupload\"";
  1877. }
  1878. // If we're hardware VAAPI decoding and software encoding, download frames from the decoder first
  1879. else if (_mediaEncoder.SupportsHwaccel("vaapi") && videoDecoder.IndexOf("vaapi", StringComparison.OrdinalIgnoreCase) != -1
  1880. && (string.Equals(outputVideoCodec, "libx264", StringComparison.OrdinalIgnoreCase)
  1881. || string.Equals(outputVideoCodec, "libx265", StringComparison.OrdinalIgnoreCase)))
  1882. {
  1883. /*
  1884. [base]: SW scaling video to OutputSize
  1885. [sub]: SW scaling subtitle to FixedOutputSize
  1886. [base][sub]: SW overlay
  1887. */
  1888. retStr = outputSizeParam.IsEmpty
  1889. ? " -filter_complex \"[{0}:{1}]{4}[sub];[0:{2}][sub]overlay\""
  1890. : " -filter_complex \"[{0}:{1}]{4}[sub];[0:{2}]{3}[base];[base][sub]overlay\"";
  1891. }
  1892. else if (string.Equals(outputVideoCodec, "h264_qsv", StringComparison.OrdinalIgnoreCase)
  1893. || string.Equals(outputVideoCodec, "hevc_qsv", StringComparison.OrdinalIgnoreCase))
  1894. {
  1895. /*
  1896. QSV in FFMpeg can now setup hardware overlay for transcodes.
  1897. For software decoding and hardware encoding option, frames must be hwuploaded into hardware
  1898. with fixed frame size.
  1899. Currently only supports linux.
  1900. */
  1901. if (isTonemappingSupportedOnQsv && isVppTonemappingSupported)
  1902. {
  1903. retStr = " -filter_complex \"[{0}:{1}]{4}[sub];[0:{2}]{3},hwdownload,format=nv12[base];[base][sub]overlay\"";
  1904. }
  1905. else if (isLinux)
  1906. {
  1907. retStr = outputSizeParam.IsEmpty
  1908. ? " -filter_complex \"[{0}:{1}]{4}[sub];[0:{2}][sub]overlay_qsv\""
  1909. : " -filter_complex \"[{0}:{1}]{4}[sub];[0:{2}]{3}[base];[base][sub]overlay_qsv\"";
  1910. }
  1911. }
  1912. else if (isNvdecDecoder && isNvencEncoder)
  1913. {
  1914. if (isCudaOverlaySupported && isCudaFormatConversionSupported)
  1915. {
  1916. retStr = outputSizeParam.IsEmpty
  1917. ? " -filter_complex \"[{0}:{1}]{4}[sub];[0:{2}]scale_cuda=format=yuv420p[base];[base][sub]overlay_cuda\""
  1918. : " -filter_complex \"[{0}:{1}]{4}[sub];[0:{2}]{3}[base];[base][sub]overlay_cuda\"";
  1919. }
  1920. else
  1921. {
  1922. retStr = outputSizeParam.IsEmpty
  1923. ? " -filter_complex \"[{0}:{1}]{4}[sub];[0:{2}][sub]overlay,format=nv12|yuv420p,hwupload_cuda\""
  1924. : " -filter_complex \"[{0}:{1}]{4}[sub];[0:{2}]{3}[base];[base][sub]overlay,format=nv12|yuv420p,hwupload_cuda\"";
  1925. }
  1926. }
  1927. return string.Format(
  1928. CultureInfo.InvariantCulture,
  1929. retStr,
  1930. mapPrefix,
  1931. subtitleStreamIndex,
  1932. state.VideoStream.Index,
  1933. outputSizeParam.ToString(),
  1934. videoSizeParam);
  1935. }
  1936. public static (int? width, int? height) GetFixedOutputSize(
  1937. int? videoWidth,
  1938. int? videoHeight,
  1939. int? requestedWidth,
  1940. int? requestedHeight,
  1941. int? requestedMaxWidth,
  1942. int? requestedMaxHeight)
  1943. {
  1944. if (!videoWidth.HasValue && !requestedWidth.HasValue)
  1945. {
  1946. return (null, null);
  1947. }
  1948. if (!videoHeight.HasValue && !requestedHeight.HasValue)
  1949. {
  1950. return (null, null);
  1951. }
  1952. decimal inputWidth = Convert.ToDecimal(videoWidth ?? requestedWidth, CultureInfo.InvariantCulture);
  1953. decimal inputHeight = Convert.ToDecimal(videoHeight ?? requestedHeight, CultureInfo.InvariantCulture);
  1954. decimal outputWidth = requestedWidth.HasValue ? Convert.ToDecimal(requestedWidth.Value) : inputWidth;
  1955. decimal outputHeight = requestedHeight.HasValue ? Convert.ToDecimal(requestedHeight.Value) : inputHeight;
  1956. decimal maximumWidth = requestedMaxWidth.HasValue ? Convert.ToDecimal(requestedMaxWidth.Value) : outputWidth;
  1957. decimal maximumHeight = requestedMaxHeight.HasValue ? Convert.ToDecimal(requestedMaxHeight.Value) : outputHeight;
  1958. if (outputWidth > maximumWidth || outputHeight > maximumHeight)
  1959. {
  1960. var scale = Math.Min(maximumWidth / outputWidth, maximumHeight / outputHeight);
  1961. outputWidth = Math.Min(maximumWidth, Math.Truncate(outputWidth * scale));
  1962. outputHeight = Math.Min(maximumHeight, Math.Truncate(outputHeight * scale));
  1963. }
  1964. outputWidth = 2 * Math.Truncate(outputWidth / 2);
  1965. outputHeight = 2 * Math.Truncate(outputHeight / 2);
  1966. return (Convert.ToInt32(outputWidth), Convert.ToInt32(outputHeight));
  1967. }
  1968. public List<string> GetScalingFilters(
  1969. EncodingJobInfo state,
  1970. EncodingOptions options,
  1971. int? videoWidth,
  1972. int? videoHeight,
  1973. Video3DFormat? threedFormat,
  1974. string videoDecoder,
  1975. string videoEncoder,
  1976. int? requestedWidth,
  1977. int? requestedHeight,
  1978. int? requestedMaxWidth,
  1979. int? requestedMaxHeight)
  1980. {
  1981. var filters = new List<string>();
  1982. var (width, height) = GetFixedOutputSize(
  1983. videoWidth,
  1984. videoHeight,
  1985. requestedWidth,
  1986. requestedHeight,
  1987. requestedMaxWidth,
  1988. requestedMaxHeight);
  1989. if ((string.Equals(videoEncoder, "h264_vaapi", StringComparison.OrdinalIgnoreCase)
  1990. || string.Equals(videoEncoder, "h264_qsv", StringComparison.OrdinalIgnoreCase)
  1991. || string.Equals(videoEncoder, "hevc_vaapi", StringComparison.OrdinalIgnoreCase)
  1992. || string.Equals(videoEncoder, "hevc_qsv", StringComparison.OrdinalIgnoreCase))
  1993. && width.HasValue
  1994. && height.HasValue)
  1995. {
  1996. // Given the input dimensions (inputWidth, inputHeight), determine the output dimensions
  1997. // (outputWidth, outputHeight). The user may request precise output dimensions or maximum
  1998. // output dimensions. Output dimensions are guaranteed to be even.
  1999. var outputWidth = width.Value;
  2000. var outputHeight = height.Value;
  2001. var qsv_or_vaapi = string.Equals(videoEncoder, "h264_qsv", StringComparison.OrdinalIgnoreCase)
  2002. || string.Equals(videoEncoder, "hevc_qsv", StringComparison.OrdinalIgnoreCase);
  2003. var isDeintEnabled = state.DeInterlace("h264", true)
  2004. || state.DeInterlace("avc", true)
  2005. || state.DeInterlace("h265", true)
  2006. || state.DeInterlace("hevc", true);
  2007. var isVaapiDecoder = videoDecoder.Contains("vaapi", StringComparison.OrdinalIgnoreCase);
  2008. var isVaapiH264Encoder = videoEncoder.Contains("h264_vaapi", StringComparison.OrdinalIgnoreCase);
  2009. var isVaapiHevcEncoder = videoEncoder.Contains("hevc_vaapi", StringComparison.OrdinalIgnoreCase);
  2010. var isQsvH264Encoder = videoEncoder.Contains("h264_qsv", StringComparison.OrdinalIgnoreCase);
  2011. var isQsvHevcEncoder = videoEncoder.Contains("hevc_qsv", StringComparison.OrdinalIgnoreCase);
  2012. var isOpenclTonemappingSupported = IsOpenclTonemappingSupported(state, options);
  2013. var isVppTonemappingSupported = IsVppTonemappingSupported(state, options);
  2014. var isTonemappingSupportedOnVaapi = string.Equals(options.HardwareAccelerationType, "vaapi", StringComparison.OrdinalIgnoreCase) && isVaapiDecoder && (isVaapiH264Encoder || isVaapiHevcEncoder);
  2015. var isTonemappingSupportedOnQsv = string.Equals(options.HardwareAccelerationType, "qsv", StringComparison.OrdinalIgnoreCase) && isVaapiDecoder && (isQsvH264Encoder || isQsvHevcEncoder);
  2016. var isP010PixFmtRequired = (isTonemappingSupportedOnVaapi && (isOpenclTonemappingSupported || isVppTonemappingSupported))
  2017. || (isTonemappingSupportedOnQsv && isVppTonemappingSupported);
  2018. var outputPixFmt = "format=nv12";
  2019. if (isP010PixFmtRequired)
  2020. {
  2021. outputPixFmt = "format=p010";
  2022. }
  2023. if (isTonemappingSupportedOnQsv && isVppTonemappingSupported)
  2024. {
  2025. qsv_or_vaapi = false;
  2026. }
  2027. if (!videoWidth.HasValue
  2028. || outputWidth != videoWidth.Value
  2029. || !videoHeight.HasValue
  2030. || outputHeight != videoHeight.Value)
  2031. {
  2032. // Force nv12 pixel format to enable 10-bit to 8-bit colour conversion.
  2033. // use vpp_qsv filter to avoid green bar when the fixed output size is requested.
  2034. filters.Add(
  2035. string.Format(
  2036. CultureInfo.InvariantCulture,
  2037. "{0}=w={1}:h={2}{3}{4}",
  2038. qsv_or_vaapi ? "vpp_qsv" : "scale_vaapi",
  2039. outputWidth,
  2040. outputHeight,
  2041. ":" + outputPixFmt,
  2042. (qsv_or_vaapi && isDeintEnabled) ? ":deinterlace=1" : string.Empty));
  2043. }
  2044. // Assert 10-bit is P010 so as we can avoid the extra scaler to get a bit more fps on high res HDR videos.
  2045. else if (!isP010PixFmtRequired)
  2046. {
  2047. filters.Add(
  2048. string.Format(
  2049. CultureInfo.InvariantCulture,
  2050. "{0}={1}{2}",
  2051. qsv_or_vaapi ? "vpp_qsv" : "scale_vaapi",
  2052. outputPixFmt,
  2053. (qsv_or_vaapi && isDeintEnabled) ? ":deinterlace=1" : string.Empty));
  2054. }
  2055. }
  2056. else if ((videoDecoder ?? string.Empty).Contains("cuda", StringComparison.OrdinalIgnoreCase)
  2057. && width.HasValue
  2058. && height.HasValue)
  2059. {
  2060. var outputWidth = width.Value;
  2061. var outputHeight = height.Value;
  2062. var isNvencEncoder = videoEncoder.Contains("nvenc", StringComparison.OrdinalIgnoreCase);
  2063. var isOpenclTonemappingSupported = IsOpenclTonemappingSupported(state, options);
  2064. var isCudaTonemappingSupported = IsCudaTonemappingSupported(state, options);
  2065. var isTonemappingSupportedOnNvenc = string.Equals(options.HardwareAccelerationType, "nvenc", StringComparison.OrdinalIgnoreCase);
  2066. var mediaEncoderVersion = _mediaEncoder.GetMediaEncoderVersion();
  2067. var isCudaOverlaySupported = _mediaEncoder.SupportsFilter("overlay_cuda") && mediaEncoderVersion != null && mediaEncoderVersion >= _minVersionForCudaOverlay;
  2068. var isCudaFormatConversionSupported = _mediaEncoder.SupportsFilterWithOption(FilterOptionType.ScaleCudaFormat);
  2069. var hasGraphicalSubs = state.SubtitleStream != null && !state.SubtitleStream.IsTextSubtitleStream && state.SubtitleDeliveryMethod == SubtitleDeliveryMethod.Encode;
  2070. var outputPixFmt = string.Empty;
  2071. if (isCudaFormatConversionSupported)
  2072. {
  2073. outputPixFmt = (hasGraphicalSubs && isCudaOverlaySupported && isNvencEncoder)
  2074. ? "format=yuv420p"
  2075. : "format=nv12";
  2076. if ((isOpenclTonemappingSupported || isCudaTonemappingSupported)
  2077. && isTonemappingSupportedOnNvenc)
  2078. {
  2079. outputPixFmt = "format=p010";
  2080. }
  2081. }
  2082. if (!videoWidth.HasValue
  2083. || outputWidth != videoWidth.Value
  2084. || !videoHeight.HasValue
  2085. || outputHeight != videoHeight.Value)
  2086. {
  2087. filters.Add(
  2088. string.Format(
  2089. CultureInfo.InvariantCulture,
  2090. "scale_cuda=w={0}:h={1}{2}",
  2091. outputWidth,
  2092. outputHeight,
  2093. isCudaFormatConversionSupported ? (":" + outputPixFmt) : string.Empty));
  2094. }
  2095. else if (isCudaFormatConversionSupported)
  2096. {
  2097. filters.Add(
  2098. string.Format(
  2099. CultureInfo.InvariantCulture,
  2100. "scale_cuda={0}",
  2101. outputPixFmt));
  2102. }
  2103. }
  2104. else if ((videoDecoder ?? string.Empty).IndexOf("cuvid", StringComparison.OrdinalIgnoreCase) != -1
  2105. && width.HasValue
  2106. && height.HasValue)
  2107. {
  2108. // Nothing to do, it's handled as an input resize filter
  2109. }
  2110. else
  2111. {
  2112. var isExynosV4L2 = string.Equals(videoEncoder, "h264_v4l2m2m", StringComparison.OrdinalIgnoreCase);
  2113. // If fixed dimensions were supplied
  2114. if (requestedWidth.HasValue && requestedHeight.HasValue)
  2115. {
  2116. if (isExynosV4L2)
  2117. {
  2118. var widthParam = requestedWidth.Value.ToString(CultureInfo.InvariantCulture);
  2119. var heightParam = requestedHeight.Value.ToString(CultureInfo.InvariantCulture);
  2120. filters.Add(
  2121. string.Format(
  2122. CultureInfo.InvariantCulture,
  2123. "scale=trunc({0}/64)*64:trunc({1}/2)*2",
  2124. widthParam,
  2125. heightParam));
  2126. }
  2127. else
  2128. {
  2129. filters.Add(GetFixedSizeScalingFilter(threedFormat, requestedWidth.Value, requestedHeight.Value));
  2130. }
  2131. }
  2132. // 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
  2133. else if (requestedMaxWidth.HasValue && requestedMaxHeight.HasValue)
  2134. {
  2135. var maxWidthParam = requestedMaxWidth.Value.ToString(CultureInfo.InvariantCulture);
  2136. var maxHeightParam = requestedMaxHeight.Value.ToString(CultureInfo.InvariantCulture);
  2137. if (isExynosV4L2)
  2138. {
  2139. filters.Add(
  2140. string.Format(
  2141. CultureInfo.InvariantCulture,
  2142. "scale=trunc(min(max(iw\\,ih*dar)\\,min({0}\\,{1}*dar))/64)*64:trunc(min(max(iw/dar\\,ih)\\,min({0}/dar\\,{1}))/2)*2",
  2143. maxWidthParam,
  2144. maxHeightParam));
  2145. }
  2146. else
  2147. {
  2148. filters.Add(
  2149. string.Format(
  2150. CultureInfo.InvariantCulture,
  2151. "scale=trunc(min(max(iw\\,ih*dar)\\,min({0}\\,{1}*dar))/2)*2:trunc(min(max(iw/dar\\,ih)\\,min({0}/dar\\,{1}))/2)*2",
  2152. maxWidthParam,
  2153. maxHeightParam));
  2154. }
  2155. }
  2156. // If a fixed width was requested
  2157. else if (requestedWidth.HasValue)
  2158. {
  2159. if (threedFormat.HasValue)
  2160. {
  2161. // This method can handle 0 being passed in for the requested height
  2162. filters.Add(GetFixedSizeScalingFilter(threedFormat, requestedWidth.Value, 0));
  2163. }
  2164. else
  2165. {
  2166. var widthParam = requestedWidth.Value.ToString(CultureInfo.InvariantCulture);
  2167. filters.Add(
  2168. string.Format(
  2169. CultureInfo.InvariantCulture,
  2170. "scale={0}:trunc(ow/a/2)*2",
  2171. widthParam));
  2172. }
  2173. }
  2174. // If a fixed height was requested
  2175. else if (requestedHeight.HasValue)
  2176. {
  2177. var heightParam = requestedHeight.Value.ToString(CultureInfo.InvariantCulture);
  2178. if (isExynosV4L2)
  2179. {
  2180. filters.Add(
  2181. string.Format(
  2182. CultureInfo.InvariantCulture,
  2183. "scale=trunc(oh*a/64)*64:{0}",
  2184. heightParam));
  2185. }
  2186. else
  2187. {
  2188. filters.Add(
  2189. string.Format(
  2190. CultureInfo.InvariantCulture,
  2191. "scale=trunc(oh*a/2)*2:{0}",
  2192. heightParam));
  2193. }
  2194. }
  2195. // If a max width was requested
  2196. else if (requestedMaxWidth.HasValue)
  2197. {
  2198. var maxWidthParam = requestedMaxWidth.Value.ToString(CultureInfo.InvariantCulture);
  2199. if (isExynosV4L2)
  2200. {
  2201. filters.Add(
  2202. string.Format(
  2203. CultureInfo.InvariantCulture,
  2204. "scale=trunc(min(max(iw\\,ih*dar)\\,{0})/64)*64:trunc(ow/dar/2)*2",
  2205. maxWidthParam));
  2206. }
  2207. else
  2208. {
  2209. filters.Add(
  2210. string.Format(
  2211. CultureInfo.InvariantCulture,
  2212. "scale=trunc(min(max(iw\\,ih*dar)\\,{0})/2)*2:trunc(ow/dar/2)*2",
  2213. maxWidthParam));
  2214. }
  2215. }
  2216. // If a max height was requested
  2217. else if (requestedMaxHeight.HasValue)
  2218. {
  2219. var maxHeightParam = requestedMaxHeight.Value.ToString(CultureInfo.InvariantCulture);
  2220. if (isExynosV4L2)
  2221. {
  2222. filters.Add(
  2223. string.Format(
  2224. CultureInfo.InvariantCulture,
  2225. "scale=trunc(oh*a/64)*64:min(max(iw/dar\\,ih)\\,{0})",
  2226. maxHeightParam));
  2227. }
  2228. else
  2229. {
  2230. filters.Add(
  2231. string.Format(
  2232. CultureInfo.InvariantCulture,
  2233. "scale=trunc(oh*a/2)*2:min(max(iw/dar\\,ih)\\,{0})",
  2234. maxHeightParam));
  2235. }
  2236. }
  2237. }
  2238. return filters;
  2239. }
  2240. private string GetFixedSizeScalingFilter(Video3DFormat? threedFormat, int requestedWidth, int requestedHeight)
  2241. {
  2242. var widthParam = requestedWidth.ToString(CultureInfo.InvariantCulture);
  2243. var heightParam = requestedHeight.ToString(CultureInfo.InvariantCulture);
  2244. string filter = null;
  2245. if (threedFormat.HasValue)
  2246. {
  2247. switch (threedFormat.Value)
  2248. {
  2249. case Video3DFormat.HalfSideBySide:
  2250. 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";
  2251. // 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.
  2252. break;
  2253. case Video3DFormat.FullSideBySide:
  2254. 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";
  2255. // fsbs crop width in half,set the display aspect,crop out any black bars we may have made the scale width to requestedWidth.
  2256. break;
  2257. case Video3DFormat.HalfTopAndBottom:
  2258. 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";
  2259. // 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
  2260. break;
  2261. case Video3DFormat.FullTopAndBottom:
  2262. 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";
  2263. // ftab crop height in half, set the display aspect,crop out any black bars we may have made the scale width to requestedWidth
  2264. break;
  2265. default:
  2266. break;
  2267. }
  2268. }
  2269. // default
  2270. if (filter == null)
  2271. {
  2272. if (requestedHeight > 0)
  2273. {
  2274. filter = "scale=trunc({0}/2)*2:trunc({1}/2)*2";
  2275. }
  2276. else
  2277. {
  2278. filter = "scale={0}:trunc({0}/dar/2)*2";
  2279. }
  2280. }
  2281. return string.Format(CultureInfo.InvariantCulture, filter, widthParam, heightParam);
  2282. }
  2283. /// <summary>
  2284. /// Gets the output size parameter.
  2285. /// </summary>
  2286. /// <param name="state">Encoding state.</param>
  2287. /// <param name="options">Encoding options.</param>
  2288. /// <param name="outputVideoCodec">Video codec to use.</param>
  2289. /// <returns>The output size parameter.</returns>
  2290. public string GetOutputSizeParam(
  2291. EncodingJobInfo state,
  2292. EncodingOptions options,
  2293. string outputVideoCodec)
  2294. {
  2295. string filters = GetOutputSizeParamInternal(state, options, outputVideoCodec);
  2296. return string.IsNullOrEmpty(filters) ? string.Empty : " -vf \"" + filters + "\"";
  2297. }
  2298. /// <summary>
  2299. /// Gets the output size parameter.
  2300. /// If we're going to put a fixed size on the command line, this will calculate it.
  2301. /// </summary>
  2302. /// <param name="state">Encoding state.</param>
  2303. /// <param name="options">Encoding options.</param>
  2304. /// <param name="outputVideoCodec">Video codec to use.</param>
  2305. /// <returns>The output size parameter.</returns>
  2306. public string GetOutputSizeParamInternal(
  2307. EncodingJobInfo state,
  2308. EncodingOptions options,
  2309. string outputVideoCodec)
  2310. {
  2311. // http://sonnati.wordpress.com/2012/10/19/ffmpeg-the-swiss-army-knife-of-internet-streaming-part-vi/
  2312. var request = state.BaseRequest;
  2313. var videoStream = state.VideoStream;
  2314. var filters = new List<string>();
  2315. var videoDecoder = GetHardwareAcceleratedVideoDecoder(state, options) ?? string.Empty;
  2316. var inputWidth = videoStream?.Width;
  2317. var inputHeight = videoStream?.Height;
  2318. var threeDFormat = state.MediaSource.Video3DFormat;
  2319. var isSwDecoder = string.IsNullOrEmpty(videoDecoder);
  2320. var isD3d11vaDecoder = videoDecoder.IndexOf("d3d11va", StringComparison.OrdinalIgnoreCase) != -1;
  2321. var isVaapiDecoder = videoDecoder.IndexOf("vaapi", StringComparison.OrdinalIgnoreCase) != -1;
  2322. var isVaapiEncoder = outputVideoCodec.IndexOf("vaapi", StringComparison.OrdinalIgnoreCase) != -1;
  2323. var isVaapiH264Encoder = outputVideoCodec.IndexOf("h264_vaapi", StringComparison.OrdinalIgnoreCase) != -1;
  2324. var isVaapiHevcEncoder = outputVideoCodec.IndexOf("hevc_vaapi", StringComparison.OrdinalIgnoreCase) != -1;
  2325. var isQsvH264Encoder = outputVideoCodec.IndexOf("h264_qsv", StringComparison.OrdinalIgnoreCase) != -1;
  2326. var isQsvHevcEncoder = outputVideoCodec.IndexOf("hevc_qsv", StringComparison.OrdinalIgnoreCase) != -1;
  2327. var isNvdecDecoder = videoDecoder.Contains("cuda", StringComparison.OrdinalIgnoreCase);
  2328. var isNvencEncoder = outputVideoCodec.Contains("nvenc", StringComparison.OrdinalIgnoreCase);
  2329. var isCuvidH264Decoder = videoDecoder.Contains("h264_cuvid", StringComparison.OrdinalIgnoreCase);
  2330. var isCuvidHevcDecoder = videoDecoder.Contains("hevc_cuvid", StringComparison.OrdinalIgnoreCase);
  2331. var isCuvidVp9Decoder = videoDecoder.Contains("vp9_cuvid", StringComparison.OrdinalIgnoreCase);
  2332. var isLibX264Encoder = outputVideoCodec.IndexOf("libx264", StringComparison.OrdinalIgnoreCase) != -1;
  2333. var isLibX265Encoder = outputVideoCodec.IndexOf("libx265", StringComparison.OrdinalIgnoreCase) != -1;
  2334. var isLinux = OperatingSystem.IsLinux();
  2335. var isColorDepth10 = IsColorDepth10(state);
  2336. var isTonemappingSupportedOnNvenc = string.Equals(options.HardwareAccelerationType, "nvenc", StringComparison.OrdinalIgnoreCase) && (isNvdecDecoder || isCuvidHevcDecoder || isCuvidVp9Decoder || isSwDecoder);
  2337. var isTonemappingSupportedOnAmf = string.Equals(options.HardwareAccelerationType, "amf", StringComparison.OrdinalIgnoreCase) && (isD3d11vaDecoder || isSwDecoder);
  2338. var isTonemappingSupportedOnVaapi = string.Equals(options.HardwareAccelerationType, "vaapi", StringComparison.OrdinalIgnoreCase) && isVaapiDecoder && (isVaapiH264Encoder || isVaapiHevcEncoder);
  2339. var isTonemappingSupportedOnQsv = string.Equals(options.HardwareAccelerationType, "qsv", StringComparison.OrdinalIgnoreCase) && isVaapiDecoder && (isQsvH264Encoder || isQsvHevcEncoder);
  2340. var isOpenclTonemappingSupported = IsOpenclTonemappingSupported(state, options);
  2341. var isVppTonemappingSupported = IsVppTonemappingSupported(state, options);
  2342. var isCudaTonemappingSupported = IsCudaTonemappingSupported(state, options);
  2343. var mediaEncoderVersion = _mediaEncoder.GetMediaEncoderVersion();
  2344. var isCudaOverlaySupported = _mediaEncoder.SupportsFilter("overlay_cuda") && mediaEncoderVersion != null && mediaEncoderVersion >= _minVersionForCudaOverlay;
  2345. var hasSubs = state.SubtitleStream != null && state.SubtitleDeliveryMethod == SubtitleDeliveryMethod.Encode;
  2346. var hasTextSubs = state.SubtitleStream != null && state.SubtitleStream.IsTextSubtitleStream && state.SubtitleDeliveryMethod == SubtitleDeliveryMethod.Encode;
  2347. var hasGraphicalSubs = state.SubtitleStream != null && !state.SubtitleStream.IsTextSubtitleStream && state.SubtitleDeliveryMethod == SubtitleDeliveryMethod.Encode;
  2348. // If double rate deinterlacing is enabled and the input framerate is 30fps or below, otherwise the output framerate will be too high for many devices
  2349. var doubleRateDeinterlace = options.DeinterlaceDoubleRate && (videoStream?.AverageFrameRate ?? 60) <= 30;
  2350. var isScalingInAdvance = false;
  2351. var isCudaDeintInAdvance = false;
  2352. var isHwuploadCudaRequired = false;
  2353. var isNoTonemapFilterApplied = true;
  2354. var isDeinterlaceH264 = state.DeInterlace("h264", true) || state.DeInterlace("avc", true);
  2355. var isDeinterlaceHevc = state.DeInterlace("h265", true) || state.DeInterlace("hevc", true);
  2356. // Add OpenCL tonemapping filter for NVENC/AMF/VAAPI.
  2357. if ((isTonemappingSupportedOnNvenc && !isCudaTonemappingSupported) || isTonemappingSupportedOnAmf || (isTonemappingSupportedOnVaapi && !isVppTonemappingSupported))
  2358. {
  2359. // NVIDIA Pascal and Turing or higher are recommended.
  2360. // AMD Polaris and Vega or higher are recommended.
  2361. // Intel Kaby Lake or newer is required.
  2362. if (isOpenclTonemappingSupported)
  2363. {
  2364. isNoTonemapFilterApplied = false;
  2365. var inputHdrParams = GetInputHdrParams(videoStream.ColorTransfer);
  2366. if (!string.IsNullOrEmpty(inputHdrParams))
  2367. {
  2368. filters.Add(inputHdrParams);
  2369. }
  2370. var parameters = "tonemap_opencl=format=nv12:primaries=bt709:transfer=bt709:matrix=bt709:tonemap={0}:desat={1}:threshold={2}:peak={3}";
  2371. if (options.TonemappingParam != 0)
  2372. {
  2373. parameters += ":param={4}";
  2374. }
  2375. if (!string.Equals(options.TonemappingRange, "auto", StringComparison.OrdinalIgnoreCase))
  2376. {
  2377. parameters += ":range={5}";
  2378. }
  2379. if (isSwDecoder || isD3d11vaDecoder)
  2380. {
  2381. isScalingInAdvance = true;
  2382. // Add zscale filter before tone mapping filter for performance.
  2383. var (width, height) = GetFixedOutputSize(inputWidth, inputHeight, request.Width, request.Height, request.MaxWidth, request.MaxHeight);
  2384. if (width.HasValue && height.HasValue)
  2385. {
  2386. filters.Add(
  2387. string.Format(
  2388. CultureInfo.InvariantCulture,
  2389. "zscale=s={0}x{1}",
  2390. width.Value,
  2391. height.Value));
  2392. }
  2393. // Convert to hardware pixel format p010 when using SW decoder.
  2394. filters.Add("format=p010");
  2395. }
  2396. if ((isDeinterlaceH264 || isDeinterlaceHevc) && isNvdecDecoder)
  2397. {
  2398. isCudaDeintInAdvance = true;
  2399. filters.Add(
  2400. string.Format(
  2401. CultureInfo.InvariantCulture,
  2402. "yadif_cuda={0}:-1:0",
  2403. doubleRateDeinterlace ? "1" : "0"));
  2404. }
  2405. if (isVaapiDecoder || isNvdecDecoder)
  2406. {
  2407. isScalingInAdvance = true;
  2408. filters.AddRange(
  2409. GetScalingFilters(
  2410. state,
  2411. options,
  2412. inputWidth,
  2413. inputHeight,
  2414. threeDFormat,
  2415. videoDecoder,
  2416. outputVideoCodec,
  2417. request.Width,
  2418. request.Height,
  2419. request.MaxWidth,
  2420. request.MaxHeight));
  2421. }
  2422. // hwmap the HDR data to opencl device by cl-va p010 interop.
  2423. if (isVaapiDecoder)
  2424. {
  2425. filters.Add("hwmap");
  2426. }
  2427. // convert cuda device data to p010 host data.
  2428. if (isNvdecDecoder)
  2429. {
  2430. filters.Add("hwdownload,format=p010");
  2431. }
  2432. if (isNvdecDecoder
  2433. || isCuvidHevcDecoder
  2434. || isCuvidVp9Decoder
  2435. || isSwDecoder
  2436. || isD3d11vaDecoder)
  2437. {
  2438. // Upload the HDR10 or HLG data to the OpenCL device,
  2439. // use tonemap_opencl filter for tone mapping,
  2440. // and then download the SDR data to memory.
  2441. filters.Add("hwupload");
  2442. }
  2443. // Fallback to hable if bt2390 is chosen but not supported in tonemap_opencl.
  2444. var isBt2390SupportedInOpenclTonemap = _mediaEncoder.SupportsFilterWithOption(FilterOptionType.TonemapOpenclBt2390);
  2445. if (string.Equals(options.TonemappingAlgorithm, "bt2390", StringComparison.OrdinalIgnoreCase)
  2446. && !isBt2390SupportedInOpenclTonemap)
  2447. {
  2448. options.TonemappingAlgorithm = "hable";
  2449. }
  2450. filters.Add(
  2451. string.Format(
  2452. CultureInfo.InvariantCulture,
  2453. parameters,
  2454. options.TonemappingAlgorithm,
  2455. options.TonemappingDesat,
  2456. options.TonemappingThreshold,
  2457. options.TonemappingPeak,
  2458. options.TonemappingParam,
  2459. options.TonemappingRange));
  2460. if (isNvdecDecoder
  2461. || isCuvidHevcDecoder
  2462. || isCuvidVp9Decoder
  2463. || isSwDecoder
  2464. || isD3d11vaDecoder)
  2465. {
  2466. filters.Add("hwdownload");
  2467. filters.Add("format=nv12");
  2468. }
  2469. if (isNvdecDecoder && isNvencEncoder)
  2470. {
  2471. isHwuploadCudaRequired = true;
  2472. }
  2473. if (isVaapiDecoder)
  2474. {
  2475. // Reverse the data route from opencl to vaapi.
  2476. filters.Add("hwmap=derive_device=vaapi:reverse=1");
  2477. }
  2478. var outputSdrParams = GetOutputSdrParams(options.TonemappingRange);
  2479. if (!string.IsNullOrEmpty(outputSdrParams))
  2480. {
  2481. filters.Add(outputSdrParams);
  2482. }
  2483. }
  2484. }
  2485. // When the input may or may not be hardware VAAPI decodable.
  2486. if ((isVaapiH264Encoder || isVaapiHevcEncoder)
  2487. && !(isTonemappingSupportedOnVaapi && (isOpenclTonemappingSupported || isVppTonemappingSupported)))
  2488. {
  2489. filters.Add("format=nv12|vaapi");
  2490. filters.Add("hwupload");
  2491. }
  2492. // When burning in graphical subtitles using overlay_qsv, upload videostream to the same qsv context.
  2493. else if (isLinux && hasGraphicalSubs && (isQsvH264Encoder || isQsvHevcEncoder)
  2494. && !(isTonemappingSupportedOnQsv && isVppTonemappingSupported))
  2495. {
  2496. filters.Add("hwupload=extra_hw_frames=64");
  2497. }
  2498. // If we're hardware VAAPI decoding and software encoding, download frames from the decoder first.
  2499. else if ((IsVaapiSupported(state) && isVaapiDecoder) && (isLibX264Encoder || isLibX265Encoder)
  2500. && !(isTonemappingSupportedOnQsv && isVppTonemappingSupported))
  2501. {
  2502. var codec = videoStream.Codec;
  2503. // Assert 10-bit hardware VAAPI decodable
  2504. if (isColorDepth10 && (string.Equals(codec, "hevc", StringComparison.OrdinalIgnoreCase)
  2505. || string.Equals(codec, "h265", StringComparison.OrdinalIgnoreCase)
  2506. || string.Equals(codec, "vp9", StringComparison.OrdinalIgnoreCase)))
  2507. {
  2508. /*
  2509. Download data from GPU to CPU as p010le format.
  2510. Colorspace conversion is unnecessary here as libx264 will handle it.
  2511. If this step is missing, it will fail on AMD but not on intel.
  2512. */
  2513. filters.Add("hwdownload");
  2514. filters.Add("format=p010le");
  2515. }
  2516. // Assert 8-bit hardware VAAPI decodable
  2517. else if (!isColorDepth10)
  2518. {
  2519. filters.Add("hwdownload");
  2520. filters.Add("format=nv12");
  2521. }
  2522. }
  2523. // Add hardware deinterlace filter before scaling filter.
  2524. if (isDeinterlaceH264 || isDeinterlaceHevc)
  2525. {
  2526. if (isVaapiEncoder
  2527. || (isTonemappingSupportedOnQsv && isVppTonemappingSupported))
  2528. {
  2529. filters.Add(
  2530. string.Format(
  2531. CultureInfo.InvariantCulture,
  2532. "deinterlace_vaapi=rate={0}",
  2533. doubleRateDeinterlace ? "field" : "frame"));
  2534. }
  2535. else if (isNvdecDecoder && !isCudaDeintInAdvance)
  2536. {
  2537. filters.Add(
  2538. string.Format(
  2539. CultureInfo.InvariantCulture,
  2540. "yadif_cuda={0}:-1:0",
  2541. doubleRateDeinterlace ? "1" : "0"));
  2542. }
  2543. }
  2544. // Add software deinterlace filter before scaling filter.
  2545. if ((isDeinterlaceH264 || isDeinterlaceHevc)
  2546. && !isVaapiH264Encoder
  2547. && !isVaapiHevcEncoder
  2548. && !isQsvH264Encoder
  2549. && !isQsvHevcEncoder
  2550. && !isNvdecDecoder
  2551. && !isCuvidH264Decoder)
  2552. {
  2553. if (string.Equals(options.DeinterlaceMethod, "bwdif", StringComparison.OrdinalIgnoreCase))
  2554. {
  2555. filters.Add(
  2556. string.Format(
  2557. CultureInfo.InvariantCulture,
  2558. "bwdif={0}:-1:0",
  2559. doubleRateDeinterlace ? "1" : "0"));
  2560. }
  2561. else
  2562. {
  2563. filters.Add(
  2564. string.Format(
  2565. CultureInfo.InvariantCulture,
  2566. "yadif={0}:-1:0",
  2567. doubleRateDeinterlace ? "1" : "0"));
  2568. }
  2569. }
  2570. // Add scaling filter: scale_*=format=nv12 or scale_*=w=*:h=*:format=nv12 or scale=expr
  2571. if (!isScalingInAdvance)
  2572. {
  2573. filters.AddRange(
  2574. GetScalingFilters(
  2575. state,
  2576. options,
  2577. inputWidth,
  2578. inputHeight,
  2579. threeDFormat,
  2580. videoDecoder,
  2581. outputVideoCodec,
  2582. request.Width,
  2583. request.Height,
  2584. request.MaxWidth,
  2585. request.MaxHeight));
  2586. }
  2587. // Add Cuda tonemapping filter.
  2588. if (isNvdecDecoder && isCudaTonemappingSupported)
  2589. {
  2590. isNoTonemapFilterApplied = false;
  2591. var inputHdrParams = GetInputHdrParams(videoStream.ColorTransfer);
  2592. if (!string.IsNullOrEmpty(inputHdrParams))
  2593. {
  2594. filters.Add(inputHdrParams);
  2595. }
  2596. var parameters = (hasGraphicalSubs && isCudaOverlaySupported && isNvencEncoder)
  2597. ? "tonemap_cuda=format=yuv420p:primaries=bt709:transfer=bt709:matrix=bt709:tonemap={0}:peak={1}:desat={2}"
  2598. : "tonemap_cuda=format=nv12:primaries=bt709:transfer=bt709:matrix=bt709:tonemap={0}:peak={1}:desat={2}";
  2599. if (options.TonemappingParam != 0)
  2600. {
  2601. parameters += ":param={3}";
  2602. }
  2603. if (!string.Equals(options.TonemappingRange, "auto", StringComparison.OrdinalIgnoreCase))
  2604. {
  2605. parameters += ":range={4}";
  2606. }
  2607. filters.Add(
  2608. string.Format(
  2609. CultureInfo.InvariantCulture,
  2610. parameters,
  2611. options.TonemappingAlgorithm,
  2612. options.TonemappingPeak,
  2613. options.TonemappingDesat,
  2614. options.TonemappingParam,
  2615. options.TonemappingRange));
  2616. if (isLibX264Encoder
  2617. || isLibX265Encoder
  2618. || hasTextSubs
  2619. || (hasGraphicalSubs && !isCudaOverlaySupported && isNvencEncoder))
  2620. {
  2621. if (isNvencEncoder)
  2622. {
  2623. isHwuploadCudaRequired = true;
  2624. }
  2625. filters.Add("hwdownload");
  2626. filters.Add("format=nv12");
  2627. }
  2628. var outputSdrParams = GetOutputSdrParams(options.TonemappingRange);
  2629. if (!string.IsNullOrEmpty(outputSdrParams))
  2630. {
  2631. filters.Add(outputSdrParams);
  2632. }
  2633. }
  2634. // Add VPP tonemapping filter for VAAPI.
  2635. // Full hardware based video post processing, faster than OpenCL but lacks fine tuning options.
  2636. if ((isTonemappingSupportedOnVaapi || isTonemappingSupportedOnQsv)
  2637. && isVppTonemappingSupported)
  2638. {
  2639. filters.Add("tonemap_vaapi=format=nv12:transfer=bt709:matrix=bt709:primaries=bt709");
  2640. }
  2641. // Another case is when using Nvenc decoder.
  2642. if (isNvdecDecoder && !isOpenclTonemappingSupported && !isCudaTonemappingSupported)
  2643. {
  2644. var codec = videoStream.Codec;
  2645. var isCudaFormatConversionSupported = _mediaEncoder.SupportsFilterWithOption(FilterOptionType.ScaleCudaFormat);
  2646. // Assert 10-bit hardware decodable
  2647. if (isColorDepth10 && (string.Equals(codec, "hevc", StringComparison.OrdinalIgnoreCase)
  2648. || string.Equals(codec, "h265", StringComparison.OrdinalIgnoreCase)
  2649. || string.Equals(codec, "vp9", StringComparison.OrdinalIgnoreCase)))
  2650. {
  2651. if (isCudaFormatConversionSupported)
  2652. {
  2653. if (isLibX264Encoder
  2654. || isLibX265Encoder
  2655. || hasTextSubs
  2656. || (hasGraphicalSubs && !isCudaOverlaySupported && isNvencEncoder))
  2657. {
  2658. if (isNvencEncoder)
  2659. {
  2660. isHwuploadCudaRequired = true;
  2661. }
  2662. filters.Add("hwdownload");
  2663. filters.Add("format=nv12");
  2664. }
  2665. }
  2666. else
  2667. {
  2668. // Download data from GPU to CPU as p010 format.
  2669. filters.Add("hwdownload");
  2670. filters.Add("format=p010");
  2671. // Cuda lacks of a pixel format converter.
  2672. if (isNvencEncoder)
  2673. {
  2674. isHwuploadCudaRequired = true;
  2675. filters.Add("format=yuv420p");
  2676. }
  2677. }
  2678. }
  2679. // Assert 8-bit hardware decodable
  2680. else if (!isColorDepth10
  2681. && (isLibX264Encoder
  2682. || isLibX265Encoder
  2683. || hasTextSubs
  2684. || (hasGraphicalSubs && !isCudaOverlaySupported && isNvencEncoder)))
  2685. {
  2686. if (isNvencEncoder)
  2687. {
  2688. isHwuploadCudaRequired = true;
  2689. }
  2690. filters.Add("hwdownload");
  2691. filters.Add("format=nv12");
  2692. }
  2693. }
  2694. // Add parameters to use VAAPI with burn-in text subtitles (GH issue #642)
  2695. if (isVaapiH264Encoder
  2696. || isVaapiHevcEncoder
  2697. || (isTonemappingSupportedOnQsv && isVppTonemappingSupported))
  2698. {
  2699. if (hasTextSubs)
  2700. {
  2701. // Convert hw context from ocl to va.
  2702. // For tonemapping and text subs burn-in.
  2703. if (isTonemappingSupportedOnVaapi && isOpenclTonemappingSupported && !isVppTonemappingSupported)
  2704. {
  2705. filters.Add("scale_vaapi");
  2706. }
  2707. // Test passed on Intel and AMD gfx
  2708. filters.Add("hwmap=mode=read+write");
  2709. filters.Add("format=nv12");
  2710. }
  2711. }
  2712. if (hasTextSubs)
  2713. {
  2714. var subParam = GetTextSubtitleParam(state);
  2715. filters.Add(subParam);
  2716. // Ensure proper filters are passed to ffmpeg in case of hardware acceleration via VA-API
  2717. // Reference: https://trac.ffmpeg.org/wiki/Hardware/VAAPI
  2718. if (isVaapiH264Encoder || isVaapiHevcEncoder)
  2719. {
  2720. filters.Add("hwmap");
  2721. }
  2722. if (isTonemappingSupportedOnQsv && isVppTonemappingSupported)
  2723. {
  2724. filters.Add("hwmap,format=vaapi");
  2725. }
  2726. if (isNvdecDecoder && isNvencEncoder)
  2727. {
  2728. isHwuploadCudaRequired = true;
  2729. }
  2730. }
  2731. // Interop the VAAPI data to QSV for hybrid tonemapping
  2732. if (isTonemappingSupportedOnQsv && isVppTonemappingSupported && !hasGraphicalSubs)
  2733. {
  2734. filters.Add("hwmap=derive_device=qsv,scale_qsv");
  2735. }
  2736. if (isHwuploadCudaRequired && !hasGraphicalSubs)
  2737. {
  2738. filters.Add("hwupload_cuda");
  2739. }
  2740. // If no tonemap filter is applied,
  2741. // tag the video range as SDR to prevent the encoder from encoding HDR video.
  2742. if (isNoTonemapFilterApplied)
  2743. {
  2744. var outputSdrParams = GetOutputSdrParams(null);
  2745. if (!string.IsNullOrEmpty(outputSdrParams))
  2746. {
  2747. filters.Add(outputSdrParams);
  2748. }
  2749. }
  2750. var output = string.Empty;
  2751. if (filters.Count > 0)
  2752. {
  2753. output += string.Format(
  2754. CultureInfo.InvariantCulture,
  2755. "{0}",
  2756. string.Join(',', filters));
  2757. }
  2758. return output;
  2759. }
  2760. public static string GetInputHdrParams(string colorTransfer)
  2761. {
  2762. if (string.Equals(colorTransfer, "arib-std-b67", StringComparison.OrdinalIgnoreCase))
  2763. {
  2764. // HLG
  2765. return "setparams=color_primaries=bt2020:color_trc=arib-std-b67:colorspace=bt2020nc";
  2766. }
  2767. else
  2768. {
  2769. // HDR10
  2770. return "setparams=color_primaries=bt2020:color_trc=smpte2084:colorspace=bt2020nc";
  2771. }
  2772. }
  2773. public static string GetOutputSdrParams(string tonemappingRange)
  2774. {
  2775. // SDR
  2776. if (string.Equals(tonemappingRange, "tv", StringComparison.OrdinalIgnoreCase))
  2777. {
  2778. return "setparams=color_primaries=bt709:color_trc=bt709:colorspace=bt709:range=tv";
  2779. }
  2780. if (string.Equals(tonemappingRange, "pc", StringComparison.OrdinalIgnoreCase))
  2781. {
  2782. return "setparams=color_primaries=bt709:color_trc=bt709:colorspace=bt709:range=pc";
  2783. }
  2784. return "setparams=color_primaries=bt709:color_trc=bt709:colorspace=bt709";
  2785. }
  2786. /// <summary>
  2787. /// Gets the number of threads.
  2788. /// </summary>
  2789. /// <param name="state">Encoding state.</param>
  2790. /// <param name="encodingOptions">Encoding options.</param>
  2791. /// <param name="outputVideoCodec">Video codec to use.</param>
  2792. /// <returns>Number of threads.</returns>
  2793. #nullable enable
  2794. public static int GetNumberOfThreads(EncodingJobInfo? state, EncodingOptions encodingOptions, string? outputVideoCodec)
  2795. {
  2796. // VP8 and VP9 encoders must have their thread counts set.
  2797. bool mustSetThreadCount = string.Equals(outputVideoCodec, "libvpx", StringComparison.OrdinalIgnoreCase)
  2798. || string.Equals(outputVideoCodec, "libvpx-vp9", StringComparison.OrdinalIgnoreCase);
  2799. var threads = state?.BaseRequest.CpuCoreLimit ?? encodingOptions.EncodingThreadCount;
  2800. if (threads <= 0)
  2801. {
  2802. // Automatically set thread count
  2803. return mustSetThreadCount ? Math.Max(Environment.ProcessorCount - 1, 1) : 0;
  2804. }
  2805. else if (threads >= Environment.ProcessorCount)
  2806. {
  2807. return Environment.ProcessorCount;
  2808. }
  2809. return threads;
  2810. }
  2811. #nullable disable
  2812. public void TryStreamCopy(EncodingJobInfo state)
  2813. {
  2814. if (state.VideoStream != null && CanStreamCopyVideo(state, state.VideoStream))
  2815. {
  2816. state.OutputVideoCodec = "copy";
  2817. }
  2818. else
  2819. {
  2820. var user = state.User;
  2821. // If the user doesn't have access to transcoding, then force stream copy, regardless of whether it will be compatible or not
  2822. if (user != null && !user.HasPermission(PermissionKind.EnableVideoPlaybackTranscoding))
  2823. {
  2824. state.OutputVideoCodec = "copy";
  2825. }
  2826. }
  2827. if (state.AudioStream != null
  2828. && CanStreamCopyAudio(state, state.AudioStream, state.SupportedAudioCodecs))
  2829. {
  2830. state.OutputAudioCodec = "copy";
  2831. }
  2832. else
  2833. {
  2834. var user = state.User;
  2835. // If the user doesn't have access to transcoding, then force stream copy, regardless of whether it will be compatible or not
  2836. if (user != null && !user.HasPermission(PermissionKind.EnableAudioPlaybackTranscoding))
  2837. {
  2838. state.OutputAudioCodec = "copy";
  2839. }
  2840. }
  2841. }
  2842. public string GetInputModifier(EncodingJobInfo state, EncodingOptions encodingOptions)
  2843. {
  2844. var inputModifier = string.Empty;
  2845. var probeSizeArgument = string.Empty;
  2846. string analyzeDurationArgument;
  2847. if (state.MediaSource.AnalyzeDurationMs.HasValue)
  2848. {
  2849. analyzeDurationArgument = "-analyzeduration " + (state.MediaSource.AnalyzeDurationMs.Value * 1000).ToString(CultureInfo.InvariantCulture);
  2850. }
  2851. else
  2852. {
  2853. analyzeDurationArgument = string.Empty;
  2854. }
  2855. if (!string.IsNullOrEmpty(probeSizeArgument))
  2856. {
  2857. inputModifier += " " + probeSizeArgument;
  2858. }
  2859. if (!string.IsNullOrEmpty(analyzeDurationArgument))
  2860. {
  2861. inputModifier += " " + analyzeDurationArgument;
  2862. }
  2863. inputModifier = inputModifier.Trim();
  2864. var userAgentParam = GetUserAgentParam(state);
  2865. if (!string.IsNullOrEmpty(userAgentParam))
  2866. {
  2867. inputModifier += " " + userAgentParam;
  2868. }
  2869. inputModifier = inputModifier.Trim();
  2870. inputModifier += " " + GetFastSeekCommandLineParameter(state.BaseRequest);
  2871. inputModifier = inputModifier.Trim();
  2872. if (state.InputProtocol == MediaProtocol.Rtsp)
  2873. {
  2874. inputModifier += " -rtsp_transport tcp -rtsp_transport udp -rtsp_flags prefer_tcp";
  2875. }
  2876. if (!string.IsNullOrEmpty(state.InputAudioSync))
  2877. {
  2878. inputModifier += " -async " + state.InputAudioSync;
  2879. }
  2880. if (!string.IsNullOrEmpty(state.InputVideoSync))
  2881. {
  2882. inputModifier += " -vsync " + state.InputVideoSync;
  2883. }
  2884. if (state.ReadInputAtNativeFramerate && state.InputProtocol != MediaProtocol.Rtsp)
  2885. {
  2886. inputModifier += " -re";
  2887. }
  2888. var flags = new List<string>();
  2889. if (state.IgnoreInputDts)
  2890. {
  2891. flags.Add("+igndts");
  2892. }
  2893. if (state.IgnoreInputIndex)
  2894. {
  2895. flags.Add("+ignidx");
  2896. }
  2897. if (state.GenPtsInput || IsCopyCodec(state.OutputVideoCodec))
  2898. {
  2899. flags.Add("+genpts");
  2900. }
  2901. if (state.DiscardCorruptFramesInput)
  2902. {
  2903. flags.Add("+discardcorrupt");
  2904. }
  2905. if (state.EnableFastSeekInput)
  2906. {
  2907. flags.Add("+fastseek");
  2908. }
  2909. if (flags.Count > 0)
  2910. {
  2911. inputModifier += " -fflags " + string.Join(string.Empty, flags);
  2912. }
  2913. var videoDecoder = GetHardwareAcceleratedVideoDecoder(state, encodingOptions);
  2914. if (!string.IsNullOrEmpty(videoDecoder))
  2915. {
  2916. inputModifier += " " + videoDecoder;
  2917. if (!IsCopyCodec(state.OutputVideoCodec)
  2918. && videoDecoder.Contains("cuvid", StringComparison.OrdinalIgnoreCase))
  2919. {
  2920. var videoStream = state.VideoStream;
  2921. var inputWidth = videoStream?.Width;
  2922. var inputHeight = videoStream?.Height;
  2923. var request = state.BaseRequest;
  2924. var (width, height) = GetFixedOutputSize(inputWidth, inputHeight, request.Width, request.Height, request.MaxWidth, request.MaxHeight);
  2925. if (videoDecoder.Contains("cuvid", StringComparison.OrdinalIgnoreCase)
  2926. && width.HasValue
  2927. && height.HasValue)
  2928. {
  2929. if (width.HasValue && height.HasValue)
  2930. {
  2931. inputModifier += string.Format(
  2932. CultureInfo.InvariantCulture,
  2933. " -resize {0}x{1}",
  2934. width.Value,
  2935. height.Value);
  2936. }
  2937. if (state.DeInterlace("h264", true))
  2938. {
  2939. inputModifier += " -deint 1";
  2940. if (!encodingOptions.DeinterlaceDoubleRate || (videoStream?.AverageFrameRate ?? 60) > 30)
  2941. {
  2942. inputModifier += " -drop_second_field 1";
  2943. }
  2944. }
  2945. }
  2946. }
  2947. }
  2948. if (state.IsVideoRequest)
  2949. {
  2950. var outputVideoCodec = GetVideoEncoder(state, encodingOptions);
  2951. // Important: If this is ever re-enabled, make sure not to use it with wtv because it breaks seeking
  2952. if (!string.Equals(state.InputContainer, "wtv", StringComparison.OrdinalIgnoreCase)
  2953. && state.TranscodingType != TranscodingJobType.Progressive
  2954. && !state.EnableBreakOnNonKeyFrames(outputVideoCodec)
  2955. && (state.BaseRequest.StartTimeTicks ?? 0) > 0)
  2956. {
  2957. inputModifier += " -noaccurate_seek";
  2958. }
  2959. if (!string.IsNullOrEmpty(state.InputContainer) && state.VideoType == VideoType.VideoFile && string.IsNullOrEmpty(encodingOptions.HardwareAccelerationType))
  2960. {
  2961. var inputFormat = GetInputFormat(state.InputContainer);
  2962. if (!string.IsNullOrEmpty(inputFormat))
  2963. {
  2964. inputModifier += " -f " + inputFormat;
  2965. }
  2966. }
  2967. }
  2968. if (state.MediaSource.RequiresLooping)
  2969. {
  2970. inputModifier += " -stream_loop -1 -reconnect_at_eof 1 -reconnect_streamed 1 -reconnect_delay_max 2";
  2971. }
  2972. return inputModifier;
  2973. }
  2974. public void AttachMediaSourceInfo(
  2975. EncodingJobInfo state,
  2976. EncodingOptions encodingOptions,
  2977. MediaSourceInfo mediaSource,
  2978. string requestedUrl)
  2979. {
  2980. if (state == null)
  2981. {
  2982. throw new ArgumentNullException(nameof(state));
  2983. }
  2984. if (mediaSource == null)
  2985. {
  2986. throw new ArgumentNullException(nameof(mediaSource));
  2987. }
  2988. var path = mediaSource.Path;
  2989. var protocol = mediaSource.Protocol;
  2990. if (!string.IsNullOrEmpty(mediaSource.EncoderPath) && mediaSource.EncoderProtocol.HasValue)
  2991. {
  2992. path = mediaSource.EncoderPath;
  2993. protocol = mediaSource.EncoderProtocol.Value;
  2994. }
  2995. state.MediaPath = path;
  2996. state.InputProtocol = protocol;
  2997. state.InputContainer = mediaSource.Container;
  2998. state.RunTimeTicks = mediaSource.RunTimeTicks;
  2999. state.RemoteHttpHeaders = mediaSource.RequiredHttpHeaders;
  3000. state.IsoType = mediaSource.IsoType;
  3001. if (mediaSource.Timestamp.HasValue)
  3002. {
  3003. state.InputTimestamp = mediaSource.Timestamp.Value;
  3004. }
  3005. state.RunTimeTicks = mediaSource.RunTimeTicks;
  3006. state.RemoteHttpHeaders = mediaSource.RequiredHttpHeaders;
  3007. state.ReadInputAtNativeFramerate = mediaSource.ReadAtNativeFramerate;
  3008. if (state.ReadInputAtNativeFramerate
  3009. || (mediaSource.Protocol == MediaProtocol.File
  3010. && string.Equals(mediaSource.Container, "wtv", StringComparison.OrdinalIgnoreCase)))
  3011. {
  3012. state.InputVideoSync = "-1";
  3013. state.InputAudioSync = "1";
  3014. }
  3015. if (string.Equals(mediaSource.Container, "wma", StringComparison.OrdinalIgnoreCase)
  3016. || string.Equals(mediaSource.Container, "asf", StringComparison.OrdinalIgnoreCase))
  3017. {
  3018. // Seeing some stuttering when transcoding wma to audio-only HLS
  3019. state.InputAudioSync = "1";
  3020. }
  3021. var mediaStreams = mediaSource.MediaStreams;
  3022. if (state.IsVideoRequest)
  3023. {
  3024. var videoRequest = state.BaseRequest;
  3025. if (string.IsNullOrEmpty(videoRequest.VideoCodec))
  3026. {
  3027. if (string.IsNullOrEmpty(requestedUrl))
  3028. {
  3029. requestedUrl = "test." + videoRequest.Container;
  3030. }
  3031. videoRequest.VideoCodec = InferVideoCodec(requestedUrl);
  3032. }
  3033. state.VideoStream = GetMediaStream(mediaStreams, videoRequest.VideoStreamIndex, MediaStreamType.Video);
  3034. state.SubtitleStream = GetMediaStream(mediaStreams, videoRequest.SubtitleStreamIndex, MediaStreamType.Subtitle, false);
  3035. state.SubtitleDeliveryMethod = videoRequest.SubtitleMethod;
  3036. state.AudioStream = GetMediaStream(mediaStreams, videoRequest.AudioStreamIndex, MediaStreamType.Audio);
  3037. if (state.SubtitleStream != null && !state.SubtitleStream.IsExternal)
  3038. {
  3039. state.InternalSubtitleStreamOffset = mediaStreams.Where(i => i.Type == MediaStreamType.Subtitle && !i.IsExternal).ToList().IndexOf(state.SubtitleStream);
  3040. }
  3041. EnforceResolutionLimit(state);
  3042. NormalizeSubtitleEmbed(state);
  3043. }
  3044. else
  3045. {
  3046. state.AudioStream = GetMediaStream(mediaStreams, null, MediaStreamType.Audio, true);
  3047. }
  3048. state.MediaSource = mediaSource;
  3049. var request = state.BaseRequest;
  3050. var supportedAudioCodecs = state.SupportedAudioCodecs;
  3051. if (request != null && supportedAudioCodecs != null && supportedAudioCodecs.Length > 0)
  3052. {
  3053. var supportedAudioCodecsList = supportedAudioCodecs.ToList();
  3054. ShiftAudioCodecsIfNeeded(supportedAudioCodecsList, state.AudioStream);
  3055. state.SupportedAudioCodecs = supportedAudioCodecsList.ToArray();
  3056. request.AudioCodec = state.SupportedAudioCodecs.FirstOrDefault(i => _mediaEncoder.CanEncodeToAudioCodec(i))
  3057. ?? state.SupportedAudioCodecs.FirstOrDefault();
  3058. }
  3059. var supportedVideoCodecs = state.SupportedVideoCodecs;
  3060. if (request != null && supportedVideoCodecs != null && supportedVideoCodecs.Length > 0)
  3061. {
  3062. var supportedVideoCodecsList = supportedVideoCodecs.ToList();
  3063. ShiftVideoCodecsIfNeeded(supportedVideoCodecsList, encodingOptions);
  3064. state.SupportedVideoCodecs = supportedVideoCodecsList.ToArray();
  3065. request.VideoCodec = state.SupportedVideoCodecs.FirstOrDefault();
  3066. }
  3067. }
  3068. private void ShiftAudioCodecsIfNeeded(List<string> audioCodecs, MediaStream audioStream)
  3069. {
  3070. // No need to shift if there is only one supported audio codec.
  3071. if (audioCodecs.Count < 2)
  3072. {
  3073. return;
  3074. }
  3075. var inputChannels = audioStream == null ? 6 : audioStream.Channels ?? 6;
  3076. if (inputChannels >= 6)
  3077. {
  3078. return;
  3079. }
  3080. // Transcoding to 2ch ac3 almost always causes a playback failure
  3081. // Keep it in the supported codecs list, but shift it to the end of the list so that if transcoding happens, another codec is used
  3082. var shiftAudioCodecs = new[] { "ac3", "eac3" };
  3083. if (audioCodecs.All(i => shiftAudioCodecs.Contains(i, StringComparer.OrdinalIgnoreCase)))
  3084. {
  3085. return;
  3086. }
  3087. while (shiftAudioCodecs.Contains(audioCodecs[0], StringComparer.OrdinalIgnoreCase))
  3088. {
  3089. var removed = shiftAudioCodecs[0];
  3090. audioCodecs.RemoveAt(0);
  3091. audioCodecs.Add(removed);
  3092. }
  3093. }
  3094. private void ShiftVideoCodecsIfNeeded(List<string> videoCodecs, EncodingOptions encodingOptions)
  3095. {
  3096. // Shift hevc/h265 to the end of list if hevc encoding is not allowed.
  3097. if (encodingOptions.AllowHevcEncoding)
  3098. {
  3099. return;
  3100. }
  3101. // No need to shift if there is only one supported video codec.
  3102. if (videoCodecs.Count < 2)
  3103. {
  3104. return;
  3105. }
  3106. var shiftVideoCodecs = new[] { "hevc", "h265" };
  3107. if (videoCodecs.All(i => shiftVideoCodecs.Contains(i, StringComparer.OrdinalIgnoreCase)))
  3108. {
  3109. return;
  3110. }
  3111. while (shiftVideoCodecs.Contains(videoCodecs[0], StringComparer.OrdinalIgnoreCase))
  3112. {
  3113. var removed = shiftVideoCodecs[0];
  3114. videoCodecs.RemoveAt(0);
  3115. videoCodecs.Add(removed);
  3116. }
  3117. }
  3118. private void NormalizeSubtitleEmbed(EncodingJobInfo state)
  3119. {
  3120. if (state.SubtitleStream == null || state.SubtitleDeliveryMethod != SubtitleDeliveryMethod.Embed)
  3121. {
  3122. return;
  3123. }
  3124. // This is tricky to remux in, after converting to dvdsub it's not positioned correctly
  3125. // Therefore, let's just burn it in
  3126. if (string.Equals(state.SubtitleStream.Codec, "DVBSUB", StringComparison.OrdinalIgnoreCase))
  3127. {
  3128. state.SubtitleDeliveryMethod = SubtitleDeliveryMethod.Encode;
  3129. }
  3130. }
  3131. /// <summary>
  3132. /// Gets the ffmpeg option string for the hardware accelerated video decoder.
  3133. /// </summary>
  3134. /// <param name="state">The encoding job info.</param>
  3135. /// <param name="encodingOptions">The encoding options.</param>
  3136. /// <returns>The option string or null if none available.</returns>
  3137. protected string GetHardwareAcceleratedVideoDecoder(EncodingJobInfo state, EncodingOptions encodingOptions)
  3138. {
  3139. var videoStream = state.VideoStream;
  3140. if (videoStream == null)
  3141. {
  3142. return null;
  3143. }
  3144. var videoType = state.MediaSource.VideoType ?? VideoType.VideoFile;
  3145. // Only use alternative encoders for video files.
  3146. // When using concat with folder rips, if the mfx session fails to initialize, ffmpeg will be stuck retrying and will not exit gracefully
  3147. // Since transcoding of folder rips is experimental anyway, it's not worth adding additional variables such as this.
  3148. if (videoType != VideoType.VideoFile)
  3149. {
  3150. return null;
  3151. }
  3152. if (IsCopyCodec(state.OutputVideoCodec))
  3153. {
  3154. return null;
  3155. }
  3156. if (!string.IsNullOrEmpty(videoStream.Codec) && !string.IsNullOrEmpty(encodingOptions.HardwareAccelerationType))
  3157. {
  3158. var isColorDepth10 = IsColorDepth10(state);
  3159. // Only hevc and vp9 formats have 10-bit hardware decoder support now.
  3160. if (isColorDepth10 && !(string.Equals(videoStream.Codec, "hevc", StringComparison.OrdinalIgnoreCase)
  3161. || string.Equals(videoStream.Codec, "h265", StringComparison.OrdinalIgnoreCase)
  3162. || string.Equals(videoStream.Codec, "vp9", StringComparison.OrdinalIgnoreCase)))
  3163. {
  3164. return null;
  3165. }
  3166. // Hybrid VPP tonemapping with VAAPI
  3167. if (string.Equals(encodingOptions.HardwareAccelerationType, "qsv", StringComparison.OrdinalIgnoreCase)
  3168. && IsVppTonemappingSupported(state, encodingOptions))
  3169. {
  3170. var outputVideoCodec = GetVideoEncoder(state, encodingOptions) ?? string.Empty;
  3171. var isQsvEncoder = outputVideoCodec.Contains("qsv", StringComparison.OrdinalIgnoreCase);
  3172. if (isQsvEncoder)
  3173. {
  3174. // Since tonemap_vaapi only support HEVC for now, no need to check the codec again.
  3175. return GetHwaccelType(state, encodingOptions, "hevc", isColorDepth10);
  3176. }
  3177. }
  3178. if (string.Equals(encodingOptions.HardwareAccelerationType, "qsv", StringComparison.OrdinalIgnoreCase))
  3179. {
  3180. switch (videoStream.Codec.ToLowerInvariant())
  3181. {
  3182. case "avc":
  3183. case "h264":
  3184. return GetHwDecoderName(encodingOptions, "h264_qsv", "h264", isColorDepth10);
  3185. case "hevc":
  3186. case "h265":
  3187. return GetHwDecoderName(encodingOptions, "hevc_qsv", "hevc", isColorDepth10);
  3188. case "mpeg2video":
  3189. return GetHwDecoderName(encodingOptions, "mpeg2_qsv", "mpeg2video", isColorDepth10);
  3190. case "vc1":
  3191. return GetHwDecoderName(encodingOptions, "vc1_qsv", "vc1", isColorDepth10);
  3192. case "vp8":
  3193. return GetHwDecoderName(encodingOptions, "vp8_qsv", "vp8", isColorDepth10);
  3194. case "vp9":
  3195. return GetHwDecoderName(encodingOptions, "vp9_qsv", "vp9", isColorDepth10);
  3196. }
  3197. }
  3198. else if (string.Equals(encodingOptions.HardwareAccelerationType, "nvenc", StringComparison.OrdinalIgnoreCase))
  3199. {
  3200. switch (videoStream.Codec.ToLowerInvariant())
  3201. {
  3202. case "avc":
  3203. case "h264":
  3204. return encodingOptions.EnableEnhancedNvdecDecoder && IsCudaSupported()
  3205. ? GetHwaccelType(state, encodingOptions, "h264", isColorDepth10)
  3206. : GetHwDecoderName(encodingOptions, "h264_cuvid", "h264", isColorDepth10);
  3207. case "hevc":
  3208. case "h265":
  3209. return encodingOptions.EnableEnhancedNvdecDecoder && IsCudaSupported()
  3210. ? GetHwaccelType(state, encodingOptions, "hevc", isColorDepth10)
  3211. : GetHwDecoderName(encodingOptions, "hevc_cuvid", "hevc", isColorDepth10);
  3212. case "mpeg2video":
  3213. return encodingOptions.EnableEnhancedNvdecDecoder && IsCudaSupported()
  3214. ? GetHwaccelType(state, encodingOptions, "mpeg2video", isColorDepth10)
  3215. : GetHwDecoderName(encodingOptions, "mpeg2_cuvid", "mpeg2video", isColorDepth10);
  3216. case "vc1":
  3217. return encodingOptions.EnableEnhancedNvdecDecoder && IsCudaSupported()
  3218. ? GetHwaccelType(state, encodingOptions, "vc1", isColorDepth10)
  3219. : GetHwDecoderName(encodingOptions, "vc1_cuvid", "vc1", isColorDepth10);
  3220. case "mpeg4":
  3221. return encodingOptions.EnableEnhancedNvdecDecoder && IsCudaSupported()
  3222. ? GetHwaccelType(state, encodingOptions, "mpeg4", isColorDepth10)
  3223. : GetHwDecoderName(encodingOptions, "mpeg4_cuvid", "mpeg4", isColorDepth10);
  3224. case "vp8":
  3225. return encodingOptions.EnableEnhancedNvdecDecoder && IsCudaSupported()
  3226. ? GetHwaccelType(state, encodingOptions, "vp8", isColorDepth10)
  3227. : GetHwDecoderName(encodingOptions, "vp8_cuvid", "vp8", isColorDepth10);
  3228. case "vp9":
  3229. return encodingOptions.EnableEnhancedNvdecDecoder && IsCudaSupported()
  3230. ? GetHwaccelType(state, encodingOptions, "vp9", isColorDepth10)
  3231. : GetHwDecoderName(encodingOptions, "vp9_cuvid", "vp9", isColorDepth10);
  3232. }
  3233. }
  3234. else if (string.Equals(encodingOptions.HardwareAccelerationType, "mediacodec", StringComparison.OrdinalIgnoreCase))
  3235. {
  3236. switch (videoStream.Codec.ToLowerInvariant())
  3237. {
  3238. case "avc":
  3239. case "h264":
  3240. return GetHwDecoderName(encodingOptions, "h264_mediacodec", "h264", isColorDepth10);
  3241. case "hevc":
  3242. case "h265":
  3243. return GetHwDecoderName(encodingOptions, "hevc_mediacodec", "hevc", isColorDepth10);
  3244. case "mpeg2video":
  3245. return GetHwDecoderName(encodingOptions, "mpeg2_mediacodec", "mpeg2video", isColorDepth10);
  3246. case "mpeg4":
  3247. return GetHwDecoderName(encodingOptions, "mpeg4_mediacodec", "mpeg4", isColorDepth10);
  3248. case "vp8":
  3249. return GetHwDecoderName(encodingOptions, "vp8_mediacodec", "vp8", isColorDepth10);
  3250. case "vp9":
  3251. return GetHwDecoderName(encodingOptions, "vp9_mediacodec", "vp9", isColorDepth10);
  3252. }
  3253. }
  3254. else if (string.Equals(encodingOptions.HardwareAccelerationType, "omx", StringComparison.OrdinalIgnoreCase))
  3255. {
  3256. switch (videoStream.Codec.ToLowerInvariant())
  3257. {
  3258. case "avc":
  3259. case "h264":
  3260. return GetHwDecoderName(encodingOptions, "h264_mmal", "h264", isColorDepth10);
  3261. case "mpeg2video":
  3262. return GetHwDecoderName(encodingOptions, "mpeg2_mmal", "mpeg2video", isColorDepth10);
  3263. case "mpeg4":
  3264. return GetHwDecoderName(encodingOptions, "mpeg4_mmal", "mpeg4", isColorDepth10);
  3265. case "vc1":
  3266. return GetHwDecoderName(encodingOptions, "vc1_mmal", "vc1", isColorDepth10);
  3267. }
  3268. }
  3269. else if (string.Equals(encodingOptions.HardwareAccelerationType, "amf", StringComparison.OrdinalIgnoreCase))
  3270. {
  3271. switch (videoStream.Codec.ToLowerInvariant())
  3272. {
  3273. case "avc":
  3274. case "h264":
  3275. return GetHwaccelType(state, encodingOptions, "h264", isColorDepth10);
  3276. case "hevc":
  3277. case "h265":
  3278. return GetHwaccelType(state, encodingOptions, "hevc", isColorDepth10);
  3279. case "mpeg2video":
  3280. return GetHwaccelType(state, encodingOptions, "mpeg2video", isColorDepth10);
  3281. case "vc1":
  3282. return GetHwaccelType(state, encodingOptions, "vc1", isColorDepth10);
  3283. case "mpeg4":
  3284. return GetHwaccelType(state, encodingOptions, "mpeg4", isColorDepth10);
  3285. case "vp9":
  3286. return GetHwaccelType(state, encodingOptions, "vp9", isColorDepth10);
  3287. }
  3288. }
  3289. else if (string.Equals(encodingOptions.HardwareAccelerationType, "vaapi", StringComparison.OrdinalIgnoreCase))
  3290. {
  3291. switch (videoStream.Codec.ToLowerInvariant())
  3292. {
  3293. case "avc":
  3294. case "h264":
  3295. return GetHwaccelType(state, encodingOptions, "h264", isColorDepth10);
  3296. case "hevc":
  3297. case "h265":
  3298. return GetHwaccelType(state, encodingOptions, "hevc", isColorDepth10);
  3299. case "mpeg2video":
  3300. return GetHwaccelType(state, encodingOptions, "mpeg2video", isColorDepth10);
  3301. case "vc1":
  3302. return GetHwaccelType(state, encodingOptions, "vc1", isColorDepth10);
  3303. case "vp8":
  3304. return GetHwaccelType(state, encodingOptions, "vp8", isColorDepth10);
  3305. case "vp9":
  3306. return GetHwaccelType(state, encodingOptions, "vp9", isColorDepth10);
  3307. }
  3308. }
  3309. else if (string.Equals(encodingOptions.HardwareAccelerationType, "videotoolbox", StringComparison.OrdinalIgnoreCase))
  3310. {
  3311. switch (videoStream.Codec.ToLowerInvariant())
  3312. {
  3313. case "avc":
  3314. case "h264":
  3315. return GetHwDecoderName(encodingOptions, "h264_opencl", "h264", isColorDepth10);
  3316. case "hevc":
  3317. case "h265":
  3318. return GetHwDecoderName(encodingOptions, "hevc_opencl", "hevc", isColorDepth10);
  3319. case "mpeg2video":
  3320. return GetHwDecoderName(encodingOptions, "mpeg2_opencl", "mpeg2video", isColorDepth10);
  3321. case "mpeg4":
  3322. return GetHwDecoderName(encodingOptions, "mpeg4_opencl", "mpeg4", isColorDepth10);
  3323. case "vc1":
  3324. return GetHwDecoderName(encodingOptions, "vc1_opencl", "vc1", isColorDepth10);
  3325. case "vp8":
  3326. return GetHwDecoderName(encodingOptions, "vp8_opencl", "vp8", isColorDepth10);
  3327. case "vp9":
  3328. return GetHwDecoderName(encodingOptions, "vp9_opencl", "vp9", isColorDepth10);
  3329. }
  3330. }
  3331. }
  3332. var whichCodec = videoStream.Codec?.ToLowerInvariant();
  3333. switch (whichCodec)
  3334. {
  3335. case "avc":
  3336. whichCodec = "h264";
  3337. break;
  3338. case "h265":
  3339. whichCodec = "hevc";
  3340. break;
  3341. }
  3342. // Avoid a second attempt if no hardware acceleration is being used
  3343. encodingOptions.HardwareDecodingCodecs = encodingOptions.HardwareDecodingCodecs.Where(val => val != whichCodec).ToArray();
  3344. // leave blank so ffmpeg will decide
  3345. return null;
  3346. }
  3347. /// <summary>
  3348. /// Gets a hw decoder name.
  3349. /// </summary>
  3350. /// <param name="options">Encoding options.</param>
  3351. /// <param name="decoder">Decoder to use.</param>
  3352. /// <param name="videoCodec">Video codec to use.</param>
  3353. /// <param name="isColorDepth10">Specifies if color depth 10.</param>
  3354. /// <returns>Hardware decoder name.</returns>
  3355. public string GetHwDecoderName(EncodingOptions options, string decoder, string videoCodec, bool isColorDepth10)
  3356. {
  3357. var isCodecAvailable = _mediaEncoder.SupportsDecoder(decoder) && options.HardwareDecodingCodecs.Contains(videoCodec, StringComparer.OrdinalIgnoreCase);
  3358. if (isColorDepth10 && isCodecAvailable)
  3359. {
  3360. if ((options.HardwareDecodingCodecs.Contains("hevc", StringComparer.OrdinalIgnoreCase) && !options.EnableDecodingColorDepth10Hevc)
  3361. || (options.HardwareDecodingCodecs.Contains("vp9", StringComparer.OrdinalIgnoreCase) && !options.EnableDecodingColorDepth10Vp9))
  3362. {
  3363. return null;
  3364. }
  3365. }
  3366. return isCodecAvailable ? ("-c:v " + decoder) : null;
  3367. }
  3368. /// <summary>
  3369. /// Gets a hwaccel type to use as a hardware decoder(dxva/vaapi) depending on the system.
  3370. /// </summary>
  3371. /// <param name="state">Encoding state.</param>
  3372. /// <param name="options">Encoding options.</param>
  3373. /// <param name="videoCodec">Video codec to use.</param>
  3374. /// <param name="isColorDepth10">Specifies if color depth 10.</param>
  3375. /// <returns>Hardware accelerator type.</returns>
  3376. public string GetHwaccelType(EncodingJobInfo state, EncodingOptions options, string videoCodec, bool isColorDepth10)
  3377. {
  3378. var isWindows = OperatingSystem.IsWindows();
  3379. var isLinux = OperatingSystem.IsLinux();
  3380. var isWindows8orLater = Environment.OSVersion.Version.Major > 6 || (Environment.OSVersion.Version.Major == 6 && Environment.OSVersion.Version.Minor > 1);
  3381. var isDxvaSupported = _mediaEncoder.SupportsHwaccel("dxva2") || _mediaEncoder.SupportsHwaccel("d3d11va");
  3382. var isCodecAvailable = options.HardwareDecodingCodecs.Contains(videoCodec, StringComparer.OrdinalIgnoreCase);
  3383. if (isColorDepth10 && isCodecAvailable)
  3384. {
  3385. if ((options.HardwareDecodingCodecs.Contains("hevc", StringComparer.OrdinalIgnoreCase) && !options.EnableDecodingColorDepth10Hevc)
  3386. || (options.HardwareDecodingCodecs.Contains("vp9", StringComparer.OrdinalIgnoreCase) && !options.EnableDecodingColorDepth10Vp9))
  3387. {
  3388. return null;
  3389. }
  3390. }
  3391. if (string.Equals(options.HardwareAccelerationType, "amf", StringComparison.OrdinalIgnoreCase))
  3392. {
  3393. // Currently there is no AMF decoder on Linux, only have h264 encoder.
  3394. if (isDxvaSupported && options.HardwareDecodingCodecs.Contains(videoCodec, StringComparer.OrdinalIgnoreCase))
  3395. {
  3396. if (isWindows && isWindows8orLater)
  3397. {
  3398. return "-hwaccel d3d11va";
  3399. }
  3400. if (isWindows && !isWindows8orLater)
  3401. {
  3402. return "-hwaccel dxva2";
  3403. }
  3404. }
  3405. }
  3406. if (string.Equals(options.HardwareAccelerationType, "vaapi", StringComparison.OrdinalIgnoreCase)
  3407. || (string.Equals(options.HardwareAccelerationType, "qsv", StringComparison.OrdinalIgnoreCase)
  3408. && IsVppTonemappingSupported(state, options)))
  3409. {
  3410. if (IsVaapiSupported(state) && options.HardwareDecodingCodecs.Contains(videoCodec, StringComparer.OrdinalIgnoreCase))
  3411. {
  3412. if (isLinux)
  3413. {
  3414. return "-hwaccel vaapi";
  3415. }
  3416. }
  3417. }
  3418. if (string.Equals(options.HardwareAccelerationType, "nvenc", StringComparison.OrdinalIgnoreCase))
  3419. {
  3420. if (options.HardwareDecodingCodecs.Contains(videoCodec, StringComparer.OrdinalIgnoreCase))
  3421. {
  3422. return "-hwaccel cuda";
  3423. }
  3424. }
  3425. return null;
  3426. }
  3427. public string GetSubtitleEmbedArguments(EncodingJobInfo state)
  3428. {
  3429. if (state.SubtitleStream == null || state.SubtitleDeliveryMethod != SubtitleDeliveryMethod.Embed)
  3430. {
  3431. return string.Empty;
  3432. }
  3433. var format = state.SupportedSubtitleCodecs.FirstOrDefault();
  3434. string codec;
  3435. if (string.IsNullOrEmpty(format) || string.Equals(format, state.SubtitleStream.Codec, StringComparison.OrdinalIgnoreCase))
  3436. {
  3437. codec = "copy";
  3438. }
  3439. else
  3440. {
  3441. codec = format;
  3442. }
  3443. return " -codec:s:0 " + codec + " -disposition:s:0 default";
  3444. }
  3445. public string GetProgressiveVideoFullCommandLine(EncodingJobInfo state, EncodingOptions encodingOptions, string outputPath, string defaultPreset)
  3446. {
  3447. // Get the output codec name
  3448. var videoCodec = GetVideoEncoder(state, encodingOptions);
  3449. var format = string.Empty;
  3450. var keyFrame = string.Empty;
  3451. if (string.Equals(Path.GetExtension(outputPath), ".mp4", StringComparison.OrdinalIgnoreCase)
  3452. && state.BaseRequest.Context == EncodingContext.Streaming)
  3453. {
  3454. // Comparison: https://github.com/jansmolders86/mediacenterjs/blob/master/lib/transcoding/desktop.js
  3455. format = " -f mp4 -movflags frag_keyframe+empty_moov";
  3456. }
  3457. var threads = GetNumberOfThreads(state, encodingOptions, videoCodec);
  3458. var inputModifier = GetInputModifier(state, encodingOptions);
  3459. return string.Format(
  3460. CultureInfo.InvariantCulture,
  3461. "{0} {1}{2} {3} {4} -map_metadata -1 -map_chapters -1 -threads {5} {6}{7}{8} -y \"{9}\"",
  3462. inputModifier,
  3463. GetInputArgument(state, encodingOptions),
  3464. keyFrame,
  3465. GetMapArgs(state),
  3466. GetProgressiveVideoArguments(state, encodingOptions, videoCodec, defaultPreset),
  3467. threads,
  3468. GetProgressiveVideoAudioArguments(state, encodingOptions),
  3469. GetSubtitleEmbedArguments(state),
  3470. format,
  3471. outputPath).Trim();
  3472. }
  3473. public string GetOutputFFlags(EncodingJobInfo state)
  3474. {
  3475. var flags = new List<string>();
  3476. if (state.GenPtsOutput)
  3477. {
  3478. flags.Add("+genpts");
  3479. }
  3480. if (flags.Count > 0)
  3481. {
  3482. return " -fflags " + string.Join(string.Empty, flags);
  3483. }
  3484. return string.Empty;
  3485. }
  3486. public string GetProgressiveVideoArguments(EncodingJobInfo state, EncodingOptions encodingOptions, string videoCodec, string defaultPreset)
  3487. {
  3488. var args = "-codec:v:0 " + videoCodec;
  3489. if (state.BaseRequest.EnableMpegtsM2TsMode)
  3490. {
  3491. args += " -mpegts_m2ts_mode 1";
  3492. }
  3493. if (IsCopyCodec(videoCodec))
  3494. {
  3495. if (state.VideoStream != null
  3496. && string.Equals(state.OutputContainer, "ts", StringComparison.OrdinalIgnoreCase)
  3497. && !string.Equals(state.VideoStream.NalLengthSize, "0", StringComparison.OrdinalIgnoreCase))
  3498. {
  3499. string bitStreamArgs = GetBitStreamArgs(state.VideoStream);
  3500. if (!string.IsNullOrEmpty(bitStreamArgs))
  3501. {
  3502. args += " " + bitStreamArgs;
  3503. }
  3504. }
  3505. if (state.RunTimeTicks.HasValue && state.BaseRequest.CopyTimestamps)
  3506. {
  3507. args += " -copyts -avoid_negative_ts disabled -start_at_zero";
  3508. }
  3509. if (!state.RunTimeTicks.HasValue)
  3510. {
  3511. args += " -fflags +genpts";
  3512. }
  3513. }
  3514. else
  3515. {
  3516. var keyFrameArg = string.Format(
  3517. CultureInfo.InvariantCulture,
  3518. " -force_key_frames \"expr:gte(t,n_forced*{0})\"",
  3519. 5);
  3520. args += keyFrameArg;
  3521. var hasGraphicalSubs = state.SubtitleStream != null && !state.SubtitleStream.IsTextSubtitleStream && state.SubtitleDeliveryMethod == SubtitleDeliveryMethod.Encode;
  3522. var hasCopyTs = false;
  3523. // Add resolution params, if specified
  3524. if (!hasGraphicalSubs)
  3525. {
  3526. var outputSizeParam = GetOutputSizeParam(state, encodingOptions, videoCodec);
  3527. args += outputSizeParam;
  3528. hasCopyTs = outputSizeParam.IndexOf("copyts", StringComparison.OrdinalIgnoreCase) != -1;
  3529. }
  3530. // This is for graphical subs
  3531. if (hasGraphicalSubs)
  3532. {
  3533. var graphicalSubtitleParam = GetGraphicalSubtitleParam(state, encodingOptions, videoCodec);
  3534. args += graphicalSubtitleParam;
  3535. hasCopyTs = graphicalSubtitleParam.IndexOf("copyts", StringComparison.OrdinalIgnoreCase) != -1;
  3536. }
  3537. if (state.RunTimeTicks.HasValue && state.BaseRequest.CopyTimestamps)
  3538. {
  3539. if (!hasCopyTs)
  3540. {
  3541. args += " -copyts";
  3542. }
  3543. args += " -avoid_negative_ts disabled";
  3544. if (!(state.SubtitleStream != null && state.SubtitleStream.IsExternal && !state.SubtitleStream.IsTextSubtitleStream))
  3545. {
  3546. args += " -start_at_zero";
  3547. }
  3548. }
  3549. var qualityParam = GetVideoQualityParam(state, videoCodec, encodingOptions, defaultPreset);
  3550. if (!string.IsNullOrEmpty(qualityParam))
  3551. {
  3552. args += " " + qualityParam.Trim();
  3553. }
  3554. }
  3555. if (!string.IsNullOrEmpty(state.OutputVideoSync))
  3556. {
  3557. args += " -vsync " + state.OutputVideoSync;
  3558. }
  3559. args += GetOutputFFlags(state);
  3560. return args;
  3561. }
  3562. public string GetProgressiveVideoAudioArguments(EncodingJobInfo state, EncodingOptions encodingOptions)
  3563. {
  3564. // If the video doesn't have an audio stream, return a default.
  3565. if (state.AudioStream == null && state.VideoStream != null)
  3566. {
  3567. return string.Empty;
  3568. }
  3569. // Get the output codec name
  3570. var codec = GetAudioEncoder(state);
  3571. var args = "-codec:a:0 " + codec;
  3572. if (IsCopyCodec(codec))
  3573. {
  3574. return args;
  3575. }
  3576. // Add the number of audio channels
  3577. var channels = state.OutputAudioChannels;
  3578. if (channels.HasValue)
  3579. {
  3580. args += " -ac " + channels.Value;
  3581. }
  3582. var bitrate = state.OutputAudioBitrate;
  3583. if (bitrate.HasValue)
  3584. {
  3585. args += " -ab " + bitrate.Value.ToString(CultureInfo.InvariantCulture);
  3586. }
  3587. if (state.OutputAudioSampleRate.HasValue)
  3588. {
  3589. args += " -ar " + state.OutputAudioSampleRate.Value.ToString(CultureInfo.InvariantCulture);
  3590. }
  3591. args += GetAudioFilterParam(state, encodingOptions);
  3592. return args;
  3593. }
  3594. public string GetProgressiveAudioFullCommandLine(EncodingJobInfo state, EncodingOptions encodingOptions, string outputPath)
  3595. {
  3596. var audioTranscodeParams = new List<string>();
  3597. var bitrate = state.OutputAudioBitrate;
  3598. if (bitrate.HasValue)
  3599. {
  3600. audioTranscodeParams.Add("-ab " + bitrate.Value.ToString(CultureInfo.InvariantCulture));
  3601. }
  3602. if (state.OutputAudioChannels.HasValue)
  3603. {
  3604. audioTranscodeParams.Add("-ac " + state.OutputAudioChannels.Value.ToString(CultureInfo.InvariantCulture));
  3605. }
  3606. // opus will fail on 44100
  3607. if (!string.Equals(state.OutputAudioCodec, "opus", StringComparison.OrdinalIgnoreCase))
  3608. {
  3609. if (state.OutputAudioSampleRate.HasValue)
  3610. {
  3611. audioTranscodeParams.Add("-ar " + state.OutputAudioSampleRate.Value.ToString(CultureInfo.InvariantCulture));
  3612. }
  3613. }
  3614. var threads = GetNumberOfThreads(state, encodingOptions, null);
  3615. var inputModifier = GetInputModifier(state, encodingOptions);
  3616. return string.Format(
  3617. CultureInfo.InvariantCulture,
  3618. "{0} {1}{7}{8} -threads {2}{3} {4} -id3v2_version 3 -write_id3v1 1{6} -y \"{5}\"",
  3619. inputModifier,
  3620. GetInputArgument(state, encodingOptions),
  3621. threads,
  3622. " -vn",
  3623. string.Join(' ', audioTranscodeParams),
  3624. outputPath,
  3625. string.Empty,
  3626. string.Empty,
  3627. string.Empty).Trim();
  3628. }
  3629. public static bool IsCopyCodec(string codec)
  3630. {
  3631. return string.Equals(codec, "copy", StringComparison.OrdinalIgnoreCase);
  3632. }
  3633. public static bool IsColorDepth10(EncodingJobInfo state)
  3634. {
  3635. var result = false;
  3636. var videoStream = state.VideoStream;
  3637. if (videoStream != null)
  3638. {
  3639. if (videoStream.BitDepth.HasValue)
  3640. {
  3641. return videoStream.BitDepth.Value == 10;
  3642. }
  3643. if (!string.IsNullOrEmpty(videoStream.PixelFormat))
  3644. {
  3645. result = videoStream.PixelFormat.Contains("p10", StringComparison.OrdinalIgnoreCase);
  3646. if (result)
  3647. {
  3648. return true;
  3649. }
  3650. }
  3651. if (!string.IsNullOrEmpty(videoStream.Profile))
  3652. {
  3653. result = videoStream.Profile.Contains("Main 10", StringComparison.OrdinalIgnoreCase)
  3654. || videoStream.Profile.Contains("High 10", StringComparison.OrdinalIgnoreCase)
  3655. || videoStream.Profile.Contains("Profile 2", StringComparison.OrdinalIgnoreCase);
  3656. if (result)
  3657. {
  3658. return true;
  3659. }
  3660. }
  3661. }
  3662. return result;
  3663. }
  3664. }
  3665. }