EncodingHelper.cs 158 KB

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