EncodingHelper.cs 142 KB

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