EncodingHelper.cs 166 KB

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