EncodingHelper.cs 175 KB

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