EncodingHelper.cs 134 KB

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