EncodingHelper.cs 149 KB

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