EncodingHelper.cs 137 KB

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