EncodingHelper.cs 144 KB

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