EncodingHelper.cs 163 KB

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